babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916
  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. var ToGammaSpace = 1 / 2.2;
  10. var 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, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, 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, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. // Temporary pre-allocated objects for engine internal use
  2955. // usage in any internal function :
  2956. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2957. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2958. var Tmp = (function () {
  2959. function Tmp() {
  2960. }
  2961. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2962. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2963. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  2964. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2965. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2966. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2967. Matrix.Zero(), Matrix.Zero(),
  2968. Matrix.Zero(), Matrix.Zero(),
  2969. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2970. return Tmp;
  2971. })();
  2972. BABYLON.Tmp = Tmp;
  2973. })(BABYLON || (BABYLON = {}));
  2974. var BABYLON;
  2975. (function (BABYLON) {
  2976. var Database = (function () {
  2977. function Database(urlToScene, callbackManifestChecked) {
  2978. // Handling various flavors of prefixed version of IndexedDB
  2979. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2980. this.callbackManifestChecked = callbackManifestChecked;
  2981. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2982. this.db = null;
  2983. this.enableSceneOffline = false;
  2984. this.enableTexturesOffline = false;
  2985. this.manifestVersionFound = 0;
  2986. this.mustUpdateRessources = false;
  2987. this.hasReachedQuota = false;
  2988. if (!Database.IDBStorageEnabled) {
  2989. this.callbackManifestChecked(true);
  2990. }
  2991. else {
  2992. this.checkManifestFile();
  2993. }
  2994. }
  2995. Database.prototype.checkManifestFile = function () {
  2996. var _this = this;
  2997. function noManifestFile() {
  2998. that.enableSceneOffline = false;
  2999. that.enableTexturesOffline = false;
  3000. that.callbackManifestChecked(false);
  3001. }
  3002. var that = this;
  3003. var manifestURL = this.currentSceneUrl + ".manifest";
  3004. var xhr = new XMLHttpRequest();
  3005. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3006. xhr.open("GET", manifestURLTimeStamped, true);
  3007. xhr.addEventListener("load", function () {
  3008. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3009. try {
  3010. var manifestFile = JSON.parse(xhr.response);
  3011. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3012. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3013. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3014. _this.manifestVersionFound = manifestFile.version;
  3015. }
  3016. if (_this.callbackManifestChecked) {
  3017. _this.callbackManifestChecked(true);
  3018. }
  3019. }
  3020. catch (ex) {
  3021. noManifestFile();
  3022. }
  3023. }
  3024. else {
  3025. noManifestFile();
  3026. }
  3027. }, false);
  3028. xhr.addEventListener("error", function (event) {
  3029. noManifestFile();
  3030. }, false);
  3031. try {
  3032. xhr.send();
  3033. }
  3034. catch (ex) {
  3035. BABYLON.Tools.Error("Error on XHR send request.");
  3036. that.callbackManifestChecked(false);
  3037. }
  3038. };
  3039. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3040. var _this = this;
  3041. function handleError() {
  3042. that.isSupported = false;
  3043. if (errorCallback)
  3044. errorCallback();
  3045. }
  3046. var that = this;
  3047. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3048. // Your browser doesn't support IndexedDB
  3049. this.isSupported = false;
  3050. if (errorCallback)
  3051. errorCallback();
  3052. }
  3053. else {
  3054. // If the DB hasn't been opened or created yet
  3055. if (!this.db) {
  3056. this.hasReachedQuota = false;
  3057. this.isSupported = true;
  3058. var request = this.idbFactory.open("babylonjs", 1);
  3059. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3060. request.onerror = function (event) {
  3061. handleError();
  3062. };
  3063. // executes when a version change transaction cannot complete due to other active transactions
  3064. request.onblocked = function (event) {
  3065. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3066. handleError();
  3067. };
  3068. // DB has been opened successfully
  3069. request.onsuccess = function (event) {
  3070. _this.db = request.result;
  3071. successCallback();
  3072. };
  3073. // Initialization of the DB. Creating Scenes & Textures stores
  3074. request.onupgradeneeded = function (event) {
  3075. _this.db = (event.target).result;
  3076. try {
  3077. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3078. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3079. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3080. }
  3081. catch (ex) {
  3082. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3083. handleError();
  3084. }
  3085. };
  3086. }
  3087. else {
  3088. if (successCallback)
  3089. successCallback();
  3090. }
  3091. }
  3092. };
  3093. Database.prototype.loadImageFromDB = function (url, image) {
  3094. var _this = this;
  3095. var completeURL = Database.ReturnFullUrlLocation(url);
  3096. var saveAndLoadImage = function () {
  3097. if (!_this.hasReachedQuota && _this.db !== null) {
  3098. // the texture is not yet in the DB, let's try to save it
  3099. _this._saveImageIntoDBAsync(completeURL, image);
  3100. }
  3101. else {
  3102. image.src = url;
  3103. }
  3104. };
  3105. if (!this.mustUpdateRessources) {
  3106. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3107. }
  3108. else {
  3109. saveAndLoadImage();
  3110. }
  3111. };
  3112. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3113. if (this.isSupported && this.db !== null) {
  3114. var texture;
  3115. var transaction = this.db.transaction(["textures"]);
  3116. transaction.onabort = function (event) {
  3117. image.src = url;
  3118. };
  3119. transaction.oncomplete = function (event) {
  3120. var blobTextureURL;
  3121. if (texture) {
  3122. var URL = window.URL || window.webkitURL;
  3123. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3124. image.onerror = function () {
  3125. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3126. image.src = url;
  3127. };
  3128. image.src = blobTextureURL;
  3129. }
  3130. else {
  3131. notInDBCallback();
  3132. }
  3133. };
  3134. var getRequest = transaction.objectStore("textures").get(url);
  3135. getRequest.onsuccess = function (event) {
  3136. texture = (event.target).result;
  3137. };
  3138. getRequest.onerror = function (event) {
  3139. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3140. image.src = url;
  3141. };
  3142. }
  3143. else {
  3144. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3145. image.src = url;
  3146. }
  3147. };
  3148. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3149. var _this = this;
  3150. if (this.isSupported) {
  3151. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3152. var generateBlobUrl = function () {
  3153. var blobTextureURL;
  3154. if (blob) {
  3155. var URL = window.URL || window.webkitURL;
  3156. try {
  3157. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3158. }
  3159. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3160. catch (ex) {
  3161. blobTextureURL = URL.createObjectURL(blob);
  3162. }
  3163. }
  3164. image.src = blobTextureURL;
  3165. };
  3166. if (Database.IsUASupportingBlobStorage) {
  3167. var xhr = new XMLHttpRequest(), blob;
  3168. xhr.open("GET", url, true);
  3169. xhr.responseType = "blob";
  3170. xhr.addEventListener("load", function () {
  3171. if (xhr.status === 200) {
  3172. // Blob as response (XHR2)
  3173. blob = xhr.response;
  3174. var transaction = _this.db.transaction(["textures"], "readwrite");
  3175. // the transaction could abort because of a QuotaExceededError error
  3176. transaction.onabort = function (event) {
  3177. try {
  3178. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3179. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3180. this.hasReachedQuota = true;
  3181. }
  3182. }
  3183. catch (ex) { }
  3184. generateBlobUrl();
  3185. };
  3186. transaction.oncomplete = function (event) {
  3187. generateBlobUrl();
  3188. };
  3189. var newTexture = { textureUrl: url, data: blob };
  3190. try {
  3191. // Put the blob into the dabase
  3192. var addRequest = transaction.objectStore("textures").put(newTexture);
  3193. addRequest.onsuccess = function (event) {
  3194. };
  3195. addRequest.onerror = function (event) {
  3196. generateBlobUrl();
  3197. };
  3198. }
  3199. catch (ex) {
  3200. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3201. if (ex.code === 25) {
  3202. Database.IsUASupportingBlobStorage = false;
  3203. }
  3204. image.src = url;
  3205. }
  3206. }
  3207. else {
  3208. image.src = url;
  3209. }
  3210. }, false);
  3211. xhr.addEventListener("error", function (event) {
  3212. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3213. image.src = url;
  3214. }, false);
  3215. xhr.send();
  3216. }
  3217. else {
  3218. image.src = url;
  3219. }
  3220. }
  3221. else {
  3222. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3223. image.src = url;
  3224. }
  3225. };
  3226. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3227. var _this = this;
  3228. var updateVersion = function (event) {
  3229. // the version is not yet in the DB or we need to update it
  3230. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3231. };
  3232. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3233. };
  3234. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3235. var _this = this;
  3236. if (this.isSupported) {
  3237. var version;
  3238. try {
  3239. var transaction = this.db.transaction(["versions"]);
  3240. transaction.oncomplete = function (event) {
  3241. if (version) {
  3242. // If the version in the JSON file is > than the version in DB
  3243. if (_this.manifestVersionFound > version.data) {
  3244. _this.mustUpdateRessources = true;
  3245. updateInDBCallback();
  3246. }
  3247. else {
  3248. callback(version.data);
  3249. }
  3250. }
  3251. else {
  3252. _this.mustUpdateRessources = true;
  3253. updateInDBCallback();
  3254. }
  3255. };
  3256. transaction.onabort = function (event) {
  3257. callback(-1);
  3258. };
  3259. var getRequest = transaction.objectStore("versions").get(url);
  3260. getRequest.onsuccess = function (event) {
  3261. version = (event.target).result;
  3262. };
  3263. getRequest.onerror = function (event) {
  3264. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3265. callback(-1);
  3266. };
  3267. }
  3268. catch (ex) {
  3269. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3270. callback(-1);
  3271. }
  3272. }
  3273. else {
  3274. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3275. callback(-1);
  3276. }
  3277. };
  3278. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3279. var _this = this;
  3280. if (this.isSupported && !this.hasReachedQuota) {
  3281. try {
  3282. // Open a transaction to the database
  3283. var transaction = this.db.transaction(["versions"], "readwrite");
  3284. // the transaction could abort because of a QuotaExceededError error
  3285. transaction.onabort = function (event) {
  3286. try {
  3287. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3288. _this.hasReachedQuota = true;
  3289. }
  3290. }
  3291. catch (ex) { }
  3292. callback(-1);
  3293. };
  3294. transaction.oncomplete = function (event) {
  3295. callback(_this.manifestVersionFound);
  3296. };
  3297. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3298. // Put the scene into the database
  3299. var addRequest = transaction.objectStore("versions").put(newVersion);
  3300. addRequest.onsuccess = function (event) {
  3301. };
  3302. addRequest.onerror = function (event) {
  3303. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3304. };
  3305. }
  3306. catch (ex) {
  3307. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3308. callback(-1);
  3309. }
  3310. }
  3311. else {
  3312. callback(-1);
  3313. }
  3314. };
  3315. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3316. var _this = this;
  3317. var completeUrl = Database.ReturnFullUrlLocation(url);
  3318. var saveAndLoadFile = function (event) {
  3319. // the scene is not yet in the DB, let's try to save it
  3320. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3321. };
  3322. this._checkVersionFromDB(completeUrl, function (version) {
  3323. if (version !== -1) {
  3324. if (!_this.mustUpdateRessources) {
  3325. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3326. }
  3327. else {
  3328. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3329. }
  3330. }
  3331. else {
  3332. errorCallback();
  3333. }
  3334. });
  3335. };
  3336. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3337. if (this.isSupported) {
  3338. var targetStore;
  3339. if (url.indexOf(".babylon") !== -1) {
  3340. targetStore = "scenes";
  3341. }
  3342. else {
  3343. targetStore = "textures";
  3344. }
  3345. var file;
  3346. var transaction = this.db.transaction([targetStore]);
  3347. transaction.oncomplete = function (event) {
  3348. if (file) {
  3349. callback(file.data);
  3350. }
  3351. else {
  3352. notInDBCallback();
  3353. }
  3354. };
  3355. transaction.onabort = function (event) {
  3356. notInDBCallback();
  3357. };
  3358. var getRequest = transaction.objectStore(targetStore).get(url);
  3359. getRequest.onsuccess = function (event) {
  3360. file = (event.target).result;
  3361. };
  3362. getRequest.onerror = function (event) {
  3363. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3364. notInDBCallback();
  3365. };
  3366. }
  3367. else {
  3368. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3369. callback();
  3370. }
  3371. };
  3372. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3373. var _this = this;
  3374. if (this.isSupported) {
  3375. var targetStore;
  3376. if (url.indexOf(".babylon") !== -1) {
  3377. targetStore = "scenes";
  3378. }
  3379. else {
  3380. targetStore = "textures";
  3381. }
  3382. // Create XHR
  3383. var xhr = new XMLHttpRequest(), fileData;
  3384. xhr.open("GET", url, true);
  3385. if (useArrayBuffer) {
  3386. xhr.responseType = "arraybuffer";
  3387. }
  3388. xhr.onprogress = progressCallback;
  3389. xhr.addEventListener("load", function () {
  3390. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3391. // Blob as response (XHR2)
  3392. //fileData = xhr.responseText;
  3393. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3394. if (!_this.hasReachedQuota) {
  3395. // Open a transaction to the database
  3396. var transaction = _this.db.transaction([targetStore], "readwrite");
  3397. // the transaction could abort because of a QuotaExceededError error
  3398. transaction.onabort = function (event) {
  3399. try {
  3400. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3401. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3402. this.hasReachedQuota = true;
  3403. }
  3404. }
  3405. catch (ex) { }
  3406. callback(fileData);
  3407. };
  3408. transaction.oncomplete = function (event) {
  3409. callback(fileData);
  3410. };
  3411. var newFile;
  3412. if (targetStore === "scenes") {
  3413. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3414. }
  3415. else {
  3416. newFile = { textureUrl: url, data: fileData };
  3417. }
  3418. try {
  3419. // Put the scene into the database
  3420. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3421. addRequest.onsuccess = function (event) {
  3422. };
  3423. addRequest.onerror = function (event) {
  3424. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3425. };
  3426. }
  3427. catch (ex) {
  3428. callback(fileData);
  3429. }
  3430. }
  3431. else {
  3432. callback(fileData);
  3433. }
  3434. }
  3435. else {
  3436. callback();
  3437. }
  3438. }, false);
  3439. xhr.addEventListener("error", function (event) {
  3440. BABYLON.Tools.Error("error on XHR request.");
  3441. callback();
  3442. }, false);
  3443. xhr.send();
  3444. }
  3445. else {
  3446. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3447. callback();
  3448. }
  3449. };
  3450. Database.IsUASupportingBlobStorage = true;
  3451. Database.IDBStorageEnabled = true;
  3452. Database.parseURL = function (url) {
  3453. var a = document.createElement('a');
  3454. a.href = url;
  3455. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3456. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3457. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3458. return absLocation;
  3459. };
  3460. Database.ReturnFullUrlLocation = function (url) {
  3461. if (url.indexOf("http:/") === -1) {
  3462. return (Database.parseURL(window.location.href) + url);
  3463. }
  3464. else {
  3465. return url;
  3466. }
  3467. };
  3468. return Database;
  3469. })();
  3470. BABYLON.Database = Database;
  3471. })(BABYLON || (BABYLON = {}));
  3472. var BABYLON;
  3473. (function (BABYLON) {
  3474. var Internals;
  3475. (function (Internals) {
  3476. /*
  3477. * Based on jsTGALoader - Javascript loader for TGA file
  3478. * By Vincent Thibault
  3479. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3480. */
  3481. var TGATools = (function () {
  3482. function TGATools() {
  3483. }
  3484. TGATools.GetTGAHeader = function (data) {
  3485. var offset = 0;
  3486. var header = {
  3487. id_length: data[offset++],
  3488. colormap_type: data[offset++],
  3489. image_type: data[offset++],
  3490. colormap_index: data[offset++] | data[offset++] << 8,
  3491. colormap_length: data[offset++] | data[offset++] << 8,
  3492. colormap_size: data[offset++],
  3493. origin: [
  3494. data[offset++] | data[offset++] << 8,
  3495. data[offset++] | data[offset++] << 8
  3496. ],
  3497. width: data[offset++] | data[offset++] << 8,
  3498. height: data[offset++] | data[offset++] << 8,
  3499. pixel_size: data[offset++],
  3500. flags: data[offset++]
  3501. };
  3502. return header;
  3503. };
  3504. TGATools.UploadContent = function (gl, data) {
  3505. // Not enough data to contain header ?
  3506. if (data.length < 19) {
  3507. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3508. return;
  3509. }
  3510. // Read Header
  3511. var offset = 18;
  3512. var header = TGATools.GetTGAHeader(data);
  3513. // Assume it's a valid Targa file.
  3514. if (header.id_length + offset > data.length) {
  3515. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3516. return;
  3517. }
  3518. // Skip not needed data
  3519. offset += header.id_length;
  3520. var use_rle = false;
  3521. var use_pal = false;
  3522. var use_rgb = false;
  3523. var use_grey = false;
  3524. // Get some informations.
  3525. switch (header.image_type) {
  3526. case TGATools._TYPE_RLE_INDEXED:
  3527. use_rle = true;
  3528. case TGATools._TYPE_INDEXED:
  3529. use_pal = true;
  3530. break;
  3531. case TGATools._TYPE_RLE_RGB:
  3532. use_rle = true;
  3533. case TGATools._TYPE_RGB:
  3534. use_rgb = true;
  3535. break;
  3536. case TGATools._TYPE_RLE_GREY:
  3537. use_rle = true;
  3538. case TGATools._TYPE_GREY:
  3539. use_grey = true;
  3540. break;
  3541. }
  3542. var pixel_data;
  3543. var numAlphaBits = header.flags & 0xf;
  3544. var pixel_size = header.pixel_size >> 3;
  3545. var pixel_total = header.width * header.height * pixel_size;
  3546. // Read palettes
  3547. var palettes;
  3548. if (use_pal) {
  3549. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3550. }
  3551. // Read LRE
  3552. if (use_rle) {
  3553. pixel_data = new Uint8Array(pixel_total);
  3554. var c, count, i;
  3555. var localOffset = 0;
  3556. var pixels = new Uint8Array(pixel_size);
  3557. while (offset < pixel_total && localOffset < pixel_total) {
  3558. c = data[offset++];
  3559. count = (c & 0x7f) + 1;
  3560. // RLE pixels
  3561. if (c & 0x80) {
  3562. // Bind pixel tmp array
  3563. for (i = 0; i < pixel_size; ++i) {
  3564. pixels[i] = data[offset++];
  3565. }
  3566. // Copy pixel array
  3567. for (i = 0; i < count; ++i) {
  3568. pixel_data.set(pixels, localOffset + i * pixel_size);
  3569. }
  3570. localOffset += pixel_size * count;
  3571. }
  3572. else {
  3573. count *= pixel_size;
  3574. for (i = 0; i < count; ++i) {
  3575. pixel_data[localOffset + i] = data[offset++];
  3576. }
  3577. localOffset += count;
  3578. }
  3579. }
  3580. }
  3581. else {
  3582. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3583. }
  3584. // Load to texture
  3585. var x_start, y_start, x_step, y_step, y_end, x_end;
  3586. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3587. default:
  3588. case TGATools._ORIGIN_UL:
  3589. x_start = 0;
  3590. x_step = 1;
  3591. x_end = header.width;
  3592. y_start = 0;
  3593. y_step = 1;
  3594. y_end = header.height;
  3595. break;
  3596. case TGATools._ORIGIN_BL:
  3597. x_start = 0;
  3598. x_step = 1;
  3599. x_end = header.width;
  3600. y_start = header.height - 1;
  3601. y_step = -1;
  3602. y_end = -1;
  3603. break;
  3604. case TGATools._ORIGIN_UR:
  3605. x_start = header.width - 1;
  3606. x_step = -1;
  3607. x_end = -1;
  3608. y_start = 0;
  3609. y_step = 1;
  3610. y_end = header.height;
  3611. break;
  3612. case TGATools._ORIGIN_BR:
  3613. x_start = header.width - 1;
  3614. x_step = -1;
  3615. x_end = -1;
  3616. y_start = header.height - 1;
  3617. y_step = -1;
  3618. y_end = -1;
  3619. break;
  3620. }
  3621. // Load the specify method
  3622. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3623. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3624. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3625. };
  3626. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3627. var image = pixel_data, colormap = palettes;
  3628. var width = header.width, height = header.height;
  3629. var color, i = 0, x, y;
  3630. var imageData = new Uint8Array(width * height * 4);
  3631. for (y = y_start; y !== y_end; y += y_step) {
  3632. for (x = x_start; x !== x_end; x += x_step, i++) {
  3633. color = image[i];
  3634. imageData[(x + width * y) * 4 + 3] = 255;
  3635. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3636. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3637. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3638. }
  3639. }
  3640. return imageData;
  3641. };
  3642. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3643. var image = pixel_data;
  3644. var width = header.width, height = header.height;
  3645. var color, i = 0, x, y;
  3646. var imageData = new Uint8Array(width * height * 4);
  3647. for (y = y_start; y !== y_end; y += y_step) {
  3648. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3649. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3650. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3651. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3652. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3653. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3654. }
  3655. }
  3656. return imageData;
  3657. };
  3658. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3659. var image = pixel_data;
  3660. var width = header.width, height = header.height;
  3661. var i = 0, x, y;
  3662. var imageData = new Uint8Array(width * height * 4);
  3663. for (y = y_start; y !== y_end; y += y_step) {
  3664. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3665. imageData[(x + width * y) * 4 + 3] = 255;
  3666. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3667. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3668. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3669. }
  3670. }
  3671. return imageData;
  3672. };
  3673. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3674. var image = pixel_data;
  3675. var width = header.width, height = header.height;
  3676. var i = 0, x, y;
  3677. var imageData = new Uint8Array(width * height * 4);
  3678. for (y = y_start; y !== y_end; y += y_step) {
  3679. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3680. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3681. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3682. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3683. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3684. }
  3685. }
  3686. return imageData;
  3687. };
  3688. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3689. var image = pixel_data;
  3690. var width = header.width, height = header.height;
  3691. var color, i = 0, x, y;
  3692. var imageData = new Uint8Array(width * height * 4);
  3693. for (y = y_start; y !== y_end; y += y_step) {
  3694. for (x = x_start; x !== x_end; x += x_step, i++) {
  3695. color = image[i];
  3696. imageData[(x + width * y) * 4 + 0] = color;
  3697. imageData[(x + width * y) * 4 + 1] = color;
  3698. imageData[(x + width * y) * 4 + 2] = color;
  3699. imageData[(x + width * y) * 4 + 3] = 255;
  3700. }
  3701. }
  3702. return imageData;
  3703. };
  3704. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3705. var image = pixel_data;
  3706. var width = header.width, height = header.height;
  3707. var i = 0, x, y;
  3708. var imageData = new Uint8Array(width * height * 4);
  3709. for (y = y_start; y !== y_end; y += y_step) {
  3710. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3711. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3712. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3713. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3714. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3715. }
  3716. }
  3717. return imageData;
  3718. };
  3719. TGATools._TYPE_NO_DATA = 0;
  3720. TGATools._TYPE_INDEXED = 1;
  3721. TGATools._TYPE_RGB = 2;
  3722. TGATools._TYPE_GREY = 3;
  3723. TGATools._TYPE_RLE_INDEXED = 9;
  3724. TGATools._TYPE_RLE_RGB = 10;
  3725. TGATools._TYPE_RLE_GREY = 11;
  3726. TGATools._ORIGIN_MASK = 0x30;
  3727. TGATools._ORIGIN_SHIFT = 0x04;
  3728. TGATools._ORIGIN_BL = 0x00;
  3729. TGATools._ORIGIN_BR = 0x01;
  3730. TGATools._ORIGIN_UL = 0x02;
  3731. TGATools._ORIGIN_UR = 0x03;
  3732. return TGATools;
  3733. })();
  3734. Internals.TGATools = TGATools;
  3735. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3736. })(BABYLON || (BABYLON = {}));
  3737. var BABYLON;
  3738. (function (BABYLON) {
  3739. var SmartArray = (function () {
  3740. function SmartArray(capacity) {
  3741. this.length = 0;
  3742. this._duplicateId = 0;
  3743. this.data = new Array(capacity);
  3744. this._id = SmartArray._GlobalId++;
  3745. }
  3746. SmartArray.prototype.push = function (value) {
  3747. this.data[this.length++] = value;
  3748. if (this.length > this.data.length) {
  3749. this.data.length *= 2;
  3750. }
  3751. if (!value.__smartArrayFlags) {
  3752. value.__smartArrayFlags = {};
  3753. }
  3754. value.__smartArrayFlags[this._id] = this._duplicateId;
  3755. };
  3756. SmartArray.prototype.pushNoDuplicate = function (value) {
  3757. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3758. return;
  3759. }
  3760. this.push(value);
  3761. };
  3762. SmartArray.prototype.sort = function (compareFn) {
  3763. this.data.sort(compareFn);
  3764. };
  3765. SmartArray.prototype.reset = function () {
  3766. this.length = 0;
  3767. this._duplicateId++;
  3768. };
  3769. SmartArray.prototype.concat = function (array) {
  3770. if (array.length === 0) {
  3771. return;
  3772. }
  3773. if (this.length + array.length > this.data.length) {
  3774. this.data.length = (this.length + array.length) * 2;
  3775. }
  3776. for (var index = 0; index < array.length; index++) {
  3777. this.data[this.length++] = (array.data || array)[index];
  3778. }
  3779. };
  3780. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3781. if (array.length === 0) {
  3782. return;
  3783. }
  3784. if (this.length + array.length > this.data.length) {
  3785. this.data.length = (this.length + array.length) * 2;
  3786. }
  3787. for (var index = 0; index < array.length; index++) {
  3788. var item = (array.data || array)[index];
  3789. this.pushNoDuplicate(item);
  3790. }
  3791. };
  3792. SmartArray.prototype.indexOf = function (value) {
  3793. var position = this.data.indexOf(value);
  3794. if (position >= this.length) {
  3795. return -1;
  3796. }
  3797. return position;
  3798. };
  3799. // Statics
  3800. SmartArray._GlobalId = 0;
  3801. return SmartArray;
  3802. })();
  3803. BABYLON.SmartArray = SmartArray;
  3804. })(BABYLON || (BABYLON = {}));
  3805. var BABYLON;
  3806. (function (BABYLON) {
  3807. var SmartCollection = (function () {
  3808. function SmartCollection(capacity) {
  3809. if (capacity === void 0) { capacity = 10; }
  3810. this.count = 0;
  3811. this._initialCapacity = capacity;
  3812. this.items = {};
  3813. this._keys = new Array(this._initialCapacity);
  3814. }
  3815. SmartCollection.prototype.add = function (key, item) {
  3816. if (this.items[key] != undefined) {
  3817. return -1;
  3818. }
  3819. this.items[key] = item;
  3820. //literal keys are always strings, but we keep source type of key in _keys array
  3821. this._keys[this.count++] = key;
  3822. if (this.count > this._keys.length) {
  3823. this._keys.length *= 2;
  3824. }
  3825. return this.count;
  3826. };
  3827. SmartCollection.prototype.remove = function (key) {
  3828. if (this.items[key] == undefined) {
  3829. return -1;
  3830. }
  3831. return this.removeItemOfIndex(this.indexOf(key));
  3832. };
  3833. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3834. if (index < this.count && index > -1) {
  3835. delete this.items[this._keys[index]];
  3836. //here, shifting by hand is better optimised than .splice
  3837. while (index < this.count) {
  3838. this._keys[index] = this._keys[index + 1];
  3839. index++;
  3840. }
  3841. }
  3842. else {
  3843. return -1;
  3844. }
  3845. return --this.count;
  3846. };
  3847. SmartCollection.prototype.indexOf = function (key) {
  3848. for (var i = 0; i !== this.count; i++) {
  3849. if (this._keys[i] === key) {
  3850. return i;
  3851. }
  3852. }
  3853. return -1;
  3854. };
  3855. SmartCollection.prototype.item = function (key) {
  3856. return this.items[key];
  3857. };
  3858. SmartCollection.prototype.getAllKeys = function () {
  3859. if (this.count > 0) {
  3860. var keys = new Array(this.count);
  3861. for (var i = 0; i < this.count; i++) {
  3862. keys[i] = this._keys[i];
  3863. }
  3864. return keys;
  3865. }
  3866. else {
  3867. return undefined;
  3868. }
  3869. };
  3870. SmartCollection.prototype.getKeyByIndex = function (index) {
  3871. if (index < this.count && index > -1) {
  3872. return this._keys[index];
  3873. }
  3874. else {
  3875. return undefined;
  3876. }
  3877. };
  3878. SmartCollection.prototype.getItemByIndex = function (index) {
  3879. if (index < this.count && index > -1) {
  3880. return this.items[this._keys[index]];
  3881. }
  3882. else {
  3883. return undefined;
  3884. }
  3885. };
  3886. SmartCollection.prototype.empty = function () {
  3887. if (this.count > 0) {
  3888. this.count = 0;
  3889. this.items = {};
  3890. this._keys = new Array(this._initialCapacity);
  3891. }
  3892. };
  3893. SmartCollection.prototype.forEach = function (block) {
  3894. var key;
  3895. for (key in this.items) {
  3896. if (this.items.hasOwnProperty(key)) {
  3897. block(this.items[key]);
  3898. }
  3899. }
  3900. };
  3901. return SmartCollection;
  3902. })();
  3903. BABYLON.SmartCollection = SmartCollection;
  3904. })(BABYLON || (BABYLON = {}));
  3905. var BABYLON;
  3906. (function (BABYLON) {
  3907. // Screenshots
  3908. var screenshotCanvas;
  3909. var cloneValue = function (source, destinationObject) {
  3910. if (!source)
  3911. return null;
  3912. if (source instanceof BABYLON.Mesh) {
  3913. return null;
  3914. }
  3915. if (source instanceof BABYLON.SubMesh) {
  3916. return source.clone(destinationObject);
  3917. }
  3918. else if (source.clone) {
  3919. return source.clone();
  3920. }
  3921. return null;
  3922. };
  3923. var Tools = (function () {
  3924. function Tools() {
  3925. }
  3926. Tools.Instantiate = function (className) {
  3927. var arr = className.split(".");
  3928. var fn = (window || this);
  3929. for (var i = 0, len = arr.length; i < len; i++) {
  3930. fn = fn[arr[i]];
  3931. }
  3932. if (typeof fn !== "function") {
  3933. return null;
  3934. }
  3935. return fn;
  3936. };
  3937. Tools.GetConstructorName = function (obj) {
  3938. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  3939. var cname = str.match(/function\s(\w*)/)[1];
  3940. var aliases = ["", "anonymous", "Anonymous"];
  3941. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  3942. };
  3943. Tools.ToHex = function (i) {
  3944. var str = i.toString(16);
  3945. if (i <= 15) {
  3946. return ("0" + str).toUpperCase();
  3947. }
  3948. return str.toUpperCase();
  3949. };
  3950. Tools.SetImmediate = function (action) {
  3951. if (window.setImmediate) {
  3952. window.setImmediate(action);
  3953. }
  3954. else {
  3955. setTimeout(action, 1);
  3956. }
  3957. };
  3958. Tools.IsExponentOfTwo = function (value) {
  3959. var count = 1;
  3960. do {
  3961. count *= 2;
  3962. } while (count < value);
  3963. return count === value;
  3964. };
  3965. Tools.GetExponentOfTwo = function (value, max) {
  3966. var count = 1;
  3967. do {
  3968. count *= 2;
  3969. } while (count < value);
  3970. if (count > max)
  3971. count = max;
  3972. return count;
  3973. };
  3974. Tools.GetFilename = function (path) {
  3975. var index = path.lastIndexOf("/");
  3976. if (index < 0)
  3977. return path;
  3978. return path.substring(index + 1);
  3979. };
  3980. Tools.GetDOMTextContent = function (element) {
  3981. var result = "";
  3982. var child = element.firstChild;
  3983. while (child) {
  3984. if (child.nodeType === 3) {
  3985. result += child.textContent;
  3986. }
  3987. child = child.nextSibling;
  3988. }
  3989. return result;
  3990. };
  3991. Tools.ToDegrees = function (angle) {
  3992. return angle * 180 / Math.PI;
  3993. };
  3994. Tools.ToRadians = function (angle) {
  3995. return angle * Math.PI / 180;
  3996. };
  3997. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3998. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3999. var output = "";
  4000. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4001. var i = 0;
  4002. var bytes = new Uint8Array(buffer);
  4003. while (i < bytes.length) {
  4004. chr1 = bytes[i++];
  4005. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4006. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4007. enc1 = chr1 >> 2;
  4008. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4009. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4010. enc4 = chr3 & 63;
  4011. if (isNaN(chr2)) {
  4012. enc3 = enc4 = 64;
  4013. }
  4014. else if (isNaN(chr3)) {
  4015. enc4 = 64;
  4016. }
  4017. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4018. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4019. }
  4020. return "data:image/png;base64," + output;
  4021. };
  4022. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4023. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4024. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4025. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4026. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4027. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4028. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4029. }
  4030. return {
  4031. minimum: minimum,
  4032. maximum: maximum
  4033. };
  4034. };
  4035. Tools.ExtractMinAndMax = function (positions, start, count) {
  4036. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4037. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4038. for (var index = start; index < start + count; index++) {
  4039. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4040. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4041. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4042. }
  4043. return {
  4044. minimum: minimum,
  4045. maximum: maximum
  4046. };
  4047. };
  4048. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4049. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4050. return undefined;
  4051. return Array.isArray(obj) ? obj : [obj];
  4052. };
  4053. // Misc.
  4054. Tools.GetPointerPrefix = function () {
  4055. var eventPrefix = "pointer";
  4056. // Check if pointer events are supported
  4057. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4058. eventPrefix = "mouse";
  4059. }
  4060. return eventPrefix;
  4061. };
  4062. Tools.QueueNewFrame = function (func) {
  4063. if (window.requestAnimationFrame)
  4064. window.requestAnimationFrame(func);
  4065. else if (window.msRequestAnimationFrame)
  4066. window.msRequestAnimationFrame(func);
  4067. else if (window.webkitRequestAnimationFrame)
  4068. window.webkitRequestAnimationFrame(func);
  4069. else if (window.mozRequestAnimationFrame)
  4070. window.mozRequestAnimationFrame(func);
  4071. else if (window.oRequestAnimationFrame)
  4072. window.oRequestAnimationFrame(func);
  4073. else {
  4074. window.setTimeout(func, 16);
  4075. }
  4076. };
  4077. Tools.RequestFullscreen = function (element) {
  4078. if (element.requestFullscreen)
  4079. element.requestFullscreen();
  4080. else if (element.msRequestFullscreen)
  4081. element.msRequestFullscreen();
  4082. else if (element.webkitRequestFullscreen)
  4083. element.webkitRequestFullscreen();
  4084. else if (element.mozRequestFullScreen)
  4085. element.mozRequestFullScreen();
  4086. };
  4087. Tools.ExitFullscreen = function () {
  4088. if (document.exitFullscreen) {
  4089. document.exitFullscreen();
  4090. }
  4091. else if (document.mozCancelFullScreen) {
  4092. document.mozCancelFullScreen();
  4093. }
  4094. else if (document.webkitCancelFullScreen) {
  4095. document.webkitCancelFullScreen();
  4096. }
  4097. else if (document.msCancelFullScreen) {
  4098. document.msCancelFullScreen();
  4099. }
  4100. };
  4101. // External files
  4102. Tools.CleanUrl = function (url) {
  4103. url = url.replace(/#/mg, "%23");
  4104. return url;
  4105. };
  4106. Tools.LoadImage = function (url, onload, onerror, database) {
  4107. if (url instanceof ArrayBuffer) {
  4108. url = Tools.EncodeArrayBufferTobase64(url);
  4109. }
  4110. url = Tools.CleanUrl(url);
  4111. var img = new Image();
  4112. if (url.substr(0, 5) !== "data:") {
  4113. if (Tools.CorsBehavior) {
  4114. switch (typeof (Tools.CorsBehavior)) {
  4115. case "function":
  4116. var result = Tools.CorsBehavior(url);
  4117. if (result) {
  4118. img.crossOrigin = result;
  4119. }
  4120. break;
  4121. case "string":
  4122. default:
  4123. img.crossOrigin = Tools.CorsBehavior;
  4124. break;
  4125. }
  4126. }
  4127. }
  4128. img.onload = function () {
  4129. onload(img);
  4130. };
  4131. img.onerror = function (err) {
  4132. Tools.Error("Error while trying to load texture: " + url);
  4133. if (Tools.UseFallbackTexture) {
  4134. 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";
  4135. onload(img);
  4136. }
  4137. else {
  4138. onerror();
  4139. }
  4140. };
  4141. var noIndexedDB = function () {
  4142. img.src = url;
  4143. };
  4144. var loadFromIndexedDB = function () {
  4145. database.loadImageFromDB(url, img);
  4146. };
  4147. //ANY database to do!
  4148. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4149. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4150. }
  4151. else {
  4152. if (url.indexOf("file:") === -1) {
  4153. noIndexedDB();
  4154. }
  4155. else {
  4156. try {
  4157. var textureName = url.substring(5);
  4158. var blobURL;
  4159. try {
  4160. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4161. }
  4162. catch (ex) {
  4163. // Chrome doesn't support oneTimeOnly parameter
  4164. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4165. }
  4166. img.src = blobURL;
  4167. }
  4168. catch (e) {
  4169. img.src = null;
  4170. }
  4171. }
  4172. }
  4173. return img;
  4174. };
  4175. //ANY
  4176. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4177. url = Tools.CleanUrl(url);
  4178. var noIndexedDB = function () {
  4179. var request = new XMLHttpRequest();
  4180. var loadUrl = Tools.BaseUrl + url;
  4181. request.open('GET', loadUrl, true);
  4182. if (useArrayBuffer) {
  4183. request.responseType = "arraybuffer";
  4184. }
  4185. request.onprogress = progressCallBack;
  4186. request.onreadystatechange = function () {
  4187. if (request.readyState === 4) {
  4188. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4189. callback(!useArrayBuffer ? request.responseText : request.response);
  4190. }
  4191. else {
  4192. if (onError) {
  4193. onError();
  4194. }
  4195. else {
  4196. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4197. }
  4198. }
  4199. }
  4200. };
  4201. request.send(null);
  4202. };
  4203. var loadFromIndexedDB = function () {
  4204. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4205. };
  4206. if (url.indexOf("file:") !== -1) {
  4207. var fileName = url.substring(5);
  4208. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4209. }
  4210. else {
  4211. // Caching all files
  4212. if (database && database.enableSceneOffline) {
  4213. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4214. }
  4215. else {
  4216. noIndexedDB();
  4217. }
  4218. }
  4219. };
  4220. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4221. var reader = new FileReader();
  4222. reader.onload = function (e) {
  4223. //target doesn't have result from ts 1.3
  4224. callback(e.target['result']);
  4225. };
  4226. reader.onprogress = progressCallback;
  4227. reader.readAsDataURL(fileToLoad);
  4228. };
  4229. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4230. var reader = new FileReader();
  4231. reader.onerror = function (e) {
  4232. Tools.Log("Error while reading file: " + fileToLoad.name);
  4233. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4234. };
  4235. reader.onload = function (e) {
  4236. //target doesn't have result from ts 1.3
  4237. callback(e.target['result']);
  4238. };
  4239. reader.onprogress = progressCallBack;
  4240. if (!useArrayBuffer) {
  4241. // Asynchronous read
  4242. reader.readAsText(fileToLoad);
  4243. }
  4244. else {
  4245. reader.readAsArrayBuffer(fileToLoad);
  4246. }
  4247. };
  4248. //returns a downloadable url to a file content.
  4249. Tools.FileAsURL = function (content) {
  4250. var fileBlob = new Blob([content]);
  4251. var url = window.URL || window.webkitURL;
  4252. var link = url.createObjectURL(fileBlob);
  4253. return link;
  4254. };
  4255. // Misc.
  4256. Tools.Clamp = function (value, min, max) {
  4257. if (min === void 0) { min = 0; }
  4258. if (max === void 0) { max = 1; }
  4259. return Math.min(max, Math.max(min, value));
  4260. };
  4261. // Returns -1 when value is a negative number and
  4262. // +1 when value is a positive number.
  4263. Tools.Sign = function (value) {
  4264. value = +value; // convert to a number
  4265. if (value === 0 || isNaN(value))
  4266. return value;
  4267. return value > 0 ? 1 : -1;
  4268. };
  4269. Tools.Format = function (value, decimals) {
  4270. if (decimals === void 0) { decimals = 2; }
  4271. return value.toFixed(decimals);
  4272. };
  4273. Tools.CheckExtends = function (v, min, max) {
  4274. if (v.x < min.x)
  4275. min.x = v.x;
  4276. if (v.y < min.y)
  4277. min.y = v.y;
  4278. if (v.z < min.z)
  4279. min.z = v.z;
  4280. if (v.x > max.x)
  4281. max.x = v.x;
  4282. if (v.y > max.y)
  4283. max.y = v.y;
  4284. if (v.z > max.z)
  4285. max.z = v.z;
  4286. };
  4287. Tools.WithinEpsilon = function (a, b, epsilon) {
  4288. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4289. var num = a - b;
  4290. return -epsilon <= num && num <= epsilon;
  4291. };
  4292. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4293. for (var prop in source) {
  4294. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4295. continue;
  4296. }
  4297. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4298. continue;
  4299. }
  4300. var sourceValue = source[prop];
  4301. var typeOfSourceValue = typeof sourceValue;
  4302. if (typeOfSourceValue === "function") {
  4303. continue;
  4304. }
  4305. if (typeOfSourceValue === "object") {
  4306. if (sourceValue instanceof Array) {
  4307. destination[prop] = [];
  4308. if (sourceValue.length > 0) {
  4309. if (typeof sourceValue[0] == "object") {
  4310. for (var index = 0; index < sourceValue.length; index++) {
  4311. var clonedValue = cloneValue(sourceValue[index], destination);
  4312. if (destination[prop].indexOf(clonedValue) === -1) {
  4313. destination[prop].push(clonedValue);
  4314. }
  4315. }
  4316. }
  4317. else {
  4318. destination[prop] = sourceValue.slice(0);
  4319. }
  4320. }
  4321. }
  4322. else {
  4323. destination[prop] = cloneValue(sourceValue, destination);
  4324. }
  4325. }
  4326. else {
  4327. destination[prop] = sourceValue;
  4328. }
  4329. }
  4330. };
  4331. Tools.IsEmpty = function (obj) {
  4332. for (var i in obj) {
  4333. return false;
  4334. }
  4335. return true;
  4336. };
  4337. Tools.RegisterTopRootEvents = function (events) {
  4338. for (var index = 0; index < events.length; index++) {
  4339. var event = events[index];
  4340. window.addEventListener(event.name, event.handler, false);
  4341. try {
  4342. if (window.parent) {
  4343. window.parent.addEventListener(event.name, event.handler, false);
  4344. }
  4345. }
  4346. catch (e) {
  4347. }
  4348. }
  4349. };
  4350. Tools.UnregisterTopRootEvents = function (events) {
  4351. for (var index = 0; index < events.length; index++) {
  4352. var event = events[index];
  4353. window.removeEventListener(event.name, event.handler);
  4354. try {
  4355. if (window.parent) {
  4356. window.parent.removeEventListener(event.name, event.handler);
  4357. }
  4358. }
  4359. catch (e) {
  4360. }
  4361. }
  4362. };
  4363. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4364. // Read the contents of the framebuffer
  4365. var numberOfChannelsByLine = width * 4;
  4366. var halfHeight = height / 2;
  4367. //Reading datas from WebGL
  4368. var data = engine.readPixels(0, 0, width, height);
  4369. //To flip image on Y axis.
  4370. for (var i = 0; i < halfHeight; i++) {
  4371. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4372. var currentCell = j + i * numberOfChannelsByLine;
  4373. var targetLine = height - i - 1;
  4374. var targetCell = j + targetLine * numberOfChannelsByLine;
  4375. var temp = data[currentCell];
  4376. data[currentCell] = data[targetCell];
  4377. data[targetCell] = temp;
  4378. }
  4379. }
  4380. // Create a 2D canvas to store the result
  4381. if (!screenshotCanvas) {
  4382. screenshotCanvas = document.createElement('canvas');
  4383. }
  4384. screenshotCanvas.width = width;
  4385. screenshotCanvas.height = height;
  4386. var context = screenshotCanvas.getContext('2d');
  4387. // Copy the pixels to a 2D canvas
  4388. var imageData = context.createImageData(width, height);
  4389. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4390. var castData = imageData.data;
  4391. castData.set(data);
  4392. context.putImageData(imageData, 0, 0);
  4393. var base64Image = screenshotCanvas.toDataURL();
  4394. if (successCallback) {
  4395. successCallback(base64Image);
  4396. }
  4397. else {
  4398. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4399. if (("download" in document.createElement("a"))) {
  4400. var a = window.document.createElement("a");
  4401. a.href = base64Image;
  4402. var date = new Date();
  4403. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4404. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4405. window.document.body.appendChild(a);
  4406. a.addEventListener("click", function () {
  4407. a.parentElement.removeChild(a);
  4408. });
  4409. a.click();
  4410. }
  4411. else {
  4412. var newWindow = window.open("");
  4413. var img = newWindow.document.createElement("img");
  4414. img.src = base64Image;
  4415. newWindow.document.body.appendChild(img);
  4416. }
  4417. }
  4418. };
  4419. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4420. var width;
  4421. var height;
  4422. //If a precision value is specified
  4423. if (size.precision) {
  4424. width = Math.round(engine.getRenderWidth() * size.precision);
  4425. height = Math.round(width / engine.getAspectRatio(camera));
  4426. size = { width: width, height: height };
  4427. }
  4428. else if (size.width && size.height) {
  4429. width = size.width;
  4430. height = size.height;
  4431. }
  4432. else if (size.width && !size.height) {
  4433. width = size.width;
  4434. height = Math.round(width / engine.getAspectRatio(camera));
  4435. size = { width: width, height: height };
  4436. }
  4437. else if (size.height && !size.width) {
  4438. height = size.height;
  4439. width = Math.round(height * engine.getAspectRatio(camera));
  4440. size = { width: width, height: height };
  4441. }
  4442. else if (!isNaN(size)) {
  4443. height = size;
  4444. width = size;
  4445. }
  4446. else {
  4447. Tools.Error("Invalid 'size' parameter !");
  4448. return;
  4449. }
  4450. var scene = camera.getScene();
  4451. var previousCamera = null;
  4452. if (scene.activeCamera !== camera) {
  4453. previousCamera = scene.activeCamera;
  4454. scene.activeCamera = camera;
  4455. }
  4456. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4457. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4458. texture.renderList = scene.meshes;
  4459. texture.onAfterRender = function () {
  4460. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4461. };
  4462. scene.incrementRenderId();
  4463. texture.render(true);
  4464. texture.dispose();
  4465. if (previousCamera) {
  4466. scene.activeCamera = previousCamera;
  4467. }
  4468. camera.getProjectionMatrix(true); // Force cache refresh;
  4469. };
  4470. // XHR response validator for local file scenario
  4471. Tools.ValidateXHRData = function (xhr, dataType) {
  4472. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4473. if (dataType === void 0) { dataType = 7; }
  4474. try {
  4475. if (dataType & 1) {
  4476. if (xhr.responseText && xhr.responseText.length > 0) {
  4477. return true;
  4478. }
  4479. else if (dataType === 1) {
  4480. return false;
  4481. }
  4482. }
  4483. if (dataType & 2) {
  4484. // Check header width and height since there is no "TGA" magic number
  4485. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4486. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4487. return true;
  4488. }
  4489. else if (dataType === 2) {
  4490. return false;
  4491. }
  4492. }
  4493. if (dataType & 4) {
  4494. // Check for the "DDS" magic number
  4495. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4496. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4497. return true;
  4498. }
  4499. else {
  4500. return false;
  4501. }
  4502. }
  4503. }
  4504. catch (e) {
  4505. }
  4506. return false;
  4507. };
  4508. Object.defineProperty(Tools, "NoneLogLevel", {
  4509. get: function () {
  4510. return Tools._NoneLogLevel;
  4511. },
  4512. enumerable: true,
  4513. configurable: true
  4514. });
  4515. Object.defineProperty(Tools, "MessageLogLevel", {
  4516. get: function () {
  4517. return Tools._MessageLogLevel;
  4518. },
  4519. enumerable: true,
  4520. configurable: true
  4521. });
  4522. Object.defineProperty(Tools, "WarningLogLevel", {
  4523. get: function () {
  4524. return Tools._WarningLogLevel;
  4525. },
  4526. enumerable: true,
  4527. configurable: true
  4528. });
  4529. Object.defineProperty(Tools, "ErrorLogLevel", {
  4530. get: function () {
  4531. return Tools._ErrorLogLevel;
  4532. },
  4533. enumerable: true,
  4534. configurable: true
  4535. });
  4536. Object.defineProperty(Tools, "AllLogLevel", {
  4537. get: function () {
  4538. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4539. },
  4540. enumerable: true,
  4541. configurable: true
  4542. });
  4543. Tools._AddLogEntry = function (entry) {
  4544. Tools._LogCache = entry + Tools._LogCache;
  4545. if (Tools.OnNewCacheEntry) {
  4546. Tools.OnNewCacheEntry(entry);
  4547. }
  4548. };
  4549. Tools._FormatMessage = function (message) {
  4550. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4551. var date = new Date();
  4552. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4553. };
  4554. Tools._LogDisabled = function (message) {
  4555. // nothing to do
  4556. };
  4557. Tools._LogEnabled = function (message) {
  4558. var formattedMessage = Tools._FormatMessage(message);
  4559. console.log("BJS - " + formattedMessage);
  4560. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4561. Tools._AddLogEntry(entry);
  4562. };
  4563. Tools._WarnDisabled = function (message) {
  4564. // nothing to do
  4565. };
  4566. Tools._WarnEnabled = function (message) {
  4567. var formattedMessage = Tools._FormatMessage(message);
  4568. console.warn("BJS - " + formattedMessage);
  4569. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4570. Tools._AddLogEntry(entry);
  4571. };
  4572. Tools._ErrorDisabled = function (message) {
  4573. // nothing to do
  4574. };
  4575. Tools._ErrorEnabled = function (message) {
  4576. Tools.errorsCount++;
  4577. var formattedMessage = Tools._FormatMessage(message);
  4578. console.error("BJS - " + formattedMessage);
  4579. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4580. Tools._AddLogEntry(entry);
  4581. };
  4582. Object.defineProperty(Tools, "LogCache", {
  4583. get: function () {
  4584. return Tools._LogCache;
  4585. },
  4586. enumerable: true,
  4587. configurable: true
  4588. });
  4589. Tools.ClearLogCache = function () {
  4590. Tools._LogCache = "";
  4591. Tools.errorsCount = 0;
  4592. };
  4593. Object.defineProperty(Tools, "LogLevels", {
  4594. set: function (level) {
  4595. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4596. Tools.Log = Tools._LogEnabled;
  4597. }
  4598. else {
  4599. Tools.Log = Tools._LogDisabled;
  4600. }
  4601. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4602. Tools.Warn = Tools._WarnEnabled;
  4603. }
  4604. else {
  4605. Tools.Warn = Tools._WarnDisabled;
  4606. }
  4607. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4608. Tools.Error = Tools._ErrorEnabled;
  4609. }
  4610. else {
  4611. Tools.Error = Tools._ErrorDisabled;
  4612. }
  4613. },
  4614. enumerable: true,
  4615. configurable: true
  4616. });
  4617. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4618. get: function () {
  4619. return Tools._PerformanceNoneLogLevel;
  4620. },
  4621. enumerable: true,
  4622. configurable: true
  4623. });
  4624. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4625. get: function () {
  4626. return Tools._PerformanceUserMarkLogLevel;
  4627. },
  4628. enumerable: true,
  4629. configurable: true
  4630. });
  4631. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4632. get: function () {
  4633. return Tools._PerformanceConsoleLogLevel;
  4634. },
  4635. enumerable: true,
  4636. configurable: true
  4637. });
  4638. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4639. set: function (level) {
  4640. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4641. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4642. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4643. return;
  4644. }
  4645. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4646. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4647. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4648. return;
  4649. }
  4650. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4651. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4652. },
  4653. enumerable: true,
  4654. configurable: true
  4655. });
  4656. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4657. };
  4658. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4659. };
  4660. Tools._StartUserMark = function (counterName, condition) {
  4661. if (condition === void 0) { condition = true; }
  4662. if (!condition || !Tools._performance.mark) {
  4663. return;
  4664. }
  4665. Tools._performance.mark(counterName + "-Begin");
  4666. };
  4667. Tools._EndUserMark = function (counterName, condition) {
  4668. if (condition === void 0) { condition = true; }
  4669. if (!condition || !Tools._performance.mark) {
  4670. return;
  4671. }
  4672. Tools._performance.mark(counterName + "-End");
  4673. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4674. };
  4675. Tools._StartPerformanceConsole = function (counterName, condition) {
  4676. if (condition === void 0) { condition = true; }
  4677. if (!condition) {
  4678. return;
  4679. }
  4680. Tools._StartUserMark(counterName, condition);
  4681. if (console.time) {
  4682. console.time(counterName);
  4683. }
  4684. };
  4685. Tools._EndPerformanceConsole = function (counterName, condition) {
  4686. if (condition === void 0) { condition = true; }
  4687. if (!condition) {
  4688. return;
  4689. }
  4690. Tools._EndUserMark(counterName, condition);
  4691. if (console.time) {
  4692. console.timeEnd(counterName);
  4693. }
  4694. };
  4695. Object.defineProperty(Tools, "Now", {
  4696. get: function () {
  4697. if (window.performance && window.performance.now) {
  4698. return window.performance.now();
  4699. }
  4700. return new Date().getTime();
  4701. },
  4702. enumerable: true,
  4703. configurable: true
  4704. });
  4705. Tools.BaseUrl = "";
  4706. Tools.CorsBehavior = "anonymous";
  4707. Tools.UseFallbackTexture = true;
  4708. // Logs
  4709. Tools._NoneLogLevel = 0;
  4710. Tools._MessageLogLevel = 1;
  4711. Tools._WarningLogLevel = 2;
  4712. Tools._ErrorLogLevel = 4;
  4713. Tools._LogCache = "";
  4714. Tools.errorsCount = 0;
  4715. Tools.Log = Tools._LogEnabled;
  4716. Tools.Warn = Tools._WarnEnabled;
  4717. Tools.Error = Tools._ErrorEnabled;
  4718. // Performances
  4719. Tools._PerformanceNoneLogLevel = 0;
  4720. Tools._PerformanceUserMarkLogLevel = 1;
  4721. Tools._PerformanceConsoleLogLevel = 2;
  4722. Tools._performance = window.performance;
  4723. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4724. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4725. return Tools;
  4726. })();
  4727. BABYLON.Tools = Tools;
  4728. /**
  4729. * An implementation of a loop for asynchronous functions.
  4730. */
  4731. var AsyncLoop = (function () {
  4732. /**
  4733. * Constroctor.
  4734. * @param iterations the number of iterations.
  4735. * @param _fn the function to run each iteration
  4736. * @param _successCallback the callback that will be called upon succesful execution
  4737. * @param offset starting offset.
  4738. */
  4739. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4740. if (offset === void 0) { offset = 0; }
  4741. this.iterations = iterations;
  4742. this._fn = _fn;
  4743. this._successCallback = _successCallback;
  4744. this.index = offset - 1;
  4745. this._done = false;
  4746. }
  4747. /**
  4748. * Execute the next iteration. Must be called after the last iteration was finished.
  4749. */
  4750. AsyncLoop.prototype.executeNext = function () {
  4751. if (!this._done) {
  4752. if (this.index + 1 < this.iterations) {
  4753. ++this.index;
  4754. this._fn(this);
  4755. }
  4756. else {
  4757. this.breakLoop();
  4758. }
  4759. }
  4760. };
  4761. /**
  4762. * Break the loop and run the success callback.
  4763. */
  4764. AsyncLoop.prototype.breakLoop = function () {
  4765. this._done = true;
  4766. this._successCallback();
  4767. };
  4768. /**
  4769. * Helper function
  4770. */
  4771. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4772. if (offset === void 0) { offset = 0; }
  4773. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4774. loop.executeNext();
  4775. return loop;
  4776. };
  4777. /**
  4778. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4779. * @param iterations total number of iterations
  4780. * @param syncedIterations number of synchronous iterations in each async iteration.
  4781. * @param fn the function to call each iteration.
  4782. * @param callback a success call back that will be called when iterating stops.
  4783. * @param breakFunction a break condition (optional)
  4784. * @param timeout timeout settings for the setTimeout function. default - 0.
  4785. * @constructor
  4786. */
  4787. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4788. if (timeout === void 0) { timeout = 0; }
  4789. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4790. if (breakFunction && breakFunction())
  4791. loop.breakLoop();
  4792. else {
  4793. setTimeout(function () {
  4794. for (var i = 0; i < syncedIterations; ++i) {
  4795. var iteration = (loop.index * syncedIterations) + i;
  4796. if (iteration >= iterations)
  4797. break;
  4798. fn(iteration);
  4799. if (breakFunction && breakFunction()) {
  4800. loop.breakLoop();
  4801. break;
  4802. }
  4803. }
  4804. loop.executeNext();
  4805. }, timeout);
  4806. }
  4807. }, callback);
  4808. };
  4809. return AsyncLoop;
  4810. })();
  4811. BABYLON.AsyncLoop = AsyncLoop;
  4812. })(BABYLON || (BABYLON = {}));
  4813. var BABYLON;
  4814. (function (BABYLON) {
  4815. var _DepthCullingState = (function () {
  4816. function _DepthCullingState() {
  4817. this._isDepthTestDirty = false;
  4818. this._isDepthMaskDirty = false;
  4819. this._isDepthFuncDirty = false;
  4820. this._isCullFaceDirty = false;
  4821. this._isCullDirty = false;
  4822. this._isZOffsetDirty = false;
  4823. }
  4824. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4825. get: function () {
  4826. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4827. },
  4828. enumerable: true,
  4829. configurable: true
  4830. });
  4831. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4832. get: function () {
  4833. return this._zOffset;
  4834. },
  4835. set: function (value) {
  4836. if (this._zOffset === value) {
  4837. return;
  4838. }
  4839. this._zOffset = value;
  4840. this._isZOffsetDirty = true;
  4841. },
  4842. enumerable: true,
  4843. configurable: true
  4844. });
  4845. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4846. get: function () {
  4847. return this._cullFace;
  4848. },
  4849. set: function (value) {
  4850. if (this._cullFace === value) {
  4851. return;
  4852. }
  4853. this._cullFace = value;
  4854. this._isCullFaceDirty = true;
  4855. },
  4856. enumerable: true,
  4857. configurable: true
  4858. });
  4859. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4860. get: function () {
  4861. return this._cull;
  4862. },
  4863. set: function (value) {
  4864. if (this._cull === value) {
  4865. return;
  4866. }
  4867. this._cull = value;
  4868. this._isCullDirty = true;
  4869. },
  4870. enumerable: true,
  4871. configurable: true
  4872. });
  4873. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4874. get: function () {
  4875. return this._depthFunc;
  4876. },
  4877. set: function (value) {
  4878. if (this._depthFunc === value) {
  4879. return;
  4880. }
  4881. this._depthFunc = value;
  4882. this._isDepthFuncDirty = true;
  4883. },
  4884. enumerable: true,
  4885. configurable: true
  4886. });
  4887. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4888. get: function () {
  4889. return this._depthMask;
  4890. },
  4891. set: function (value) {
  4892. if (this._depthMask === value) {
  4893. return;
  4894. }
  4895. this._depthMask = value;
  4896. this._isDepthMaskDirty = true;
  4897. },
  4898. enumerable: true,
  4899. configurable: true
  4900. });
  4901. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4902. get: function () {
  4903. return this._depthTest;
  4904. },
  4905. set: function (value) {
  4906. if (this._depthTest === value) {
  4907. return;
  4908. }
  4909. this._depthTest = value;
  4910. this._isDepthTestDirty = true;
  4911. },
  4912. enumerable: true,
  4913. configurable: true
  4914. });
  4915. _DepthCullingState.prototype.reset = function () {
  4916. this._depthMask = true;
  4917. this._depthTest = true;
  4918. this._depthFunc = null;
  4919. this._cull = null;
  4920. this._cullFace = null;
  4921. this._zOffset = 0;
  4922. this._isDepthTestDirty = true;
  4923. this._isDepthMaskDirty = true;
  4924. this._isDepthFuncDirty = false;
  4925. this._isCullFaceDirty = false;
  4926. this._isCullDirty = false;
  4927. this._isZOffsetDirty = false;
  4928. };
  4929. _DepthCullingState.prototype.apply = function (gl) {
  4930. if (!this.isDirty) {
  4931. return;
  4932. }
  4933. // Cull
  4934. if (this._isCullDirty) {
  4935. if (this.cull) {
  4936. gl.enable(gl.CULL_FACE);
  4937. }
  4938. else {
  4939. gl.disable(gl.CULL_FACE);
  4940. }
  4941. this._isCullDirty = false;
  4942. }
  4943. // Cull face
  4944. if (this._isCullFaceDirty) {
  4945. gl.cullFace(this.cullFace);
  4946. this._isCullFaceDirty = false;
  4947. }
  4948. // Depth mask
  4949. if (this._isDepthMaskDirty) {
  4950. gl.depthMask(this.depthMask);
  4951. this._isDepthMaskDirty = false;
  4952. }
  4953. // Depth test
  4954. if (this._isDepthTestDirty) {
  4955. if (this.depthTest) {
  4956. gl.enable(gl.DEPTH_TEST);
  4957. }
  4958. else {
  4959. gl.disable(gl.DEPTH_TEST);
  4960. }
  4961. this._isDepthTestDirty = false;
  4962. }
  4963. // Depth func
  4964. if (this._isDepthFuncDirty) {
  4965. gl.depthFunc(this.depthFunc);
  4966. this._isDepthFuncDirty = false;
  4967. }
  4968. // zOffset
  4969. if (this._isZOffsetDirty) {
  4970. if (this.zOffset) {
  4971. gl.enable(gl.POLYGON_OFFSET_FILL);
  4972. gl.polygonOffset(this.zOffset, 0);
  4973. }
  4974. else {
  4975. gl.disable(gl.POLYGON_OFFSET_FILL);
  4976. }
  4977. this._isZOffsetDirty = false;
  4978. }
  4979. };
  4980. return _DepthCullingState;
  4981. })();
  4982. BABYLON._DepthCullingState = _DepthCullingState;
  4983. var _AlphaState = (function () {
  4984. function _AlphaState() {
  4985. this._isAlphaBlendDirty = false;
  4986. this._isBlendFunctionParametersDirty = false;
  4987. this._alphaBlend = false;
  4988. this._blendFunctionParameters = new Array(4);
  4989. }
  4990. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4991. get: function () {
  4992. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4993. },
  4994. enumerable: true,
  4995. configurable: true
  4996. });
  4997. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4998. get: function () {
  4999. return this._alphaBlend;
  5000. },
  5001. set: function (value) {
  5002. if (this._alphaBlend === value) {
  5003. return;
  5004. }
  5005. this._alphaBlend = value;
  5006. this._isAlphaBlendDirty = true;
  5007. },
  5008. enumerable: true,
  5009. configurable: true
  5010. });
  5011. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5012. if (this._blendFunctionParameters[0] === value0 &&
  5013. this._blendFunctionParameters[1] === value1 &&
  5014. this._blendFunctionParameters[2] === value2 &&
  5015. this._blendFunctionParameters[3] === value3) {
  5016. return;
  5017. }
  5018. this._blendFunctionParameters[0] = value0;
  5019. this._blendFunctionParameters[1] = value1;
  5020. this._blendFunctionParameters[2] = value2;
  5021. this._blendFunctionParameters[3] = value3;
  5022. this._isBlendFunctionParametersDirty = true;
  5023. };
  5024. _AlphaState.prototype.reset = function () {
  5025. this._alphaBlend = false;
  5026. this._blendFunctionParameters[0] = null;
  5027. this._blendFunctionParameters[1] = null;
  5028. this._blendFunctionParameters[2] = null;
  5029. this._blendFunctionParameters[3] = null;
  5030. this._isAlphaBlendDirty = true;
  5031. this._isBlendFunctionParametersDirty = false;
  5032. };
  5033. _AlphaState.prototype.apply = function (gl) {
  5034. if (!this.isDirty) {
  5035. return;
  5036. }
  5037. // Alpha blend
  5038. if (this._isAlphaBlendDirty) {
  5039. if (this._alphaBlend) {
  5040. gl.enable(gl.BLEND);
  5041. }
  5042. else {
  5043. gl.disable(gl.BLEND);
  5044. }
  5045. this._isAlphaBlendDirty = false;
  5046. }
  5047. // Alpha function
  5048. if (this._isBlendFunctionParametersDirty) {
  5049. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5050. this._isBlendFunctionParametersDirty = false;
  5051. }
  5052. };
  5053. return _AlphaState;
  5054. })();
  5055. BABYLON._AlphaState = _AlphaState;
  5056. var compileShader = function (gl, source, type, defines) {
  5057. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5058. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5059. gl.compileShader(shader);
  5060. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5061. throw new Error(gl.getShaderInfoLog(shader));
  5062. }
  5063. return shader;
  5064. };
  5065. var getWebGLTextureType = function (gl, type) {
  5066. var textureType = gl.UNSIGNED_BYTE;
  5067. if (type === Engine.TEXTURETYPE_FLOAT)
  5068. textureType = gl.FLOAT;
  5069. return textureType;
  5070. };
  5071. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5072. var magFilter = gl.NEAREST;
  5073. var minFilter = gl.NEAREST;
  5074. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5075. magFilter = gl.LINEAR;
  5076. if (generateMipMaps) {
  5077. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5078. }
  5079. else {
  5080. minFilter = gl.LINEAR;
  5081. }
  5082. }
  5083. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5084. magFilter = gl.LINEAR;
  5085. if (generateMipMaps) {
  5086. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5087. }
  5088. else {
  5089. minFilter = gl.LINEAR;
  5090. }
  5091. }
  5092. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5093. magFilter = gl.NEAREST;
  5094. if (generateMipMaps) {
  5095. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5096. }
  5097. else {
  5098. minFilter = gl.NEAREST;
  5099. }
  5100. }
  5101. return {
  5102. min: minFilter,
  5103. mag: magFilter
  5104. };
  5105. };
  5106. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5108. var engine = scene.getEngine();
  5109. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5110. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5111. gl.bindTexture(gl.TEXTURE_2D, texture);
  5112. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5113. texture._baseWidth = width;
  5114. texture._baseHeight = height;
  5115. texture._width = potWidth;
  5116. texture._height = potHeight;
  5117. texture.isReady = true;
  5118. processFunction(potWidth, potHeight);
  5119. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5122. if (!noMipmap && !isCompressed) {
  5123. gl.generateMipmap(gl.TEXTURE_2D);
  5124. }
  5125. gl.bindTexture(gl.TEXTURE_2D, null);
  5126. engine.resetTextureCache();
  5127. scene._removePendingData(texture);
  5128. };
  5129. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5130. var img;
  5131. var onload = function () {
  5132. loadedImages[index] = img;
  5133. loadedImages._internalCount++;
  5134. scene._removePendingData(img);
  5135. if (loadedImages._internalCount === 6) {
  5136. onfinish(loadedImages);
  5137. }
  5138. };
  5139. var onerror = function () {
  5140. scene._removePendingData(img);
  5141. };
  5142. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5143. scene._addPendingData(img);
  5144. };
  5145. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5146. var loadedImages = [];
  5147. loadedImages._internalCount = 0;
  5148. for (var index = 0; index < 6; index++) {
  5149. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5150. }
  5151. };
  5152. var EngineCapabilities = (function () {
  5153. function EngineCapabilities() {
  5154. }
  5155. return EngineCapabilities;
  5156. })();
  5157. BABYLON.EngineCapabilities = EngineCapabilities;
  5158. /**
  5159. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5160. */
  5161. var Engine = (function () {
  5162. /**
  5163. * @constructor
  5164. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5165. * @param {boolean} [antialias] - enable antialias
  5166. * @param options - further options to be sent to the getContext function
  5167. */
  5168. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5169. var _this = this;
  5170. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5171. // Public members
  5172. this.isFullscreen = false;
  5173. this.isPointerLock = false;
  5174. this.cullBackFaces = true;
  5175. this.renderEvenInBackground = true;
  5176. // To enable/disable IDB support and avoid XHR on .manifest
  5177. this.enableOfflineSupport = true;
  5178. this.scenes = new Array();
  5179. this._windowIsBackground = false;
  5180. this._drawCalls = 0;
  5181. this._renderingQueueLaunched = false;
  5182. this._activeRenderLoops = [];
  5183. // FPS
  5184. this.fpsRange = 60;
  5185. this.previousFramesDuration = [];
  5186. this.fps = 60;
  5187. this.deltaTime = 0;
  5188. // States
  5189. this._depthCullingState = new _DepthCullingState();
  5190. this._alphaState = new _AlphaState();
  5191. this._alphaMode = Engine.ALPHA_DISABLE;
  5192. // Cache
  5193. this._loadedTexturesCache = new Array();
  5194. this._maxTextureChannels = 16;
  5195. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5196. this._compiledEffects = {};
  5197. this._uintIndicesCurrentlySet = false;
  5198. this._renderingCanvas = canvas;
  5199. options = options || {};
  5200. options.antialias = antialias;
  5201. if (options.preserveDrawingBuffer === undefined) {
  5202. options.preserveDrawingBuffer = false;
  5203. }
  5204. // GL
  5205. try {
  5206. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5207. }
  5208. catch (e) {
  5209. throw new Error("WebGL not supported");
  5210. }
  5211. if (!this._gl) {
  5212. throw new Error("WebGL not supported");
  5213. }
  5214. this._onBlur = function () {
  5215. _this._windowIsBackground = true;
  5216. };
  5217. this._onFocus = function () {
  5218. _this._windowIsBackground = false;
  5219. };
  5220. window.addEventListener("blur", this._onBlur);
  5221. window.addEventListener("focus", this._onFocus);
  5222. // Viewport
  5223. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5224. this.resize();
  5225. // Caps
  5226. this._caps = new EngineCapabilities();
  5227. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5228. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5229. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5230. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5231. // Infos
  5232. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5233. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5234. if (rendererInfo != null) {
  5235. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5236. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5237. }
  5238. if (!this._glVendor) {
  5239. this._glVendor = "Unknown vendor";
  5240. }
  5241. if (!this._glRenderer) {
  5242. this._glRenderer = "Unknown renderer";
  5243. }
  5244. // Extensions
  5245. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5246. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5247. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5248. 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');
  5249. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5250. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5251. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5252. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5253. this._caps.highPrecisionShaderSupported = true;
  5254. if (this._gl.getShaderPrecisionFormat) {
  5255. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5256. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5257. }
  5258. // Depth buffer
  5259. this.setDepthBuffer(true);
  5260. this.setDepthFunctionToLessOrEqual();
  5261. this.setDepthWrite(true);
  5262. // Fullscreen
  5263. this._onFullscreenChange = function () {
  5264. if (document.fullscreen !== undefined) {
  5265. _this.isFullscreen = document.fullscreen;
  5266. }
  5267. else if (document.mozFullScreen !== undefined) {
  5268. _this.isFullscreen = document.mozFullScreen;
  5269. }
  5270. else if (document.webkitIsFullScreen !== undefined) {
  5271. _this.isFullscreen = document.webkitIsFullScreen;
  5272. }
  5273. else if (document.msIsFullScreen !== undefined) {
  5274. _this.isFullscreen = document.msIsFullScreen;
  5275. }
  5276. // Pointer lock
  5277. if (_this.isFullscreen && _this._pointerLockRequested) {
  5278. canvas.requestPointerLock = canvas.requestPointerLock ||
  5279. canvas.msRequestPointerLock ||
  5280. canvas.mozRequestPointerLock ||
  5281. canvas.webkitRequestPointerLock;
  5282. if (canvas.requestPointerLock) {
  5283. canvas.requestPointerLock();
  5284. }
  5285. }
  5286. };
  5287. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5288. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5289. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5290. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5291. // Pointer lock
  5292. this._onPointerLockChange = function () {
  5293. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5294. document.webkitPointerLockElement === canvas ||
  5295. document.msPointerLockElement === canvas ||
  5296. document.pointerLockElement === canvas);
  5297. };
  5298. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5299. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5300. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5301. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5302. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5303. Engine.audioEngine = new BABYLON.AudioEngine();
  5304. }
  5305. //default loading screen
  5306. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5307. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5308. }
  5309. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5310. get: function () {
  5311. return Engine._ALPHA_DISABLE;
  5312. },
  5313. enumerable: true,
  5314. configurable: true
  5315. });
  5316. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5317. get: function () {
  5318. return Engine._ALPHA_ONEONE;
  5319. },
  5320. enumerable: true,
  5321. configurable: true
  5322. });
  5323. Object.defineProperty(Engine, "ALPHA_ADD", {
  5324. get: function () {
  5325. return Engine._ALPHA_ADD;
  5326. },
  5327. enumerable: true,
  5328. configurable: true
  5329. });
  5330. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5331. get: function () {
  5332. return Engine._ALPHA_COMBINE;
  5333. },
  5334. enumerable: true,
  5335. configurable: true
  5336. });
  5337. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5338. get: function () {
  5339. return Engine._ALPHA_SUBTRACT;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5345. get: function () {
  5346. return Engine._ALPHA_MULTIPLY;
  5347. },
  5348. enumerable: true,
  5349. configurable: true
  5350. });
  5351. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5352. get: function () {
  5353. return Engine._ALPHA_MAXIMIZED;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5359. get: function () {
  5360. return Engine._DELAYLOADSTATE_NONE;
  5361. },
  5362. enumerable: true,
  5363. configurable: true
  5364. });
  5365. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5366. get: function () {
  5367. return Engine._DELAYLOADSTATE_LOADED;
  5368. },
  5369. enumerable: true,
  5370. configurable: true
  5371. });
  5372. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5373. get: function () {
  5374. return Engine._DELAYLOADSTATE_LOADING;
  5375. },
  5376. enumerable: true,
  5377. configurable: true
  5378. });
  5379. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5380. get: function () {
  5381. return Engine._DELAYLOADSTATE_NOTLOADED;
  5382. },
  5383. enumerable: true,
  5384. configurable: true
  5385. });
  5386. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5387. get: function () {
  5388. return Engine._TEXTUREFORMAT_ALPHA;
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5394. get: function () {
  5395. return Engine._TEXTUREFORMAT_LUMINANCE;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5401. get: function () {
  5402. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5403. },
  5404. enumerable: true,
  5405. configurable: true
  5406. });
  5407. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5408. get: function () {
  5409. return Engine._TEXTUREFORMAT_RGB;
  5410. },
  5411. enumerable: true,
  5412. configurable: true
  5413. });
  5414. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5415. get: function () {
  5416. return Engine._TEXTUREFORMAT_RGBA;
  5417. },
  5418. enumerable: true,
  5419. configurable: true
  5420. });
  5421. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5422. get: function () {
  5423. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5424. },
  5425. enumerable: true,
  5426. configurable: true
  5427. });
  5428. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5429. get: function () {
  5430. return Engine._TEXTURETYPE_FLOAT;
  5431. },
  5432. enumerable: true,
  5433. configurable: true
  5434. });
  5435. Object.defineProperty(Engine, "Version", {
  5436. get: function () {
  5437. return "2.3.0-beta";
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. Engine.prototype._prepareWorkingCanvas = function () {
  5443. if (this._workingCanvas) {
  5444. return;
  5445. }
  5446. this._workingCanvas = document.createElement("canvas");
  5447. this._workingContext = this._workingCanvas.getContext("2d");
  5448. };
  5449. Engine.prototype.resetTextureCache = function () {
  5450. for (var index = 0; index < this._maxTextureChannels; index++) {
  5451. this._activeTexturesCache[index] = null;
  5452. }
  5453. };
  5454. Engine.prototype.getGlInfo = function () {
  5455. return {
  5456. vendor: this._glVendor,
  5457. renderer: this._glRenderer,
  5458. version: this._glVersion
  5459. };
  5460. };
  5461. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5462. if (useScreen === void 0) { useScreen = false; }
  5463. var viewport = camera.viewport;
  5464. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5465. };
  5466. Engine.prototype.getRenderWidth = function (useScreen) {
  5467. if (useScreen === void 0) { useScreen = false; }
  5468. if (!useScreen && this._currentRenderTarget) {
  5469. return this._currentRenderTarget._width;
  5470. }
  5471. return this._renderingCanvas.width;
  5472. };
  5473. Engine.prototype.getRenderHeight = function (useScreen) {
  5474. if (useScreen === void 0) { useScreen = false; }
  5475. if (!useScreen && this._currentRenderTarget) {
  5476. return this._currentRenderTarget._height;
  5477. }
  5478. return this._renderingCanvas.height;
  5479. };
  5480. Engine.prototype.getRenderingCanvas = function () {
  5481. return this._renderingCanvas;
  5482. };
  5483. Engine.prototype.getRenderingCanvasClientRect = function () {
  5484. return this._renderingCanvas.getBoundingClientRect();
  5485. };
  5486. Engine.prototype.setHardwareScalingLevel = function (level) {
  5487. this._hardwareScalingLevel = level;
  5488. this.resize();
  5489. };
  5490. Engine.prototype.getHardwareScalingLevel = function () {
  5491. return this._hardwareScalingLevel;
  5492. };
  5493. Engine.prototype.getLoadedTexturesCache = function () {
  5494. return this._loadedTexturesCache;
  5495. };
  5496. Engine.prototype.getCaps = function () {
  5497. return this._caps;
  5498. };
  5499. Object.defineProperty(Engine.prototype, "drawCalls", {
  5500. get: function () {
  5501. return this._drawCalls;
  5502. },
  5503. enumerable: true,
  5504. configurable: true
  5505. });
  5506. // Methods
  5507. Engine.prototype.resetDrawCalls = function () {
  5508. this._drawCalls = 0;
  5509. };
  5510. Engine.prototype.setDepthFunctionToGreater = function () {
  5511. this._depthCullingState.depthFunc = this._gl.GREATER;
  5512. };
  5513. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5514. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5515. };
  5516. Engine.prototype.setDepthFunctionToLess = function () {
  5517. this._depthCullingState.depthFunc = this._gl.LESS;
  5518. };
  5519. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5520. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5521. };
  5522. /**
  5523. * stop executing a render loop function and remove it from the execution array
  5524. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5525. */
  5526. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5527. if (!renderFunction) {
  5528. this._activeRenderLoops = [];
  5529. return;
  5530. }
  5531. var index = this._activeRenderLoops.indexOf(renderFunction);
  5532. if (index >= 0) {
  5533. this._activeRenderLoops.splice(index, 1);
  5534. }
  5535. };
  5536. Engine.prototype._renderLoop = function () {
  5537. var shouldRender = true;
  5538. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5539. shouldRender = false;
  5540. }
  5541. if (shouldRender) {
  5542. // Start new frame
  5543. this.beginFrame();
  5544. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5545. var renderFunction = this._activeRenderLoops[index];
  5546. renderFunction();
  5547. }
  5548. // Present
  5549. this.endFrame();
  5550. }
  5551. if (this._activeRenderLoops.length > 0) {
  5552. // Register new frame
  5553. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5554. }
  5555. else {
  5556. this._renderingQueueLaunched = false;
  5557. }
  5558. };
  5559. /**
  5560. * Register and execute a render loop. The engine can have more than one render function.
  5561. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5562. * @example
  5563. * engine.runRenderLoop(function () {
  5564. * scene.render()
  5565. * })
  5566. */
  5567. Engine.prototype.runRenderLoop = function (renderFunction) {
  5568. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5569. return;
  5570. }
  5571. this._activeRenderLoops.push(renderFunction);
  5572. if (!this._renderingQueueLaunched) {
  5573. this._renderingQueueLaunched = true;
  5574. this._bindedRenderFunction = this._renderLoop.bind(this);
  5575. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5576. }
  5577. };
  5578. /**
  5579. * Toggle full screen mode.
  5580. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5581. */
  5582. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5583. if (this.isFullscreen) {
  5584. BABYLON.Tools.ExitFullscreen();
  5585. }
  5586. else {
  5587. this._pointerLockRequested = requestPointerLock;
  5588. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5589. }
  5590. };
  5591. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5592. this.applyStates();
  5593. if (backBuffer) {
  5594. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5595. }
  5596. if (depthStencil && this._depthCullingState.depthMask) {
  5597. this._gl.clearDepth(1.0);
  5598. }
  5599. var mode = 0;
  5600. if (backBuffer) {
  5601. mode |= this._gl.COLOR_BUFFER_BIT;
  5602. }
  5603. if (depthStencil && this._depthCullingState.depthMask) {
  5604. mode |= this._gl.DEPTH_BUFFER_BIT;
  5605. }
  5606. this._gl.clear(mode);
  5607. };
  5608. /**
  5609. * Set the WebGL's viewport
  5610. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5611. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5612. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5613. */
  5614. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5615. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5616. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5617. var x = viewport.x || 0;
  5618. var y = viewport.y || 0;
  5619. this._cachedViewport = viewport;
  5620. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5621. };
  5622. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5623. this._cachedViewport = null;
  5624. this._gl.viewport(x, y, width, height);
  5625. };
  5626. Engine.prototype.beginFrame = function () {
  5627. this._measureFps();
  5628. };
  5629. Engine.prototype.endFrame = function () {
  5630. //this.flushFramebuffer();
  5631. };
  5632. /**
  5633. * resize the view according to the canvas' size.
  5634. * @example
  5635. * window.addEventListener("resize", function () {
  5636. * engine.resize();
  5637. * });
  5638. */
  5639. Engine.prototype.resize = function () {
  5640. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5641. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5642. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5643. for (var index = 0; index < this.scenes.length; index++) {
  5644. var scene = this.scenes[index];
  5645. if (scene.debugLayer.isVisible()) {
  5646. scene.debugLayer._syncPositions();
  5647. }
  5648. }
  5649. };
  5650. /**
  5651. * force a specific size of the canvas
  5652. * @param {number} width - the new canvas' width
  5653. * @param {number} height - the new canvas' height
  5654. */
  5655. Engine.prototype.setSize = function (width, height) {
  5656. this._renderingCanvas.width = width;
  5657. this._renderingCanvas.height = height;
  5658. for (var index = 0; index < this.scenes.length; index++) {
  5659. var scene = this.scenes[index];
  5660. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5661. var cam = scene.cameras[camIndex];
  5662. cam._currentRenderId = 0;
  5663. }
  5664. }
  5665. };
  5666. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5667. this._currentRenderTarget = texture;
  5668. var gl = this._gl;
  5669. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5670. if (texture.isCube) {
  5671. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5672. }
  5673. else {
  5674. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5675. }
  5676. this._gl.viewport(0, 0, texture._width, texture._height);
  5677. this.wipeCaches();
  5678. };
  5679. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5680. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5681. this._currentRenderTarget = null;
  5682. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5683. var gl = this._gl;
  5684. gl.bindTexture(gl.TEXTURE_2D, texture);
  5685. gl.generateMipmap(gl.TEXTURE_2D);
  5686. gl.bindTexture(gl.TEXTURE_2D, null);
  5687. }
  5688. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5689. };
  5690. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5691. if (texture.generateMipMaps) {
  5692. var gl = this._gl;
  5693. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5694. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5695. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5696. }
  5697. };
  5698. Engine.prototype.flushFramebuffer = function () {
  5699. this._gl.flush();
  5700. };
  5701. Engine.prototype.restoreDefaultFramebuffer = function () {
  5702. this._currentRenderTarget = null;
  5703. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5704. this.setViewport(this._cachedViewport);
  5705. this.wipeCaches();
  5706. };
  5707. // VBOs
  5708. Engine.prototype._resetVertexBufferBinding = function () {
  5709. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5710. this._cachedVertexBuffers = null;
  5711. };
  5712. Engine.prototype.createVertexBuffer = function (vertices) {
  5713. var vbo = this._gl.createBuffer();
  5714. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5715. if (vertices instanceof Float32Array) {
  5716. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5717. }
  5718. else {
  5719. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5720. }
  5721. this._resetVertexBufferBinding();
  5722. vbo.references = 1;
  5723. return vbo;
  5724. };
  5725. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5726. var vbo = this._gl.createBuffer();
  5727. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5728. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5729. this._resetVertexBufferBinding();
  5730. vbo.references = 1;
  5731. return vbo;
  5732. };
  5733. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5734. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5735. if (offset === undefined) {
  5736. offset = 0;
  5737. }
  5738. if (vertices instanceof Float32Array) {
  5739. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5740. }
  5741. else {
  5742. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5743. }
  5744. this._resetVertexBufferBinding();
  5745. };
  5746. Engine.prototype._resetIndexBufferBinding = function () {
  5747. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5748. this._cachedIndexBuffer = null;
  5749. };
  5750. Engine.prototype.createIndexBuffer = function (indices) {
  5751. var vbo = this._gl.createBuffer();
  5752. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5753. // Check for 32 bits indices
  5754. var arrayBuffer;
  5755. var need32Bits = false;
  5756. if (this._caps.uintIndices) {
  5757. for (var index = 0; index < indices.length; index++) {
  5758. if (indices[index] > 65535) {
  5759. need32Bits = true;
  5760. break;
  5761. }
  5762. }
  5763. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5764. }
  5765. else {
  5766. arrayBuffer = new Uint16Array(indices);
  5767. }
  5768. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5769. this._resetIndexBufferBinding();
  5770. vbo.references = 1;
  5771. vbo.is32Bits = need32Bits;
  5772. return vbo;
  5773. };
  5774. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5775. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5776. this._cachedVertexBuffers = vertexBuffer;
  5777. this._cachedEffectForVertexBuffers = effect;
  5778. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5779. var offset = 0;
  5780. for (var index = 0; index < vertexDeclaration.length; index++) {
  5781. var order = effect.getAttributeLocation(index);
  5782. if (order >= 0) {
  5783. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5784. }
  5785. offset += vertexDeclaration[index] * 4;
  5786. }
  5787. }
  5788. if (this._cachedIndexBuffer !== indexBuffer) {
  5789. this._cachedIndexBuffer = indexBuffer;
  5790. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5791. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5792. }
  5793. };
  5794. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5795. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5796. this._cachedVertexBuffers = vertexBuffers;
  5797. this._cachedEffectForVertexBuffers = effect;
  5798. var attributes = effect.getAttributesNames();
  5799. for (var index = 0; index < attributes.length; index++) {
  5800. var order = effect.getAttributeLocation(index);
  5801. if (order >= 0) {
  5802. var vertexBuffer = vertexBuffers[attributes[index]];
  5803. if (!vertexBuffer) {
  5804. continue;
  5805. }
  5806. var stride = vertexBuffer.getStrideSize();
  5807. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5808. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5809. }
  5810. }
  5811. }
  5812. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5813. this._cachedIndexBuffer = indexBuffer;
  5814. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5815. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5816. }
  5817. };
  5818. Engine.prototype._releaseBuffer = function (buffer) {
  5819. buffer.references--;
  5820. if (buffer.references === 0) {
  5821. this._gl.deleteBuffer(buffer);
  5822. return true;
  5823. }
  5824. return false;
  5825. };
  5826. Engine.prototype.createInstancesBuffer = function (capacity) {
  5827. var buffer = this._gl.createBuffer();
  5828. buffer.capacity = capacity;
  5829. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5830. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5831. return buffer;
  5832. };
  5833. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5834. this._gl.deleteBuffer(buffer);
  5835. };
  5836. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5837. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5838. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5839. for (var index = 0; index < 4; index++) {
  5840. var offsetLocation = offsetLocations[index];
  5841. this._gl.enableVertexAttribArray(offsetLocation);
  5842. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5843. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5844. }
  5845. };
  5846. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5847. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5848. for (var index = 0; index < 4; index++) {
  5849. var offsetLocation = offsetLocations[index];
  5850. this._gl.disableVertexAttribArray(offsetLocation);
  5851. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5852. }
  5853. };
  5854. Engine.prototype.applyStates = function () {
  5855. this._depthCullingState.apply(this._gl);
  5856. this._alphaState.apply(this._gl);
  5857. };
  5858. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5859. // Apply states
  5860. this.applyStates();
  5861. this._drawCalls++;
  5862. // Render
  5863. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5864. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5865. if (instancesCount) {
  5866. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5867. return;
  5868. }
  5869. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5870. };
  5871. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5872. // Apply states
  5873. this.applyStates();
  5874. this._drawCalls++;
  5875. if (instancesCount) {
  5876. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5877. return;
  5878. }
  5879. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5880. };
  5881. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5882. // Apply states
  5883. this.applyStates();
  5884. this._drawCalls++;
  5885. if (instancesCount) {
  5886. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5887. return;
  5888. }
  5889. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5890. };
  5891. // Shaders
  5892. Engine.prototype._releaseEffect = function (effect) {
  5893. if (this._compiledEffects[effect._key]) {
  5894. delete this._compiledEffects[effect._key];
  5895. if (effect.getProgram()) {
  5896. this._gl.deleteProgram(effect.getProgram());
  5897. }
  5898. }
  5899. };
  5900. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5901. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5902. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5903. var name = vertex + "+" + fragment + "@" + defines;
  5904. if (this._compiledEffects[name]) {
  5905. return this._compiledEffects[name];
  5906. }
  5907. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5908. effect._key = name;
  5909. this._compiledEffects[name] = effect;
  5910. return effect;
  5911. };
  5912. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5913. if (uniformsNames === void 0) { uniformsNames = []; }
  5914. if (samplers === void 0) { samplers = []; }
  5915. if (defines === void 0) { defines = ""; }
  5916. return this.createEffect({
  5917. vertex: "particles",
  5918. fragmentElement: fragmentName
  5919. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5920. };
  5921. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5922. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5923. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5924. var shaderProgram = this._gl.createProgram();
  5925. this._gl.attachShader(shaderProgram, vertexShader);
  5926. this._gl.attachShader(shaderProgram, fragmentShader);
  5927. this._gl.linkProgram(shaderProgram);
  5928. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5929. if (!linked) {
  5930. var error = this._gl.getProgramInfoLog(shaderProgram);
  5931. if (error) {
  5932. throw new Error(error);
  5933. }
  5934. }
  5935. this._gl.deleteShader(vertexShader);
  5936. this._gl.deleteShader(fragmentShader);
  5937. return shaderProgram;
  5938. };
  5939. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5940. var results = [];
  5941. for (var index = 0; index < uniformsNames.length; index++) {
  5942. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5943. }
  5944. return results;
  5945. };
  5946. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5947. var results = [];
  5948. for (var index = 0; index < attributesNames.length; index++) {
  5949. try {
  5950. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5951. }
  5952. catch (e) {
  5953. results.push(-1);
  5954. }
  5955. }
  5956. return results;
  5957. };
  5958. Engine.prototype.enableEffect = function (effect) {
  5959. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5960. if (effect && effect.onBind) {
  5961. effect.onBind(effect);
  5962. }
  5963. return;
  5964. }
  5965. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5966. // Use program
  5967. this._gl.useProgram(effect.getProgram());
  5968. for (var i in this._vertexAttribArrays) {
  5969. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5970. continue;
  5971. }
  5972. this._vertexAttribArrays[i] = false;
  5973. this._gl.disableVertexAttribArray(i);
  5974. }
  5975. var attributesCount = effect.getAttributesCount();
  5976. for (var index = 0; index < attributesCount; index++) {
  5977. // Attributes
  5978. var order = effect.getAttributeLocation(index);
  5979. if (order >= 0) {
  5980. this._vertexAttribArrays[order] = true;
  5981. this._gl.enableVertexAttribArray(order);
  5982. }
  5983. }
  5984. this._currentEffect = effect;
  5985. if (effect.onBind) {
  5986. effect.onBind(effect);
  5987. }
  5988. };
  5989. Engine.prototype.setArray = function (uniform, array) {
  5990. if (!uniform)
  5991. return;
  5992. this._gl.uniform1fv(uniform, array);
  5993. };
  5994. Engine.prototype.setArray2 = function (uniform, array) {
  5995. if (!uniform || array.length % 2 !== 0)
  5996. return;
  5997. this._gl.uniform2fv(uniform, array);
  5998. };
  5999. Engine.prototype.setArray3 = function (uniform, array) {
  6000. if (!uniform || array.length % 3 !== 0)
  6001. return;
  6002. this._gl.uniform3fv(uniform, array);
  6003. };
  6004. Engine.prototype.setArray4 = function (uniform, array) {
  6005. if (!uniform || array.length % 4 !== 0)
  6006. return;
  6007. this._gl.uniform4fv(uniform, array);
  6008. };
  6009. Engine.prototype.setMatrices = function (uniform, matrices) {
  6010. if (!uniform)
  6011. return;
  6012. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6013. };
  6014. Engine.prototype.setMatrix = function (uniform, matrix) {
  6015. if (!uniform)
  6016. return;
  6017. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6018. };
  6019. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6020. if (!uniform)
  6021. return;
  6022. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6023. };
  6024. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6025. if (!uniform)
  6026. return;
  6027. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6028. };
  6029. Engine.prototype.setFloat = function (uniform, value) {
  6030. if (!uniform)
  6031. return;
  6032. this._gl.uniform1f(uniform, value);
  6033. };
  6034. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6035. if (!uniform)
  6036. return;
  6037. this._gl.uniform2f(uniform, x, y);
  6038. };
  6039. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6040. if (!uniform)
  6041. return;
  6042. this._gl.uniform3f(uniform, x, y, z);
  6043. };
  6044. Engine.prototype.setBool = function (uniform, bool) {
  6045. if (!uniform)
  6046. return;
  6047. this._gl.uniform1i(uniform, bool);
  6048. };
  6049. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6050. if (!uniform)
  6051. return;
  6052. this._gl.uniform4f(uniform, x, y, z, w);
  6053. };
  6054. Engine.prototype.setColor3 = function (uniform, color3) {
  6055. if (!uniform)
  6056. return;
  6057. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6058. };
  6059. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6060. if (!uniform)
  6061. return;
  6062. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6063. };
  6064. // States
  6065. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6066. if (zOffset === void 0) { zOffset = 0; }
  6067. if (reverseSide === void 0) { reverseSide = false; }
  6068. // Culling
  6069. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6070. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6071. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6072. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6073. if (culling) {
  6074. this._depthCullingState.cullFace = cullFace;
  6075. this._depthCullingState.cull = true;
  6076. }
  6077. else {
  6078. this._depthCullingState.cull = false;
  6079. }
  6080. }
  6081. // Z offset
  6082. this._depthCullingState.zOffset = zOffset;
  6083. };
  6084. Engine.prototype.setDepthBuffer = function (enable) {
  6085. this._depthCullingState.depthTest = enable;
  6086. };
  6087. Engine.prototype.getDepthWrite = function () {
  6088. return this._depthCullingState.depthMask;
  6089. };
  6090. Engine.prototype.setDepthWrite = function (enable) {
  6091. this._depthCullingState.depthMask = enable;
  6092. };
  6093. Engine.prototype.setColorWrite = function (enable) {
  6094. this._gl.colorMask(enable, enable, enable, enable);
  6095. };
  6096. Engine.prototype.setAlphaMode = function (mode) {
  6097. if (this._alphaMode === mode) {
  6098. return;
  6099. }
  6100. switch (mode) {
  6101. case Engine.ALPHA_DISABLE:
  6102. this.setDepthWrite(true);
  6103. this._alphaState.alphaBlend = false;
  6104. break;
  6105. case Engine.ALPHA_COMBINE:
  6106. this.setDepthWrite(false);
  6107. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6108. this._alphaState.alphaBlend = true;
  6109. break;
  6110. case Engine.ALPHA_ONEONE:
  6111. this.setDepthWrite(false);
  6112. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6113. this._alphaState.alphaBlend = true;
  6114. break;
  6115. case Engine.ALPHA_ADD:
  6116. this.setDepthWrite(false);
  6117. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6118. this._alphaState.alphaBlend = true;
  6119. break;
  6120. case Engine.ALPHA_SUBTRACT:
  6121. this.setDepthWrite(false);
  6122. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6123. this._alphaState.alphaBlend = true;
  6124. break;
  6125. case Engine.ALPHA_MULTIPLY:
  6126. this.setDepthWrite(false);
  6127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6128. this._alphaState.alphaBlend = true;
  6129. break;
  6130. case Engine.ALPHA_MAXIMIZED:
  6131. this.setDepthWrite(false);
  6132. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6133. this._alphaState.alphaBlend = true;
  6134. break;
  6135. }
  6136. this._alphaMode = mode;
  6137. };
  6138. Engine.prototype.getAlphaMode = function () {
  6139. return this._alphaMode;
  6140. };
  6141. Engine.prototype.setAlphaTesting = function (enable) {
  6142. this._alphaTest = enable;
  6143. };
  6144. Engine.prototype.getAlphaTesting = function () {
  6145. return this._alphaTest;
  6146. };
  6147. // Textures
  6148. Engine.prototype.wipeCaches = function () {
  6149. this.resetTextureCache();
  6150. this._currentEffect = null;
  6151. this._depthCullingState.reset();
  6152. this._alphaState.reset();
  6153. this._cachedVertexBuffers = null;
  6154. this._cachedIndexBuffer = null;
  6155. this._cachedEffectForVertexBuffers = null;
  6156. };
  6157. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6158. var gl = this._gl;
  6159. gl.bindTexture(gl.TEXTURE_2D, texture);
  6160. var magFilter = gl.NEAREST;
  6161. var minFilter = gl.NEAREST;
  6162. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6163. magFilter = gl.LINEAR;
  6164. minFilter = gl.LINEAR;
  6165. }
  6166. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6167. magFilter = gl.LINEAR;
  6168. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6169. }
  6170. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6172. gl.bindTexture(gl.TEXTURE_2D, null);
  6173. texture.samplingMode = samplingMode;
  6174. };
  6175. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6176. var _this = this;
  6177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6178. if (onLoad === void 0) { onLoad = null; }
  6179. if (onError === void 0) { onError = null; }
  6180. if (buffer === void 0) { buffer = null; }
  6181. var texture = this._gl.createTexture();
  6182. var extension;
  6183. var fromData = false;
  6184. if (url.substr(0, 5) === "data:") {
  6185. fromData = true;
  6186. }
  6187. if (!fromData)
  6188. extension = url.substr(url.length - 4, 4).toLowerCase();
  6189. else {
  6190. var oldUrl = url;
  6191. fromData = oldUrl.split(':');
  6192. url = oldUrl;
  6193. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6194. }
  6195. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6196. var isTGA = (extension === ".tga");
  6197. scene._addPendingData(texture);
  6198. texture.url = url;
  6199. texture.noMipmap = noMipmap;
  6200. texture.references = 1;
  6201. texture.samplingMode = samplingMode;
  6202. this._loadedTexturesCache.push(texture);
  6203. var onerror = function () {
  6204. scene._removePendingData(texture);
  6205. if (onError) {
  6206. onError();
  6207. }
  6208. };
  6209. var callback;
  6210. if (isTGA) {
  6211. callback = function (arrayBuffer) {
  6212. var data = new Uint8Array(arrayBuffer);
  6213. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6214. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6215. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6216. if (onLoad) {
  6217. onLoad();
  6218. }
  6219. }, samplingMode);
  6220. };
  6221. if (!(fromData instanceof Array))
  6222. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6223. callback(arrayBuffer);
  6224. }, onerror, scene.database, true);
  6225. else
  6226. callback(buffer);
  6227. }
  6228. else if (isDDS) {
  6229. callback = function (data) {
  6230. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6231. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6232. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6233. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6234. if (onLoad) {
  6235. onLoad();
  6236. }
  6237. }, samplingMode);
  6238. };
  6239. if (!(fromData instanceof Array))
  6240. BABYLON.Tools.LoadFile(url, function (data) {
  6241. callback(data);
  6242. }, onerror, scene.database, true);
  6243. else
  6244. callback(buffer);
  6245. }
  6246. else {
  6247. var onload = function (img) {
  6248. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6249. var isPot = (img.width === potWidth && img.height === potHeight);
  6250. if (!isPot) {
  6251. _this._prepareWorkingCanvas();
  6252. _this._workingCanvas.width = potWidth;
  6253. _this._workingCanvas.height = potHeight;
  6254. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6255. _this._workingContext.imageSmoothingEnabled = false;
  6256. _this._workingContext.mozImageSmoothingEnabled = false;
  6257. _this._workingContext.oImageSmoothingEnabled = false;
  6258. _this._workingContext.webkitImageSmoothingEnabled = false;
  6259. _this._workingContext.msImageSmoothingEnabled = false;
  6260. }
  6261. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6262. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6263. _this._workingContext.imageSmoothingEnabled = true;
  6264. _this._workingContext.mozImageSmoothingEnabled = true;
  6265. _this._workingContext.oImageSmoothingEnabled = true;
  6266. _this._workingContext.webkitImageSmoothingEnabled = true;
  6267. _this._workingContext.msImageSmoothingEnabled = true;
  6268. }
  6269. }
  6270. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6271. if (onLoad) {
  6272. onLoad();
  6273. }
  6274. }, samplingMode);
  6275. };
  6276. if (!(fromData instanceof Array))
  6277. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6278. else
  6279. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6280. }
  6281. return texture;
  6282. };
  6283. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6284. if (compression === void 0) { compression = null; }
  6285. var internalFormat = this._gl.RGBA;
  6286. switch (format) {
  6287. case Engine.TEXTUREFORMAT_ALPHA:
  6288. internalFormat = this._gl.ALPHA;
  6289. break;
  6290. case Engine.TEXTUREFORMAT_LUMINANCE:
  6291. internalFormat = this._gl.LUMINANCE;
  6292. break;
  6293. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6294. internalFormat = this._gl.LUMINANCE_ALPHA;
  6295. break;
  6296. case Engine.TEXTUREFORMAT_RGB:
  6297. internalFormat = this._gl.RGB;
  6298. break;
  6299. case Engine.TEXTUREFORMAT_RGBA:
  6300. internalFormat = this._gl.RGBA;
  6301. break;
  6302. }
  6303. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6304. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6305. if (compression) {
  6306. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6307. }
  6308. else {
  6309. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6310. }
  6311. if (texture.generateMipMaps) {
  6312. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6313. }
  6314. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6315. this.resetTextureCache();
  6316. texture.isReady = true;
  6317. };
  6318. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6319. if (compression === void 0) { compression = null; }
  6320. var texture = this._gl.createTexture();
  6321. texture._baseWidth = width;
  6322. texture._baseHeight = height;
  6323. texture._width = width;
  6324. texture._height = height;
  6325. texture.references = 1;
  6326. this.updateRawTexture(texture, data, format, invertY, compression);
  6327. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6328. // Filters
  6329. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6332. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6333. texture.samplingMode = samplingMode;
  6334. this._loadedTexturesCache.push(texture);
  6335. return texture;
  6336. };
  6337. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6338. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6339. var texture = this._gl.createTexture();
  6340. texture._baseWidth = width;
  6341. texture._baseHeight = height;
  6342. if (forceExponantOfTwo) {
  6343. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6344. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6345. }
  6346. this.resetTextureCache();
  6347. texture._width = width;
  6348. texture._height = height;
  6349. texture.isReady = false;
  6350. texture.generateMipMaps = generateMipMaps;
  6351. texture.references = 1;
  6352. texture.samplingMode = samplingMode;
  6353. this.updateTextureSamplingMode(samplingMode, texture);
  6354. this._loadedTexturesCache.push(texture);
  6355. return texture;
  6356. };
  6357. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6358. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6359. if (texture.isCube) {
  6360. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6361. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6362. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6363. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6364. }
  6365. else {
  6366. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6369. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6370. }
  6371. };
  6372. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6373. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6374. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6375. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6376. if (texture.generateMipMaps) {
  6377. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6378. }
  6379. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6380. this.resetTextureCache();
  6381. texture.isReady = true;
  6382. };
  6383. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6384. if (texture._isDisabled) {
  6385. return;
  6386. }
  6387. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6388. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6389. try {
  6390. // Testing video texture support
  6391. if (this._videoTextureSupported === undefined) {
  6392. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6393. if (this._gl.getError() !== 0) {
  6394. this._videoTextureSupported = false;
  6395. }
  6396. else {
  6397. this._videoTextureSupported = true;
  6398. }
  6399. }
  6400. // Copy video through the current working canvas if video texture is not supported
  6401. if (!this._videoTextureSupported) {
  6402. if (!texture._workingCanvas) {
  6403. texture._workingCanvas = document.createElement("canvas");
  6404. texture._workingContext = texture._workingCanvas.getContext("2d");
  6405. texture._workingCanvas.width = texture._width;
  6406. texture._workingCanvas.height = texture._height;
  6407. }
  6408. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6409. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6410. }
  6411. else {
  6412. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6413. }
  6414. if (texture.generateMipMaps) {
  6415. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6416. }
  6417. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6418. this.resetTextureCache();
  6419. texture.isReady = true;
  6420. }
  6421. catch (ex) {
  6422. // Something unexpected
  6423. // Let's disable the texture
  6424. texture._isDisabled = true;
  6425. }
  6426. };
  6427. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6428. // old version had a "generateMipMaps" arg instead of options.
  6429. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6430. // in the same way, generateDepthBuffer is defaulted to true
  6431. var generateMipMaps = false;
  6432. var generateDepthBuffer = true;
  6433. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6434. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6435. if (options !== undefined) {
  6436. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6437. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6438. type = options.type === undefined ? type : options.type;
  6439. if (options.samplingMode !== undefined) {
  6440. samplingMode = options.samplingMode;
  6441. }
  6442. if (type === Engine.TEXTURETYPE_FLOAT) {
  6443. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6444. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6445. }
  6446. }
  6447. var gl = this._gl;
  6448. var texture = gl.createTexture();
  6449. gl.bindTexture(gl.TEXTURE_2D, texture);
  6450. var width = size.width || size;
  6451. var height = size.height || size;
  6452. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6453. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6454. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6455. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6456. }
  6457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6461. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6462. var depthBuffer;
  6463. // Create the depth buffer
  6464. if (generateDepthBuffer) {
  6465. depthBuffer = gl.createRenderbuffer();
  6466. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6467. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6468. }
  6469. // Create the framebuffer
  6470. var framebuffer = gl.createFramebuffer();
  6471. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6472. if (generateDepthBuffer) {
  6473. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6474. }
  6475. if (generateMipMaps) {
  6476. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6477. }
  6478. // Unbind
  6479. gl.bindTexture(gl.TEXTURE_2D, null);
  6480. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6481. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6482. texture._framebuffer = framebuffer;
  6483. if (generateDepthBuffer) {
  6484. texture._depthBuffer = depthBuffer;
  6485. }
  6486. texture._width = width;
  6487. texture._height = height;
  6488. texture.isReady = true;
  6489. texture.generateMipMaps = generateMipMaps;
  6490. texture.references = 1;
  6491. texture.samplingMode = samplingMode;
  6492. this.resetTextureCache();
  6493. this._loadedTexturesCache.push(texture);
  6494. return texture;
  6495. };
  6496. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6497. var gl = this._gl;
  6498. var texture = gl.createTexture();
  6499. var generateMipMaps = true;
  6500. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6501. if (options !== undefined) {
  6502. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6503. if (options.samplingMode !== undefined) {
  6504. samplingMode = options.samplingMode;
  6505. }
  6506. }
  6507. texture.isCube = true;
  6508. texture.references = 1;
  6509. texture.generateMipMaps = generateMipMaps;
  6510. texture.references = 1;
  6511. texture.samplingMode = samplingMode;
  6512. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6513. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6514. for (var face = 0; face < 6; face++) {
  6515. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6516. }
  6517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6521. // Create the depth buffer
  6522. var depthBuffer = gl.createRenderbuffer();
  6523. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6524. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6525. // Create the framebuffer
  6526. var framebuffer = gl.createFramebuffer();
  6527. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6528. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6529. // mipmaps
  6530. if (texture.generateMipMaps) {
  6531. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6532. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6533. }
  6534. // Unbind
  6535. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6536. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6537. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6538. texture._framebuffer = framebuffer;
  6539. texture._depthBuffer = depthBuffer;
  6540. this.resetTextureCache();
  6541. texture._width = size;
  6542. texture._height = size;
  6543. texture.isReady = true;
  6544. return texture;
  6545. };
  6546. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6547. var _this = this;
  6548. var gl = this._gl;
  6549. var texture = gl.createTexture();
  6550. texture.isCube = true;
  6551. texture.url = rootUrl;
  6552. texture.references = 1;
  6553. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6554. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6555. if (isDDS) {
  6556. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6557. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6558. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6559. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6560. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6561. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6562. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6563. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6564. }
  6565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6567. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6568. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6569. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6570. _this.resetTextureCache();
  6571. texture._width = info.width;
  6572. texture._height = info.height;
  6573. texture.isReady = true;
  6574. }, null, null, true);
  6575. }
  6576. else {
  6577. cascadeLoad(rootUrl, scene, function (imgs) {
  6578. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6579. var height = width;
  6580. _this._prepareWorkingCanvas();
  6581. _this._workingCanvas.width = width;
  6582. _this._workingCanvas.height = height;
  6583. var faces = [
  6584. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6585. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6586. ];
  6587. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6588. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6589. for (var index = 0; index < faces.length; index++) {
  6590. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6591. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6592. }
  6593. if (!noMipmap) {
  6594. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6595. }
  6596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6597. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6600. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6601. _this.resetTextureCache();
  6602. texture._width = width;
  6603. texture._height = height;
  6604. texture.isReady = true;
  6605. }, extensions);
  6606. }
  6607. return texture;
  6608. };
  6609. Engine.prototype._releaseTexture = function (texture) {
  6610. var gl = this._gl;
  6611. if (texture._framebuffer) {
  6612. gl.deleteFramebuffer(texture._framebuffer);
  6613. }
  6614. if (texture._depthBuffer) {
  6615. gl.deleteRenderbuffer(texture._depthBuffer);
  6616. }
  6617. gl.deleteTexture(texture);
  6618. // Unbind channels
  6619. this.unbindAllTextures();
  6620. var index = this._loadedTexturesCache.indexOf(texture);
  6621. if (index !== -1) {
  6622. this._loadedTexturesCache.splice(index, 1);
  6623. }
  6624. };
  6625. Engine.prototype.bindSamplers = function (effect) {
  6626. this._gl.useProgram(effect.getProgram());
  6627. var samplers = effect.getSamplers();
  6628. for (var index = 0; index < samplers.length; index++) {
  6629. var uniform = effect.getUniform(samplers[index]);
  6630. this._gl.uniform1i(uniform, index);
  6631. }
  6632. this._currentEffect = null;
  6633. };
  6634. Engine.prototype._bindTexture = function (channel, texture) {
  6635. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6636. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6637. this._activeTexturesCache[channel] = null;
  6638. };
  6639. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6640. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6641. };
  6642. Engine.prototype.unbindAllTextures = function () {
  6643. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6644. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6645. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6646. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6647. this._activeTexturesCache[channel] = null;
  6648. }
  6649. };
  6650. Engine.prototype.setTexture = function (channel, texture) {
  6651. if (channel < 0) {
  6652. return;
  6653. }
  6654. // Not ready?
  6655. if (!texture || !texture.isReady()) {
  6656. if (this._activeTexturesCache[channel] != null) {
  6657. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6658. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6659. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6660. this._activeTexturesCache[channel] = null;
  6661. }
  6662. return;
  6663. }
  6664. // Video
  6665. var alreadyActivated = false;
  6666. if (texture instanceof BABYLON.VideoTexture) {
  6667. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6668. alreadyActivated = true;
  6669. texture.update();
  6670. }
  6671. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6672. texture.delayLoad();
  6673. return;
  6674. }
  6675. if (this._activeTexturesCache[channel] === texture) {
  6676. return;
  6677. }
  6678. this._activeTexturesCache[channel] = texture;
  6679. var internalTexture = texture.getInternalTexture();
  6680. if (!alreadyActivated) {
  6681. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6682. }
  6683. if (internalTexture.isCube) {
  6684. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6685. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6686. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6687. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6688. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6689. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6690. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6691. }
  6692. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6693. }
  6694. else {
  6695. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6696. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6697. internalTexture._cachedWrapU = texture.wrapU;
  6698. switch (texture.wrapU) {
  6699. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6700. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6701. break;
  6702. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6703. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6704. break;
  6705. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6706. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6707. break;
  6708. }
  6709. }
  6710. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6711. internalTexture._cachedWrapV = texture.wrapV;
  6712. switch (texture.wrapV) {
  6713. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6714. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6715. break;
  6716. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6717. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6718. break;
  6719. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6720. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6721. break;
  6722. }
  6723. }
  6724. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6725. }
  6726. };
  6727. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6728. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6729. var value = texture.anisotropicFilteringLevel;
  6730. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6731. value = 1;
  6732. }
  6733. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6734. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6735. texture._cachedAnisotropicFilteringLevel = value;
  6736. }
  6737. };
  6738. Engine.prototype.readPixels = function (x, y, width, height) {
  6739. var data = new Uint8Array(height * width * 4);
  6740. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6741. return data;
  6742. };
  6743. Engine.prototype.releaseInternalTexture = function (texture) {
  6744. if (!texture) {
  6745. return;
  6746. }
  6747. texture.references--;
  6748. // Final reference ?
  6749. if (texture.references === 0) {
  6750. var texturesCache = this.getLoadedTexturesCache();
  6751. var index = texturesCache.indexOf(texture);
  6752. if (index > -1) {
  6753. texturesCache.splice(index, 1);
  6754. }
  6755. this._releaseTexture(texture);
  6756. }
  6757. };
  6758. // Dispose
  6759. Engine.prototype.dispose = function () {
  6760. this.hideLoadingUI();
  6761. this.stopRenderLoop();
  6762. // Release scenes
  6763. while (this.scenes.length) {
  6764. this.scenes[0].dispose();
  6765. }
  6766. // Release audio engine
  6767. Engine.audioEngine.dispose();
  6768. // Release effects
  6769. for (var name in this._compiledEffects) {
  6770. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6771. }
  6772. // Unbind
  6773. for (var i in this._vertexAttribArrays) {
  6774. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6775. continue;
  6776. }
  6777. this._gl.disableVertexAttribArray(i);
  6778. }
  6779. this._gl = null;
  6780. // Events
  6781. window.removeEventListener("blur", this._onBlur);
  6782. window.removeEventListener("focus", this._onFocus);
  6783. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6784. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6785. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6786. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6787. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6788. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6789. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6790. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6791. };
  6792. // Loading screen
  6793. Engine.prototype.displayLoadingUI = function () {
  6794. this._loadingScreen.displayLoadingUI();
  6795. };
  6796. Engine.prototype.hideLoadingUI = function () {
  6797. this._loadingScreen.hideLoadingUI();
  6798. };
  6799. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6800. get: function () {
  6801. return this._loadingScreen;
  6802. },
  6803. set: function (loadingScreen) {
  6804. this._loadingScreen = loadingScreen;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6810. set: function (text) {
  6811. this._loadingScreen.loadingUIText = text;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6817. set: function (color) {
  6818. this._loadingScreen.loadingUIBackgroundColor = color;
  6819. },
  6820. enumerable: true,
  6821. configurable: true
  6822. });
  6823. // FPS
  6824. Engine.prototype.getFps = function () {
  6825. return this.fps;
  6826. };
  6827. Engine.prototype.getDeltaTime = function () {
  6828. return this.deltaTime;
  6829. };
  6830. Engine.prototype._measureFps = function () {
  6831. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6832. var length = this.previousFramesDuration.length;
  6833. if (length >= 2) {
  6834. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6835. }
  6836. if (length >= this.fpsRange) {
  6837. if (length > this.fpsRange) {
  6838. this.previousFramesDuration.splice(0, 1);
  6839. length = this.previousFramesDuration.length;
  6840. }
  6841. var sum = 0;
  6842. for (var id = 0; id < length - 1; id++) {
  6843. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6844. }
  6845. this.fps = 1000.0 / (sum / (length - 1));
  6846. }
  6847. };
  6848. // Statics
  6849. Engine.isSupported = function () {
  6850. try {
  6851. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6852. if (navigator.isCocoonJS) {
  6853. return true;
  6854. }
  6855. var tempcanvas = document.createElement("canvas");
  6856. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6857. return gl != null && !!window.WebGLRenderingContext;
  6858. }
  6859. catch (e) {
  6860. return false;
  6861. }
  6862. };
  6863. // Const statics
  6864. Engine._ALPHA_DISABLE = 0;
  6865. Engine._ALPHA_ADD = 1;
  6866. Engine._ALPHA_COMBINE = 2;
  6867. Engine._ALPHA_SUBTRACT = 3;
  6868. Engine._ALPHA_MULTIPLY = 4;
  6869. Engine._ALPHA_MAXIMIZED = 5;
  6870. Engine._ALPHA_ONEONE = 6;
  6871. Engine._DELAYLOADSTATE_NONE = 0;
  6872. Engine._DELAYLOADSTATE_LOADED = 1;
  6873. Engine._DELAYLOADSTATE_LOADING = 2;
  6874. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6875. Engine._TEXTUREFORMAT_ALPHA = 0;
  6876. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6877. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6878. Engine._TEXTUREFORMAT_RGB = 4;
  6879. Engine._TEXTUREFORMAT_RGBA = 5;
  6880. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6881. Engine._TEXTURETYPE_FLOAT = 1;
  6882. // Updatable statics so stick with vars here
  6883. Engine.Epsilon = 0.001;
  6884. Engine.CollisionsEpsilon = 0.001;
  6885. Engine.CodeRepository = "src/";
  6886. Engine.ShadersRepository = "src/Shaders/";
  6887. return Engine;
  6888. })();
  6889. BABYLON.Engine = Engine;
  6890. })(BABYLON || (BABYLON = {}));
  6891. var BABYLON;
  6892. (function (BABYLON) {
  6893. /**
  6894. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6895. */
  6896. var Node = (function () {
  6897. /**
  6898. * @constructor
  6899. * @param {string} name - the name and id to be given to this node
  6900. * @param {BABYLON.Scene} the scene this node will be added to
  6901. */
  6902. function Node(name, scene) {
  6903. this.state = "";
  6904. this.animations = new Array();
  6905. this._ranges = {};
  6906. this._childrenFlag = -1;
  6907. this._isEnabled = true;
  6908. this._isReady = true;
  6909. this._currentRenderId = -1;
  6910. this._parentRenderId = -1;
  6911. this.name = name;
  6912. this.id = name;
  6913. this._scene = scene;
  6914. this._initCache();
  6915. }
  6916. Node.prototype.getScene = function () {
  6917. return this._scene;
  6918. };
  6919. Node.prototype.getEngine = function () {
  6920. return this._scene.getEngine();
  6921. };
  6922. // override it in derived class
  6923. Node.prototype.getWorldMatrix = function () {
  6924. return BABYLON.Matrix.Identity();
  6925. };
  6926. // override it in derived class if you add new variables to the cache
  6927. // and call the parent class method
  6928. Node.prototype._initCache = function () {
  6929. this._cache = {};
  6930. this._cache.parent = undefined;
  6931. };
  6932. Node.prototype.updateCache = function (force) {
  6933. if (!force && this.isSynchronized())
  6934. return;
  6935. this._cache.parent = this.parent;
  6936. this._updateCache();
  6937. };
  6938. // override it in derived class if you add new variables to the cache
  6939. // and call the parent class method if !ignoreParentClass
  6940. Node.prototype._updateCache = function (ignoreParentClass) {
  6941. };
  6942. // override it in derived class if you add new variables to the cache
  6943. Node.prototype._isSynchronized = function () {
  6944. return true;
  6945. };
  6946. Node.prototype._markSyncedWithParent = function () {
  6947. this._parentRenderId = this.parent._currentRenderId;
  6948. };
  6949. Node.prototype.isSynchronizedWithParent = function () {
  6950. if (!this.parent) {
  6951. return true;
  6952. }
  6953. if (this._parentRenderId !== this.parent._currentRenderId) {
  6954. return false;
  6955. }
  6956. return this.parent.isSynchronized();
  6957. };
  6958. Node.prototype.isSynchronized = function (updateCache) {
  6959. var check = this.hasNewParent();
  6960. check = check || !this.isSynchronizedWithParent();
  6961. check = check || !this._isSynchronized();
  6962. if (updateCache)
  6963. this.updateCache(true);
  6964. return !check;
  6965. };
  6966. Node.prototype.hasNewParent = function (update) {
  6967. if (this._cache.parent === this.parent)
  6968. return false;
  6969. if (update)
  6970. this._cache.parent = this.parent;
  6971. return true;
  6972. };
  6973. /**
  6974. * Is this node ready to be used/rendered
  6975. * @return {boolean} is it ready
  6976. */
  6977. Node.prototype.isReady = function () {
  6978. return this._isReady;
  6979. };
  6980. /**
  6981. * Is this node enabled.
  6982. * If the node has a parent and is enabled, the parent will be inspected as well.
  6983. * @return {boolean} whether this node (and its parent) is enabled.
  6984. * @see setEnabled
  6985. */
  6986. Node.prototype.isEnabled = function () {
  6987. if (!this._isEnabled) {
  6988. return false;
  6989. }
  6990. if (this.parent) {
  6991. return this.parent.isEnabled();
  6992. }
  6993. return true;
  6994. };
  6995. /**
  6996. * Set the enabled state of this node.
  6997. * @param {boolean} value - the new enabled state
  6998. * @see isEnabled
  6999. */
  7000. Node.prototype.setEnabled = function (value) {
  7001. this._isEnabled = value;
  7002. };
  7003. /**
  7004. * Is this node a descendant of the given node.
  7005. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7006. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7007. * @see parent
  7008. */
  7009. Node.prototype.isDescendantOf = function (ancestor) {
  7010. if (this.parent) {
  7011. if (this.parent === ancestor) {
  7012. return true;
  7013. }
  7014. return this.parent.isDescendantOf(ancestor);
  7015. }
  7016. return false;
  7017. };
  7018. Node.prototype._getDescendants = function (list, results) {
  7019. for (var index = 0; index < list.length; index++) {
  7020. var item = list[index];
  7021. if (item.isDescendantOf(this)) {
  7022. results.push(item);
  7023. }
  7024. }
  7025. };
  7026. /**
  7027. * Will return all nodes that have this node as parent.
  7028. * @return {BABYLON.Node[]} all children nodes of all types.
  7029. */
  7030. Node.prototype.getDescendants = function () {
  7031. var results = [];
  7032. this._getDescendants(this._scene.meshes, results);
  7033. this._getDescendants(this._scene.lights, results);
  7034. this._getDescendants(this._scene.cameras, results);
  7035. return results;
  7036. };
  7037. Node.prototype._setReady = function (state) {
  7038. if (state === this._isReady) {
  7039. return;
  7040. }
  7041. if (!state) {
  7042. this._isReady = false;
  7043. return;
  7044. }
  7045. this._isReady = true;
  7046. if (this.onReady) {
  7047. this.onReady(this);
  7048. }
  7049. };
  7050. Node.prototype.getAnimationByName = function (name) {
  7051. for (var i = 0; i < this.animations.length; i++) {
  7052. var animation = this.animations[i];
  7053. if (animation.name === name) {
  7054. return animation;
  7055. }
  7056. }
  7057. return null;
  7058. };
  7059. Node.prototype.createAnimationRange = function (name, from, to) {
  7060. // check name not already in use
  7061. if (!this._ranges[name]) {
  7062. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7063. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7064. if (this.animations[i]) {
  7065. this.animations[i].createRange(name, from, to);
  7066. }
  7067. }
  7068. }
  7069. };
  7070. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7071. if (deleteFrames === void 0) { deleteFrames = true; }
  7072. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7073. if (this.animations[i]) {
  7074. this.animations[i].deleteRange(name, deleteFrames);
  7075. }
  7076. }
  7077. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7078. };
  7079. Node.prototype.getAnimationRange = function (name) {
  7080. return this._ranges[name];
  7081. };
  7082. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7083. var range = this.getAnimationRange(name);
  7084. if (!range) {
  7085. return null;
  7086. }
  7087. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7088. };
  7089. Node.prototype.serializeAnimationRanges = function () {
  7090. var serializationRanges = [];
  7091. for (var name in this._ranges) {
  7092. var range = {};
  7093. range.name = name;
  7094. range.from = this._ranges[name].from;
  7095. range.to = this._ranges[name].to;
  7096. serializationRanges.push(range);
  7097. }
  7098. return serializationRanges;
  7099. };
  7100. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7101. if (parsedNode.ranges) {
  7102. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7103. var data = parsedNode.ranges[index];
  7104. node.createAnimationRange(data.name, data.from, data.to);
  7105. }
  7106. }
  7107. };
  7108. return Node;
  7109. })();
  7110. BABYLON.Node = Node;
  7111. })(BABYLON || (BABYLON = {}));
  7112. var BABYLON;
  7113. (function (BABYLON) {
  7114. var FilesInput = (function () {
  7115. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7116. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7117. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7118. this._engine = p_engine;
  7119. this._canvas = p_canvas;
  7120. this._currentScene = p_scene;
  7121. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7122. this._progressCallback = p_progressCallback;
  7123. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7124. this._textureLoadingCallback = p_textureLoadingCallback;
  7125. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7126. }
  7127. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7128. var _this = this;
  7129. if (p_elementToMonitor) {
  7130. this._elementToMonitor = p_elementToMonitor;
  7131. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7132. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7133. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7134. }
  7135. };
  7136. FilesInput.prototype.renderFunction = function () {
  7137. if (this._additionnalRenderLoopLogicCallback) {
  7138. this._additionnalRenderLoopLogicCallback();
  7139. }
  7140. if (this._currentScene) {
  7141. if (this._textureLoadingCallback) {
  7142. var remaining = this._currentScene.getWaitingItemsCount();
  7143. if (remaining > 0) {
  7144. this._textureLoadingCallback(remaining);
  7145. }
  7146. }
  7147. this._currentScene.render();
  7148. }
  7149. };
  7150. FilesInput.prototype.drag = function (e) {
  7151. e.stopPropagation();
  7152. e.preventDefault();
  7153. };
  7154. FilesInput.prototype.drop = function (eventDrop) {
  7155. eventDrop.stopPropagation();
  7156. eventDrop.preventDefault();
  7157. this.loadFiles(eventDrop);
  7158. };
  7159. FilesInput.prototype.loadFiles = function (event) {
  7160. if (this._startingProcessingFilesCallback)
  7161. this._startingProcessingFilesCallback();
  7162. // Handling data transfer via drag'n'drop
  7163. if (event && event.dataTransfer && event.dataTransfer.files) {
  7164. this._filesToLoad = event.dataTransfer.files;
  7165. }
  7166. // Handling files from input files
  7167. if (event && event.target && event.target.files) {
  7168. this._filesToLoad = event.target.files;
  7169. }
  7170. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7171. for (var i = 0; i < this._filesToLoad.length; i++) {
  7172. switch (this._filesToLoad[i].type) {
  7173. case "image/jpeg":
  7174. case "image/png":
  7175. case "image/bmp":
  7176. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7177. break;
  7178. case "image/targa":
  7179. case "image/vnd.ms-dds":
  7180. case "audio/wav":
  7181. case "audio/x-wav":
  7182. case "audio/mp3":
  7183. case "audio/mpeg":
  7184. case "audio/mpeg3":
  7185. case "audio/x-mpeg-3":
  7186. case "audio/ogg":
  7187. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7188. break;
  7189. default:
  7190. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7191. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7192. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7193. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7194. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7195. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7196. this._sceneFileToLoad = this._filesToLoad[i];
  7197. }
  7198. break;
  7199. }
  7200. }
  7201. this.reload();
  7202. }
  7203. };
  7204. FilesInput.prototype.reload = function () {
  7205. var _this = this;
  7206. var that = this;
  7207. // If a ".babylon" file has been provided
  7208. if (this._sceneFileToLoad) {
  7209. if (this._currentScene) {
  7210. if (BABYLON.Tools.errorsCount > 0) {
  7211. BABYLON.Tools.ClearLogCache();
  7212. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7213. }
  7214. this._engine.stopRenderLoop();
  7215. this._currentScene.dispose();
  7216. }
  7217. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7218. that._currentScene = newScene;
  7219. // Wait for textures and shaders to be ready
  7220. that._currentScene.executeWhenReady(function () {
  7221. // Attach camera to canvas inputs
  7222. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7223. that._currentScene.createDefaultCameraOrLight();
  7224. }
  7225. that._currentScene.activeCamera.attachControl(that._canvas);
  7226. if (that._sceneLoadedCallback) {
  7227. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7228. }
  7229. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7230. });
  7231. }, function (progress) {
  7232. if (_this._progressCallback) {
  7233. _this._progressCallback(progress);
  7234. }
  7235. });
  7236. }
  7237. else {
  7238. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7239. }
  7240. };
  7241. FilesInput.FilesTextures = new Array();
  7242. FilesInput.FilesToLoad = new Array();
  7243. return FilesInput;
  7244. })();
  7245. BABYLON.FilesInput = FilesInput;
  7246. })(BABYLON || (BABYLON = {}));
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var IntersectionInfo = (function () {
  7250. function IntersectionInfo(bu, bv, distance) {
  7251. this.bu = bu;
  7252. this.bv = bv;
  7253. this.distance = distance;
  7254. this.faceId = 0;
  7255. this.subMeshId = 0;
  7256. }
  7257. return IntersectionInfo;
  7258. })();
  7259. BABYLON.IntersectionInfo = IntersectionInfo;
  7260. var PickingInfo = (function () {
  7261. function PickingInfo() {
  7262. this.hit = false;
  7263. this.distance = 0;
  7264. this.pickedPoint = null;
  7265. this.pickedMesh = null;
  7266. this.bu = 0;
  7267. this.bv = 0;
  7268. this.faceId = -1;
  7269. this.subMeshId = 0;
  7270. this.pickedSprite = null;
  7271. }
  7272. // Methods
  7273. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7274. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7275. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7276. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7277. return null;
  7278. }
  7279. var indices = this.pickedMesh.getIndices();
  7280. var result;
  7281. if (useVerticesNormals) {
  7282. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7283. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7284. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7285. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7286. normal0 = normal0.scale(this.bu);
  7287. normal1 = normal1.scale(this.bv);
  7288. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7289. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7290. }
  7291. else {
  7292. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7293. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7294. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7295. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7296. var p1p2 = vertex1.subtract(vertex2);
  7297. var p3p2 = vertex3.subtract(vertex2);
  7298. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7299. }
  7300. if (useWorldCoordinates) {
  7301. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7302. }
  7303. return BABYLON.Vector3.Normalize(result);
  7304. };
  7305. PickingInfo.prototype.getTextureCoordinates = function () {
  7306. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7307. return null;
  7308. }
  7309. var indices = this.pickedMesh.getIndices();
  7310. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7311. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7312. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7313. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7314. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7315. uv1 = uv1.scale(this.bu);
  7316. uv2 = uv2.scale(this.bv);
  7317. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7318. };
  7319. return PickingInfo;
  7320. })();
  7321. BABYLON.PickingInfo = PickingInfo;
  7322. })(BABYLON || (BABYLON = {}));
  7323. var BABYLON;
  7324. (function (BABYLON) {
  7325. var BoundingSphere = (function () {
  7326. function BoundingSphere(minimum, maximum) {
  7327. this.minimum = minimum;
  7328. this.maximum = maximum;
  7329. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7330. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7331. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7332. this.radius = distance * 0.5;
  7333. this.centerWorld = BABYLON.Vector3.Zero();
  7334. this._update(BABYLON.Matrix.Identity());
  7335. }
  7336. // Methods
  7337. BoundingSphere.prototype._update = function (world) {
  7338. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7339. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7340. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7341. };
  7342. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7343. for (var i = 0; i < 6; i++) {
  7344. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7345. return false;
  7346. }
  7347. return true;
  7348. };
  7349. BoundingSphere.prototype.intersectsPoint = function (point) {
  7350. var x = this.centerWorld.x - point.x;
  7351. var y = this.centerWorld.y - point.y;
  7352. var z = this.centerWorld.z - point.z;
  7353. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7354. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7355. return false;
  7356. return true;
  7357. };
  7358. // Statics
  7359. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7360. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7361. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7362. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7363. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7364. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7365. return false;
  7366. return true;
  7367. };
  7368. return BoundingSphere;
  7369. })();
  7370. BABYLON.BoundingSphere = BoundingSphere;
  7371. })(BABYLON || (BABYLON = {}));
  7372. var BABYLON;
  7373. (function (BABYLON) {
  7374. var BoundingBox = (function () {
  7375. function BoundingBox(minimum, maximum) {
  7376. this.minimum = minimum;
  7377. this.maximum = maximum;
  7378. this.vectors = new Array();
  7379. this.vectorsWorld = new Array();
  7380. // Bounding vectors
  7381. this.vectors.push(this.minimum.clone());
  7382. this.vectors.push(this.maximum.clone());
  7383. this.vectors.push(this.minimum.clone());
  7384. this.vectors[2].x = this.maximum.x;
  7385. this.vectors.push(this.minimum.clone());
  7386. this.vectors[3].y = this.maximum.y;
  7387. this.vectors.push(this.minimum.clone());
  7388. this.vectors[4].z = this.maximum.z;
  7389. this.vectors.push(this.maximum.clone());
  7390. this.vectors[5].z = this.minimum.z;
  7391. this.vectors.push(this.maximum.clone());
  7392. this.vectors[6].x = this.minimum.x;
  7393. this.vectors.push(this.maximum.clone());
  7394. this.vectors[7].y = this.minimum.y;
  7395. // OBB
  7396. this.center = this.maximum.add(this.minimum).scale(0.5);
  7397. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7398. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7399. // World
  7400. for (var index = 0; index < this.vectors.length; index++) {
  7401. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7402. }
  7403. this.minimumWorld = BABYLON.Vector3.Zero();
  7404. this.maximumWorld = BABYLON.Vector3.Zero();
  7405. this._update(BABYLON.Matrix.Identity());
  7406. }
  7407. // Methods
  7408. BoundingBox.prototype.getWorldMatrix = function () {
  7409. return this._worldMatrix;
  7410. };
  7411. BoundingBox.prototype._update = function (world) {
  7412. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7413. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7414. for (var index = 0; index < this.vectors.length; index++) {
  7415. var v = this.vectorsWorld[index];
  7416. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7417. if (v.x < this.minimumWorld.x)
  7418. this.minimumWorld.x = v.x;
  7419. if (v.y < this.minimumWorld.y)
  7420. this.minimumWorld.y = v.y;
  7421. if (v.z < this.minimumWorld.z)
  7422. this.minimumWorld.z = v.z;
  7423. if (v.x > this.maximumWorld.x)
  7424. this.maximumWorld.x = v.x;
  7425. if (v.y > this.maximumWorld.y)
  7426. this.maximumWorld.y = v.y;
  7427. if (v.z > this.maximumWorld.z)
  7428. this.maximumWorld.z = v.z;
  7429. }
  7430. // OBB
  7431. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7432. this.center.scaleInPlace(0.5);
  7433. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7434. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7435. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7436. this._worldMatrix = world;
  7437. };
  7438. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7439. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7440. };
  7441. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7442. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7443. };
  7444. BoundingBox.prototype.intersectsPoint = function (point) {
  7445. var delta = -BABYLON.Engine.Epsilon;
  7446. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7447. return false;
  7448. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7449. return false;
  7450. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7451. return false;
  7452. return true;
  7453. };
  7454. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7455. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7456. };
  7457. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7458. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7459. return false;
  7460. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7461. return false;
  7462. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7463. return false;
  7464. return true;
  7465. };
  7466. // Statics
  7467. BoundingBox.Intersects = function (box0, box1) {
  7468. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7469. return false;
  7470. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7471. return false;
  7472. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7473. return false;
  7474. return true;
  7475. };
  7476. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7477. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7478. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7479. return (num <= (sphereRadius * sphereRadius));
  7480. };
  7481. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7482. for (var p = 0; p < 6; p++) {
  7483. for (var i = 0; i < 8; i++) {
  7484. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7485. return false;
  7486. }
  7487. }
  7488. }
  7489. return true;
  7490. };
  7491. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7492. for (var p = 0; p < 6; p++) {
  7493. var inCount = 8;
  7494. for (var i = 0; i < 8; i++) {
  7495. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7496. --inCount;
  7497. }
  7498. else {
  7499. break;
  7500. }
  7501. }
  7502. if (inCount === 0)
  7503. return false;
  7504. }
  7505. return true;
  7506. };
  7507. return BoundingBox;
  7508. })();
  7509. BABYLON.BoundingBox = BoundingBox;
  7510. })(BABYLON || (BABYLON = {}));
  7511. var BABYLON;
  7512. (function (BABYLON) {
  7513. var computeBoxExtents = function (axis, box) {
  7514. var p = BABYLON.Vector3.Dot(box.center, axis);
  7515. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7516. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7517. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7518. var r = r0 + r1 + r2;
  7519. return {
  7520. min: p - r,
  7521. max: p + r
  7522. };
  7523. };
  7524. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7525. var axisOverlap = function (axis, box0, box1) {
  7526. var result0 = computeBoxExtents(axis, box0);
  7527. var result1 = computeBoxExtents(axis, box1);
  7528. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7529. };
  7530. var BoundingInfo = (function () {
  7531. function BoundingInfo(minimum, maximum) {
  7532. this.minimum = minimum;
  7533. this.maximum = maximum;
  7534. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7535. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7536. }
  7537. // Methods
  7538. BoundingInfo.prototype._update = function (world) {
  7539. this.boundingBox._update(world);
  7540. this.boundingSphere._update(world);
  7541. };
  7542. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7543. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7544. return false;
  7545. return this.boundingBox.isInFrustum(frustumPlanes);
  7546. };
  7547. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7548. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7549. };
  7550. BoundingInfo.prototype._checkCollision = function (collider) {
  7551. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7552. };
  7553. BoundingInfo.prototype.intersectsPoint = function (point) {
  7554. if (!this.boundingSphere.centerWorld) {
  7555. return false;
  7556. }
  7557. if (!this.boundingSphere.intersectsPoint(point)) {
  7558. return false;
  7559. }
  7560. if (!this.boundingBox.intersectsPoint(point)) {
  7561. return false;
  7562. }
  7563. return true;
  7564. };
  7565. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7566. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7567. return false;
  7568. }
  7569. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7570. return false;
  7571. }
  7572. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7573. return false;
  7574. }
  7575. if (!precise) {
  7576. return true;
  7577. }
  7578. var box0 = this.boundingBox;
  7579. var box1 = boundingInfo.boundingBox;
  7580. if (!axisOverlap(box0.directions[0], box0, box1))
  7581. return false;
  7582. if (!axisOverlap(box0.directions[1], box0, box1))
  7583. return false;
  7584. if (!axisOverlap(box0.directions[2], box0, box1))
  7585. return false;
  7586. if (!axisOverlap(box1.directions[0], box0, box1))
  7587. return false;
  7588. if (!axisOverlap(box1.directions[1], box0, box1))
  7589. return false;
  7590. if (!axisOverlap(box1.directions[2], box0, box1))
  7591. return false;
  7592. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7593. return false;
  7594. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7595. return false;
  7596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7597. return false;
  7598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7599. return false;
  7600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7601. return false;
  7602. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7603. return false;
  7604. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7605. return false;
  7606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7607. return false;
  7608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7609. return false;
  7610. return true;
  7611. };
  7612. return BoundingInfo;
  7613. })();
  7614. BABYLON.BoundingInfo = BoundingInfo;
  7615. })(BABYLON || (BABYLON = {}));
  7616. var BABYLON;
  7617. (function (BABYLON) {
  7618. var AbstractMesh = (function (_super) {
  7619. __extends(AbstractMesh, _super);
  7620. // Constructor
  7621. function AbstractMesh(name, scene) {
  7622. var _this = this;
  7623. _super.call(this, name, scene);
  7624. // Properties
  7625. this.definedFacingForward = true; // orientation for POV movement & rotation
  7626. this.position = new BABYLON.Vector3(0, 0, 0);
  7627. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7628. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7629. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7630. this.visibility = 1.0;
  7631. this.alphaIndex = Number.MAX_VALUE;
  7632. this.infiniteDistance = false;
  7633. this.isVisible = true;
  7634. this.isPickable = true;
  7635. this.showBoundingBox = false;
  7636. this.showSubMeshesBoundingBox = false;
  7637. this.onDispose = null;
  7638. this.isBlocker = false;
  7639. this.renderingGroupId = 0;
  7640. this.receiveShadows = false;
  7641. this.renderOutline = false;
  7642. this.outlineColor = BABYLON.Color3.Red();
  7643. this.outlineWidth = 0.02;
  7644. this.renderOverlay = false;
  7645. this.overlayColor = BABYLON.Color3.Red();
  7646. this.overlayAlpha = 0.5;
  7647. this.hasVertexAlpha = false;
  7648. this.useVertexColors = true;
  7649. this.applyFog = true;
  7650. this.computeBonesUsingShaders = true;
  7651. this.scalingDeterminant = 1;
  7652. this.numBoneInfluencers = 4;
  7653. this.useOctreeForRenderingSelection = true;
  7654. this.useOctreeForPicking = true;
  7655. this.useOctreeForCollisions = true;
  7656. this.layerMask = 0x0FFFFFFF;
  7657. this.alwaysSelectAsActiveMesh = false;
  7658. // Physics
  7659. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7660. // Collisions
  7661. this._checkCollisions = false;
  7662. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7663. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7664. this._collider = new BABYLON.Collider();
  7665. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7666. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7667. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7668. // Edges
  7669. this.edgesWidth = 1;
  7670. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7671. // Cache
  7672. this._localWorld = BABYLON.Matrix.Zero();
  7673. this._worldMatrix = BABYLON.Matrix.Zero();
  7674. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7675. this._absolutePosition = BABYLON.Vector3.Zero();
  7676. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7677. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7678. this._isDirty = false;
  7679. this._pivotMatrix = BABYLON.Matrix.Identity();
  7680. this._isDisposed = false;
  7681. this._renderId = 0;
  7682. this._intersectionsInProgress = new Array();
  7683. this._onAfterWorldMatrixUpdate = new Array();
  7684. this._isWorldMatrixFrozen = false;
  7685. this._unIndexed = false;
  7686. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7687. if (collidedMesh === void 0) { collidedMesh = null; }
  7688. //TODO move this to the collision coordinator!
  7689. if (_this.getScene().workerCollisions)
  7690. newPosition.multiplyInPlace(_this._collider.radius);
  7691. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7692. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7693. _this.position.addInPlace(_this._diffPositionForCollisions);
  7694. }
  7695. if (_this.onCollide && collidedMesh) {
  7696. _this.onCollide(collidedMesh);
  7697. }
  7698. if (_this.onCollisionPositionChange) {
  7699. _this.onCollisionPositionChange(_this.position);
  7700. }
  7701. };
  7702. scene.addMesh(this);
  7703. }
  7704. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7705. get: function () {
  7706. return AbstractMesh._BILLBOARDMODE_NONE;
  7707. },
  7708. enumerable: true,
  7709. configurable: true
  7710. });
  7711. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7712. get: function () {
  7713. return AbstractMesh._BILLBOARDMODE_X;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7719. get: function () {
  7720. return AbstractMesh._BILLBOARDMODE_Y;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7726. get: function () {
  7727. return AbstractMesh._BILLBOARDMODE_Z;
  7728. },
  7729. enumerable: true,
  7730. configurable: true
  7731. });
  7732. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7733. get: function () {
  7734. return AbstractMesh._BILLBOARDMODE_ALL;
  7735. },
  7736. enumerable: true,
  7737. configurable: true
  7738. });
  7739. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  7740. get: function () {
  7741. return this._skeleton;
  7742. },
  7743. set: function (value) {
  7744. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  7745. this._skeleton._unregisterMeshWithPoseMatrix(this);
  7746. }
  7747. if (value && value.needInitialSkinMatrix) {
  7748. value._registerMeshWithPoseMatrix(this);
  7749. }
  7750. this._skeleton = value;
  7751. if (!this._skeleton) {
  7752. this._bonesTransformMatrices = null;
  7753. }
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. // Methods
  7759. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  7760. this._poseMatrix.copyFrom(matrix);
  7761. };
  7762. AbstractMesh.prototype.getPoseMatrix = function () {
  7763. return this._poseMatrix;
  7764. };
  7765. AbstractMesh.prototype.disableEdgesRendering = function () {
  7766. if (this._edgesRenderer !== undefined) {
  7767. this._edgesRenderer.dispose();
  7768. this._edgesRenderer = undefined;
  7769. }
  7770. };
  7771. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7772. if (epsilon === void 0) { epsilon = 0.95; }
  7773. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7774. this.disableEdgesRendering();
  7775. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7776. };
  7777. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7778. get: function () {
  7779. return false;
  7780. },
  7781. enumerable: true,
  7782. configurable: true
  7783. });
  7784. AbstractMesh.prototype.getLOD = function (camera) {
  7785. return this;
  7786. };
  7787. AbstractMesh.prototype.getTotalVertices = function () {
  7788. return 0;
  7789. };
  7790. AbstractMesh.prototype.getIndices = function () {
  7791. return null;
  7792. };
  7793. AbstractMesh.prototype.getVerticesData = function (kind) {
  7794. return null;
  7795. };
  7796. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7797. return false;
  7798. };
  7799. AbstractMesh.prototype.getBoundingInfo = function () {
  7800. if (this._masterMesh) {
  7801. return this._masterMesh.getBoundingInfo();
  7802. }
  7803. if (!this._boundingInfo) {
  7804. this._updateBoundingInfo();
  7805. }
  7806. return this._boundingInfo;
  7807. };
  7808. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7809. get: function () {
  7810. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7811. },
  7812. enumerable: true,
  7813. configurable: true
  7814. });
  7815. AbstractMesh.prototype._preActivate = function () {
  7816. };
  7817. AbstractMesh.prototype._activate = function (renderId) {
  7818. this._renderId = renderId;
  7819. };
  7820. AbstractMesh.prototype.getWorldMatrix = function () {
  7821. if (this._masterMesh) {
  7822. return this._masterMesh.getWorldMatrix();
  7823. }
  7824. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7825. this.computeWorldMatrix();
  7826. }
  7827. return this._worldMatrix;
  7828. };
  7829. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7830. get: function () {
  7831. return this._worldMatrix;
  7832. },
  7833. enumerable: true,
  7834. configurable: true
  7835. });
  7836. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7837. get: function () {
  7838. return this._absolutePosition;
  7839. },
  7840. enumerable: true,
  7841. configurable: true
  7842. });
  7843. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7844. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7845. this.computeWorldMatrix(true);
  7846. this._isWorldMatrixFrozen = true;
  7847. };
  7848. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7849. this._isWorldMatrixFrozen = false;
  7850. this.computeWorldMatrix(true);
  7851. };
  7852. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7853. get: function () {
  7854. return this._isWorldMatrixFrozen;
  7855. },
  7856. enumerable: true,
  7857. configurable: true
  7858. });
  7859. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7860. axis.normalize();
  7861. if (!this.rotationQuaternion) {
  7862. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7863. this.rotation = BABYLON.Vector3.Zero();
  7864. }
  7865. var rotationQuaternion;
  7866. if (!space || space === BABYLON.Space.LOCAL) {
  7867. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7868. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7869. }
  7870. else {
  7871. if (this.parent) {
  7872. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7873. invertParentWorldMatrix.invert();
  7874. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7875. }
  7876. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7877. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7878. }
  7879. };
  7880. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7881. var displacementVector = axis.scale(distance);
  7882. if (!space || space === BABYLON.Space.LOCAL) {
  7883. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7884. this.setPositionWithLocalVector(tempV3);
  7885. }
  7886. else {
  7887. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7888. }
  7889. };
  7890. AbstractMesh.prototype.getAbsolutePosition = function () {
  7891. this.computeWorldMatrix();
  7892. return this._absolutePosition;
  7893. };
  7894. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7895. if (!absolutePosition) {
  7896. return;
  7897. }
  7898. var absolutePositionX;
  7899. var absolutePositionY;
  7900. var absolutePositionZ;
  7901. if (absolutePosition.x === undefined) {
  7902. if (arguments.length < 3) {
  7903. return;
  7904. }
  7905. absolutePositionX = arguments[0];
  7906. absolutePositionY = arguments[1];
  7907. absolutePositionZ = arguments[2];
  7908. }
  7909. else {
  7910. absolutePositionX = absolutePosition.x;
  7911. absolutePositionY = absolutePosition.y;
  7912. absolutePositionZ = absolutePosition.z;
  7913. }
  7914. if (this.parent) {
  7915. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7916. invertParentWorldMatrix.invert();
  7917. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7918. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7919. }
  7920. else {
  7921. this.position.x = absolutePositionX;
  7922. this.position.y = absolutePositionY;
  7923. this.position.z = absolutePositionZ;
  7924. }
  7925. };
  7926. // ================================== Point of View Movement =================================
  7927. /**
  7928. * Perform relative position change from the point of view of behind the front of the mesh.
  7929. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7930. * Supports definition of mesh facing forward or backward.
  7931. * @param {number} amountRight
  7932. * @param {number} amountUp
  7933. * @param {number} amountForward
  7934. */
  7935. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7936. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7937. };
  7938. /**
  7939. * Calculate relative position change from the point of view of behind the front of the mesh.
  7940. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7941. * Supports definition of mesh facing forward or backward.
  7942. * @param {number} amountRight
  7943. * @param {number} amountUp
  7944. * @param {number} amountForward
  7945. */
  7946. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7947. var rotMatrix = new BABYLON.Matrix();
  7948. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7949. rotQuaternion.toRotationMatrix(rotMatrix);
  7950. var translationDelta = BABYLON.Vector3.Zero();
  7951. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7952. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7953. return translationDelta;
  7954. };
  7955. // ================================== Point of View Rotation =================================
  7956. /**
  7957. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7958. * Supports definition of mesh facing forward or backward.
  7959. * @param {number} flipBack
  7960. * @param {number} twirlClockwise
  7961. * @param {number} tiltRight
  7962. */
  7963. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7964. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7965. };
  7966. /**
  7967. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7968. * Supports definition of mesh facing forward or backward.
  7969. * @param {number} flipBack
  7970. * @param {number} twirlClockwise
  7971. * @param {number} tiltRight
  7972. */
  7973. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7974. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7975. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7976. };
  7977. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7978. this._pivotMatrix = matrix;
  7979. this._cache.pivotMatrixUpdated = true;
  7980. };
  7981. AbstractMesh.prototype.getPivotMatrix = function () {
  7982. return this._pivotMatrix;
  7983. };
  7984. AbstractMesh.prototype._isSynchronized = function () {
  7985. if (this._isDirty) {
  7986. return false;
  7987. }
  7988. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7989. return false;
  7990. if (this._cache.pivotMatrixUpdated) {
  7991. return false;
  7992. }
  7993. if (this.infiniteDistance) {
  7994. return false;
  7995. }
  7996. if (!this._cache.position.equals(this.position))
  7997. return false;
  7998. if (this.rotationQuaternion) {
  7999. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8000. return false;
  8001. }
  8002. else {
  8003. if (!this._cache.rotation.equals(this.rotation))
  8004. return false;
  8005. }
  8006. if (!this._cache.scaling.equals(this.scaling))
  8007. return false;
  8008. return true;
  8009. };
  8010. AbstractMesh.prototype._initCache = function () {
  8011. _super.prototype._initCache.call(this);
  8012. this._cache.localMatrixUpdated = false;
  8013. this._cache.position = BABYLON.Vector3.Zero();
  8014. this._cache.scaling = BABYLON.Vector3.Zero();
  8015. this._cache.rotation = BABYLON.Vector3.Zero();
  8016. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8017. this._cache.billboardMode = -1;
  8018. };
  8019. AbstractMesh.prototype.markAsDirty = function (property) {
  8020. if (property === "rotation") {
  8021. this.rotationQuaternion = null;
  8022. }
  8023. this._currentRenderId = Number.MAX_VALUE;
  8024. this._isDirty = true;
  8025. };
  8026. AbstractMesh.prototype._updateBoundingInfo = function () {
  8027. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8028. this._boundingInfo._update(this.worldMatrixFromCache);
  8029. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8030. };
  8031. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8032. if (!this.subMeshes) {
  8033. return;
  8034. }
  8035. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8036. var subMesh = this.subMeshes[subIndex];
  8037. if (!subMesh.IsGlobal) {
  8038. subMesh.updateBoundingInfo(matrix);
  8039. }
  8040. }
  8041. };
  8042. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8043. if (this._isWorldMatrixFrozen) {
  8044. return this._worldMatrix;
  8045. }
  8046. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8047. this._currentRenderId = this.getScene().getRenderId();
  8048. return this._worldMatrix;
  8049. }
  8050. this._cache.position.copyFrom(this.position);
  8051. this._cache.scaling.copyFrom(this.scaling);
  8052. this._cache.pivotMatrixUpdated = false;
  8053. this._cache.billboardMode = this.billboardMode;
  8054. this._currentRenderId = this.getScene().getRenderId();
  8055. this._isDirty = false;
  8056. // Scaling
  8057. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8058. // Rotation
  8059. if (this.rotationQuaternion) {
  8060. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8061. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8062. }
  8063. else {
  8064. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8065. this._cache.rotation.copyFrom(this.rotation);
  8066. }
  8067. // Translation
  8068. if (this.infiniteDistance && !this.parent) {
  8069. var camera = this.getScene().activeCamera;
  8070. if (camera) {
  8071. var cameraWorldMatrix = camera.getWorldMatrix();
  8072. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8073. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8074. }
  8075. }
  8076. else {
  8077. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8078. }
  8079. // Composing transformations
  8080. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8081. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8082. // Billboarding
  8083. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8084. var localPosition = this.position.clone();
  8085. var zero = this.getScene().activeCamera.globalPosition.clone();
  8086. if (this.parent && this.parent.position) {
  8087. localPosition.addInPlace(this.parent.position);
  8088. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8089. }
  8090. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8091. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8092. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8093. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8094. zero.y = localPosition.y + 0.001;
  8095. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8096. zero.z = localPosition.z + 0.001;
  8097. }
  8098. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8099. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8100. BABYLON.Tmp.Matrix[3].invert();
  8101. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8102. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8103. }
  8104. // Local world
  8105. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8106. // Parent
  8107. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8108. this._markSyncedWithParent();
  8109. if (this._meshToBoneReferal) {
  8110. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8111. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8112. }
  8113. else {
  8114. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8115. }
  8116. }
  8117. else {
  8118. this._worldMatrix.copyFrom(this._localWorld);
  8119. }
  8120. // Bounding info
  8121. this._updateBoundingInfo();
  8122. // Absolute position
  8123. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8124. // Callbacks
  8125. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8126. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8127. }
  8128. if (!this._poseMatrix) {
  8129. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8130. }
  8131. return this._worldMatrix;
  8132. };
  8133. /**
  8134. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8135. * @param func: callback function to add
  8136. */
  8137. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8138. this._onAfterWorldMatrixUpdate.push(func);
  8139. };
  8140. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8141. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8142. if (index > -1) {
  8143. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8144. }
  8145. };
  8146. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8147. this.computeWorldMatrix();
  8148. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8149. };
  8150. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8151. this.computeWorldMatrix();
  8152. var invLocalWorldMatrix = this._localWorld.clone();
  8153. invLocalWorldMatrix.invert();
  8154. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8155. };
  8156. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8157. this.computeWorldMatrix(true);
  8158. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8159. };
  8160. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8161. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8162. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8163. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8164. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8165. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8166. /// <returns>Mesh oriented towards targetMesh</returns>
  8167. yawCor = yawCor || 0; // default to zero if undefined
  8168. pitchCor = pitchCor || 0;
  8169. rollCor = rollCor || 0;
  8170. var dv = targetPoint.subtract(this.position);
  8171. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8172. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8173. var pitch = Math.atan2(dv.y, len);
  8174. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8175. };
  8176. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8177. this._meshToBoneReferal = affectedMesh;
  8178. this.parent = bone;
  8179. if (bone.getWorldMatrix().determinant() < 0) {
  8180. this.scalingDeterminant *= -1;
  8181. }
  8182. };
  8183. AbstractMesh.prototype.detachFromBone = function () {
  8184. if (this.parent.getWorldMatrix().determinant() < 0) {
  8185. this.scalingDeterminant *= -1;
  8186. }
  8187. this._meshToBoneReferal = null;
  8188. this.parent = null;
  8189. };
  8190. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8191. return this._boundingInfo.isInFrustum(frustumPlanes);
  8192. };
  8193. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8194. if (!camera) {
  8195. camera = this.getScene().activeCamera;
  8196. }
  8197. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8198. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8199. return false;
  8200. }
  8201. return true;
  8202. };
  8203. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8204. if (!this._boundingInfo || !mesh._boundingInfo) {
  8205. return false;
  8206. }
  8207. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8208. };
  8209. AbstractMesh.prototype.intersectsPoint = function (point) {
  8210. if (!this._boundingInfo) {
  8211. return false;
  8212. }
  8213. return this._boundingInfo.intersectsPoint(point);
  8214. };
  8215. // Physics
  8216. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8217. var physicsEngine = this.getScene().getPhysicsEngine();
  8218. if (!physicsEngine) {
  8219. return null;
  8220. }
  8221. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8222. if (impostor.impostor) {
  8223. // Old API
  8224. options = impostor;
  8225. impostor = impostor.impostor;
  8226. }
  8227. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8228. physicsEngine._unregisterMesh(this);
  8229. return null;
  8230. }
  8231. if (!options) {
  8232. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8233. }
  8234. else {
  8235. if (!options.mass && options.mass !== 0)
  8236. options.mass = 0;
  8237. if (!options.friction && options.friction !== 0)
  8238. options.friction = 0.2;
  8239. if (!options.restitution && options.restitution !== 0)
  8240. options.restitution = 0.2;
  8241. }
  8242. this._physicImpostor = impostor;
  8243. this._physicsMass = options.mass;
  8244. this._physicsFriction = options.friction;
  8245. this._physicRestitution = options.restitution;
  8246. return physicsEngine._registerMesh(this, impostor, options);
  8247. };
  8248. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8249. if (!this._physicImpostor) {
  8250. return BABYLON.PhysicsEngine.NoImpostor;
  8251. }
  8252. return this._physicImpostor;
  8253. };
  8254. AbstractMesh.prototype.getPhysicsMass = function () {
  8255. if (!this._physicsMass) {
  8256. return 0;
  8257. }
  8258. return this._physicsMass;
  8259. };
  8260. AbstractMesh.prototype.getPhysicsFriction = function () {
  8261. if (!this._physicsFriction) {
  8262. return 0;
  8263. }
  8264. return this._physicsFriction;
  8265. };
  8266. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8267. if (!this._physicRestitution) {
  8268. return 0;
  8269. }
  8270. return this._physicRestitution;
  8271. };
  8272. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8273. if (!camera) {
  8274. camera = this.getScene().activeCamera;
  8275. }
  8276. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8277. };
  8278. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8279. if (!camera) {
  8280. camera = this.getScene().activeCamera;
  8281. }
  8282. return this.absolutePosition.subtract(camera.position).length();
  8283. };
  8284. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8285. if (!this._physicImpostor) {
  8286. return;
  8287. }
  8288. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8289. };
  8290. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8291. if (!this._physicImpostor) {
  8292. return;
  8293. }
  8294. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8295. };
  8296. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8297. if (!this._physicImpostor) {
  8298. return;
  8299. }
  8300. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8301. };
  8302. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8303. // Collisions
  8304. get: function () {
  8305. return this._checkCollisions;
  8306. },
  8307. set: function (collisionEnabled) {
  8308. this._checkCollisions = collisionEnabled;
  8309. if (this.getScene().workerCollisions) {
  8310. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8311. }
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8317. var globalPosition = this.getAbsolutePosition();
  8318. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8319. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8320. this._collider.radius = this.ellipsoid;
  8321. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8322. };
  8323. // Submeshes octree
  8324. /**
  8325. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8326. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8327. */
  8328. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8329. if (maxCapacity === void 0) { maxCapacity = 64; }
  8330. if (maxDepth === void 0) { maxDepth = 2; }
  8331. if (!this._submeshesOctree) {
  8332. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8333. }
  8334. this.computeWorldMatrix(true);
  8335. // Update octree
  8336. var bbox = this.getBoundingInfo().boundingBox;
  8337. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8338. return this._submeshesOctree;
  8339. };
  8340. // Collisions
  8341. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8342. this._generatePointsArray();
  8343. // Transformation
  8344. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8345. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8346. subMesh._lastColliderWorldVertices = [];
  8347. subMesh._trianglePlanes = [];
  8348. var start = subMesh.verticesStart;
  8349. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8350. for (var i = start; i < end; i++) {
  8351. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8352. }
  8353. }
  8354. // Collide
  8355. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8356. if (collider.collisionFound) {
  8357. collider.collidedMesh = this;
  8358. }
  8359. };
  8360. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8361. var subMeshes;
  8362. var len;
  8363. // Octrees
  8364. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8365. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8366. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8367. len = intersections.length;
  8368. subMeshes = intersections.data;
  8369. }
  8370. else {
  8371. subMeshes = this.subMeshes;
  8372. len = subMeshes.length;
  8373. }
  8374. for (var index = 0; index < len; index++) {
  8375. var subMesh = subMeshes[index];
  8376. // Bounding test
  8377. if (len > 1 && !subMesh._checkCollision(collider))
  8378. continue;
  8379. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8380. }
  8381. };
  8382. AbstractMesh.prototype._checkCollision = function (collider) {
  8383. // Bounding box test
  8384. if (!this._boundingInfo._checkCollision(collider))
  8385. return;
  8386. // Transformation matrix
  8387. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8388. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8389. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8390. };
  8391. // Picking
  8392. AbstractMesh.prototype._generatePointsArray = function () {
  8393. return false;
  8394. };
  8395. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8396. var pickingInfo = new BABYLON.PickingInfo();
  8397. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8398. return pickingInfo;
  8399. }
  8400. if (!this._generatePointsArray()) {
  8401. return pickingInfo;
  8402. }
  8403. var intersectInfo = null;
  8404. // Octrees
  8405. var subMeshes;
  8406. var len;
  8407. if (this._submeshesOctree && this.useOctreeForPicking) {
  8408. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8409. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8410. len = intersections.length;
  8411. subMeshes = intersections.data;
  8412. }
  8413. else {
  8414. subMeshes = this.subMeshes;
  8415. len = subMeshes.length;
  8416. }
  8417. for (var index = 0; index < len; index++) {
  8418. var subMesh = subMeshes[index];
  8419. // Bounding test
  8420. if (len > 1 && !subMesh.canIntersects(ray))
  8421. continue;
  8422. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8423. if (currentIntersectInfo) {
  8424. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8425. intersectInfo = currentIntersectInfo;
  8426. intersectInfo.subMeshId = index;
  8427. if (fastCheck) {
  8428. break;
  8429. }
  8430. }
  8431. }
  8432. }
  8433. if (intersectInfo) {
  8434. // Get picked point
  8435. var world = this.getWorldMatrix();
  8436. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8437. var direction = ray.direction.clone();
  8438. direction = direction.scale(intersectInfo.distance);
  8439. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8440. var pickedPoint = worldOrigin.add(worldDirection);
  8441. // Return result
  8442. pickingInfo.hit = true;
  8443. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8444. pickingInfo.pickedPoint = pickedPoint;
  8445. pickingInfo.pickedMesh = this;
  8446. pickingInfo.bu = intersectInfo.bu;
  8447. pickingInfo.bv = intersectInfo.bv;
  8448. pickingInfo.faceId = intersectInfo.faceId;
  8449. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8450. return pickingInfo;
  8451. }
  8452. return pickingInfo;
  8453. };
  8454. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8455. return null;
  8456. };
  8457. AbstractMesh.prototype.releaseSubMeshes = function () {
  8458. if (this.subMeshes) {
  8459. while (this.subMeshes.length) {
  8460. this.subMeshes[0].dispose();
  8461. }
  8462. }
  8463. else {
  8464. this.subMeshes = new Array();
  8465. }
  8466. };
  8467. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8468. var index;
  8469. // Skeleton
  8470. this.skeleton = null;
  8471. // Animations
  8472. this.getScene().stopAnimation(this);
  8473. // Physics
  8474. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8475. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8476. }
  8477. // Intersections in progress
  8478. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8479. var other = this._intersectionsInProgress[index];
  8480. var pos = other._intersectionsInProgress.indexOf(this);
  8481. other._intersectionsInProgress.splice(pos, 1);
  8482. }
  8483. this._intersectionsInProgress = [];
  8484. // Edges
  8485. if (this._edgesRenderer) {
  8486. this._edgesRenderer.dispose();
  8487. this._edgesRenderer = null;
  8488. }
  8489. // SubMeshes
  8490. this.releaseSubMeshes();
  8491. // Remove from scene
  8492. this.getScene().removeMesh(this);
  8493. if (!doNotRecurse) {
  8494. // Particles
  8495. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8496. if (this.getScene().particleSystems[index].emitter === this) {
  8497. this.getScene().particleSystems[index].dispose();
  8498. index--;
  8499. }
  8500. }
  8501. // Children
  8502. var objects = this.getScene().meshes.slice(0);
  8503. for (index = 0; index < objects.length; index++) {
  8504. if (objects[index].parent === this) {
  8505. objects[index].dispose();
  8506. }
  8507. }
  8508. }
  8509. else {
  8510. for (index = 0; index < this.getScene().meshes.length; index++) {
  8511. var obj = this.getScene().meshes[index];
  8512. if (obj.parent === this) {
  8513. obj.parent = null;
  8514. obj.computeWorldMatrix(true);
  8515. }
  8516. }
  8517. }
  8518. this._onAfterWorldMatrixUpdate = [];
  8519. this._isDisposed = true;
  8520. // Callback
  8521. if (this.onDispose) {
  8522. this.onDispose();
  8523. }
  8524. };
  8525. // Statics
  8526. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8527. AbstractMesh._BILLBOARDMODE_X = 1;
  8528. AbstractMesh._BILLBOARDMODE_Y = 2;
  8529. AbstractMesh._BILLBOARDMODE_Z = 4;
  8530. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8531. return AbstractMesh;
  8532. })(BABYLON.Node);
  8533. BABYLON.AbstractMesh = AbstractMesh;
  8534. })(BABYLON || (BABYLON = {}));
  8535. var BABYLON;
  8536. (function (BABYLON) {
  8537. var Light = (function (_super) {
  8538. __extends(Light, _super);
  8539. function Light(name, scene) {
  8540. _super.call(this, name, scene);
  8541. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8542. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8543. this.intensity = 1.0;
  8544. this.range = Number.MAX_VALUE;
  8545. this.includeOnlyWithLayerMask = 0;
  8546. this.includedOnlyMeshes = new Array();
  8547. this.excludedMeshes = new Array();
  8548. this.excludeWithLayerMask = 0;
  8549. this._excludedMeshesIds = new Array();
  8550. this._includedOnlyMeshesIds = new Array();
  8551. scene.addLight(this);
  8552. }
  8553. Light.prototype.getShadowGenerator = function () {
  8554. return this._shadowGenerator;
  8555. };
  8556. Light.prototype.getAbsolutePosition = function () {
  8557. return BABYLON.Vector3.Zero();
  8558. };
  8559. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8560. };
  8561. Light.prototype._getWorldMatrix = function () {
  8562. return BABYLON.Matrix.Identity();
  8563. };
  8564. Light.prototype.canAffectMesh = function (mesh) {
  8565. if (!mesh) {
  8566. return true;
  8567. }
  8568. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8569. return false;
  8570. }
  8571. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8572. return false;
  8573. }
  8574. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8575. return false;
  8576. }
  8577. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8578. return false;
  8579. }
  8580. return true;
  8581. };
  8582. Light.prototype.getWorldMatrix = function () {
  8583. this._currentRenderId = this.getScene().getRenderId();
  8584. var worldMatrix = this._getWorldMatrix();
  8585. if (this.parent && this.parent.getWorldMatrix) {
  8586. if (!this._parentedWorldMatrix) {
  8587. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8588. }
  8589. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8590. this._markSyncedWithParent();
  8591. return this._parentedWorldMatrix;
  8592. }
  8593. return worldMatrix;
  8594. };
  8595. Light.prototype.dispose = function () {
  8596. if (this._shadowGenerator) {
  8597. this._shadowGenerator.dispose();
  8598. this._shadowGenerator = null;
  8599. }
  8600. // Animations
  8601. this.getScene().stopAnimation(this);
  8602. // Remove from scene
  8603. this.getScene().removeLight(this);
  8604. };
  8605. Light.prototype.serialize = function () {
  8606. var serializationObject = {};
  8607. serializationObject.name = this.name;
  8608. serializationObject.id = this.id;
  8609. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8610. if (this.intensity) {
  8611. serializationObject.intensity = this.intensity;
  8612. }
  8613. serializationObject.range = this.range;
  8614. serializationObject.diffuse = this.diffuse.asArray();
  8615. serializationObject.specular = this.specular.asArray();
  8616. return serializationObject;
  8617. };
  8618. Light.Parse = function (parsedLight, scene) {
  8619. var light;
  8620. switch (parsedLight.type) {
  8621. case 0:
  8622. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8623. break;
  8624. case 1:
  8625. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8626. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8627. break;
  8628. case 2:
  8629. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8630. break;
  8631. case 3:
  8632. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8633. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8634. break;
  8635. }
  8636. light.id = parsedLight.id;
  8637. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8638. if (parsedLight.intensity !== undefined) {
  8639. light.intensity = parsedLight.intensity;
  8640. }
  8641. if (parsedLight.range) {
  8642. light.range = parsedLight.range;
  8643. }
  8644. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8645. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8646. if (parsedLight.excludedMeshesIds) {
  8647. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8648. }
  8649. // Parent
  8650. if (parsedLight.parentId) {
  8651. light._waitingParentId = parsedLight.parentId;
  8652. }
  8653. if (parsedLight.includedOnlyMeshesIds) {
  8654. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8655. }
  8656. // Animations
  8657. if (parsedLight.animations) {
  8658. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8659. var parsedAnimation = parsedLight.animations[animationIndex];
  8660. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8661. }
  8662. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8663. }
  8664. if (parsedLight.autoAnimate) {
  8665. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8666. }
  8667. return light;
  8668. };
  8669. return Light;
  8670. })(BABYLON.Node);
  8671. BABYLON.Light = Light;
  8672. })(BABYLON || (BABYLON = {}));
  8673. var BABYLON;
  8674. (function (BABYLON) {
  8675. var PointLight = (function (_super) {
  8676. __extends(PointLight, _super);
  8677. function PointLight(name, position, scene) {
  8678. _super.call(this, name, scene);
  8679. this.position = position;
  8680. }
  8681. PointLight.prototype.getAbsolutePosition = function () {
  8682. return this.transformedPosition ? this.transformedPosition : this.position;
  8683. };
  8684. PointLight.prototype.computeTransformedPosition = function () {
  8685. if (this.parent && this.parent.getWorldMatrix) {
  8686. if (!this.transformedPosition) {
  8687. this.transformedPosition = BABYLON.Vector3.Zero();
  8688. }
  8689. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8690. return true;
  8691. }
  8692. return false;
  8693. };
  8694. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8695. if (this.parent && this.parent.getWorldMatrix) {
  8696. this.computeTransformedPosition();
  8697. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8698. return;
  8699. }
  8700. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8701. };
  8702. PointLight.prototype.needCube = function () {
  8703. return true;
  8704. };
  8705. PointLight.prototype.supportsVSM = function () {
  8706. return false;
  8707. };
  8708. PointLight.prototype.needRefreshPerFrame = function () {
  8709. return false;
  8710. };
  8711. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8712. switch (faceIndex) {
  8713. case 0:
  8714. return new BABYLON.Vector3(1, 0, 0);
  8715. case 1:
  8716. return new BABYLON.Vector3(-1, 0, 0);
  8717. case 2:
  8718. return new BABYLON.Vector3(0, -1, 0);
  8719. case 3:
  8720. return new BABYLON.Vector3(0, 1, 0);
  8721. case 4:
  8722. return new BABYLON.Vector3(0, 0, 1);
  8723. case 5:
  8724. return new BABYLON.Vector3(0, 0, -1);
  8725. }
  8726. return BABYLON.Vector3.Zero();
  8727. };
  8728. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8729. var activeCamera = this.getScene().activeCamera;
  8730. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8731. };
  8732. PointLight.prototype._getWorldMatrix = function () {
  8733. if (!this._worldMatrix) {
  8734. this._worldMatrix = BABYLON.Matrix.Identity();
  8735. }
  8736. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8737. return this._worldMatrix;
  8738. };
  8739. PointLight.prototype.serialize = function () {
  8740. var serializationObject = _super.prototype.serialize.call(this);
  8741. serializationObject.type = 0;
  8742. serializationObject.position = this.position.asArray();
  8743. return serializationObject;
  8744. };
  8745. return PointLight;
  8746. })(BABYLON.Light);
  8747. BABYLON.PointLight = PointLight;
  8748. })(BABYLON || (BABYLON = {}));
  8749. var BABYLON;
  8750. (function (BABYLON) {
  8751. var SpotLight = (function (_super) {
  8752. __extends(SpotLight, _super);
  8753. function SpotLight(name, position, direction, angle, exponent, scene) {
  8754. _super.call(this, name, scene);
  8755. this.position = position;
  8756. this.direction = direction;
  8757. this.angle = angle;
  8758. this.exponent = exponent;
  8759. }
  8760. SpotLight.prototype.getAbsolutePosition = function () {
  8761. return this.transformedPosition ? this.transformedPosition : this.position;
  8762. };
  8763. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8764. var activeCamera = this.getScene().activeCamera;
  8765. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8766. };
  8767. SpotLight.prototype.needCube = function () {
  8768. return false;
  8769. };
  8770. SpotLight.prototype.supportsVSM = function () {
  8771. return true;
  8772. };
  8773. SpotLight.prototype.needRefreshPerFrame = function () {
  8774. return false;
  8775. };
  8776. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8777. return this.direction;
  8778. };
  8779. SpotLight.prototype.setDirectionToTarget = function (target) {
  8780. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8781. return this.direction;
  8782. };
  8783. SpotLight.prototype.computeTransformedPosition = function () {
  8784. if (this.parent && this.parent.getWorldMatrix) {
  8785. if (!this.transformedPosition) {
  8786. this.transformedPosition = BABYLON.Vector3.Zero();
  8787. }
  8788. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8789. return true;
  8790. }
  8791. return false;
  8792. };
  8793. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8794. var normalizeDirection;
  8795. if (this.parent && this.parent.getWorldMatrix) {
  8796. if (!this._transformedDirection) {
  8797. this._transformedDirection = BABYLON.Vector3.Zero();
  8798. }
  8799. this.computeTransformedPosition();
  8800. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8801. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8802. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8803. }
  8804. else {
  8805. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8806. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8807. }
  8808. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8809. };
  8810. SpotLight.prototype._getWorldMatrix = function () {
  8811. if (!this._worldMatrix) {
  8812. this._worldMatrix = BABYLON.Matrix.Identity();
  8813. }
  8814. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8815. return this._worldMatrix;
  8816. };
  8817. SpotLight.prototype.serialize = function () {
  8818. var serializationObject = _super.prototype.serialize.call(this);
  8819. serializationObject.type = 2;
  8820. serializationObject.position = this.position.asArray();
  8821. serializationObject.direction = this.position.asArray();
  8822. serializationObject.angle = this.angle;
  8823. serializationObject.exponent = this.exponent;
  8824. return serializationObject;
  8825. };
  8826. return SpotLight;
  8827. })(BABYLON.Light);
  8828. BABYLON.SpotLight = SpotLight;
  8829. })(BABYLON || (BABYLON = {}));
  8830. var BABYLON;
  8831. (function (BABYLON) {
  8832. var HemisphericLight = (function (_super) {
  8833. __extends(HemisphericLight, _super);
  8834. function HemisphericLight(name, direction, scene) {
  8835. _super.call(this, name, scene);
  8836. this.direction = direction;
  8837. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8838. }
  8839. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8840. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8841. return this.direction;
  8842. };
  8843. HemisphericLight.prototype.getShadowGenerator = function () {
  8844. return null;
  8845. };
  8846. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8847. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8848. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8849. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8850. };
  8851. HemisphericLight.prototype._getWorldMatrix = function () {
  8852. if (!this._worldMatrix) {
  8853. this._worldMatrix = BABYLON.Matrix.Identity();
  8854. }
  8855. return this._worldMatrix;
  8856. };
  8857. HemisphericLight.prototype.serialize = function () {
  8858. var serializationObject = _super.prototype.serialize.call(this);
  8859. serializationObject.type = 3;
  8860. serializationObject.direction = this.direction.asArray();
  8861. serializationObject.groundColor = this.groundColor.asArray();
  8862. return serializationObject;
  8863. };
  8864. return HemisphericLight;
  8865. })(BABYLON.Light);
  8866. BABYLON.HemisphericLight = HemisphericLight;
  8867. })(BABYLON || (BABYLON = {}));
  8868. var BABYLON;
  8869. (function (BABYLON) {
  8870. var DirectionalLight = (function (_super) {
  8871. __extends(DirectionalLight, _super);
  8872. function DirectionalLight(name, direction, scene) {
  8873. _super.call(this, name, scene);
  8874. this.direction = direction;
  8875. this.shadowOrthoScale = 0.5;
  8876. this.autoUpdateExtends = true;
  8877. // Cache
  8878. this._orthoLeft = Number.MAX_VALUE;
  8879. this._orthoRight = Number.MIN_VALUE;
  8880. this._orthoTop = Number.MIN_VALUE;
  8881. this._orthoBottom = Number.MAX_VALUE;
  8882. this.position = direction.scale(-1);
  8883. }
  8884. DirectionalLight.prototype.getAbsolutePosition = function () {
  8885. return this.transformedPosition ? this.transformedPosition : this.position;
  8886. };
  8887. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8888. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8889. return this.direction;
  8890. };
  8891. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8892. var activeCamera = this.getScene().activeCamera;
  8893. // Check extends
  8894. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8895. var tempVector3 = BABYLON.Vector3.Zero();
  8896. this._orthoLeft = Number.MAX_VALUE;
  8897. this._orthoRight = Number.MIN_VALUE;
  8898. this._orthoTop = Number.MIN_VALUE;
  8899. this._orthoBottom = Number.MAX_VALUE;
  8900. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8901. var mesh = renderList[meshIndex];
  8902. if (!mesh) {
  8903. continue;
  8904. }
  8905. var boundingInfo = mesh.getBoundingInfo();
  8906. if (!boundingInfo) {
  8907. continue;
  8908. }
  8909. var boundingBox = boundingInfo.boundingBox;
  8910. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8911. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8912. if (tempVector3.x < this._orthoLeft)
  8913. this._orthoLeft = tempVector3.x;
  8914. if (tempVector3.y < this._orthoBottom)
  8915. this._orthoBottom = tempVector3.y;
  8916. if (tempVector3.x > this._orthoRight)
  8917. this._orthoRight = tempVector3.x;
  8918. if (tempVector3.y > this._orthoTop)
  8919. this._orthoTop = tempVector3.y;
  8920. }
  8921. }
  8922. }
  8923. var xOffset = this._orthoRight - this._orthoLeft;
  8924. var yOffset = this._orthoTop - this._orthoBottom;
  8925. 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);
  8926. };
  8927. DirectionalLight.prototype.supportsVSM = function () {
  8928. return true;
  8929. };
  8930. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8931. return true;
  8932. };
  8933. DirectionalLight.prototype.needCube = function () {
  8934. return false;
  8935. };
  8936. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8937. return this.direction;
  8938. };
  8939. DirectionalLight.prototype.computeTransformedPosition = function () {
  8940. if (this.parent && this.parent.getWorldMatrix) {
  8941. if (!this.transformedPosition) {
  8942. this.transformedPosition = BABYLON.Vector3.Zero();
  8943. }
  8944. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8945. return true;
  8946. }
  8947. return false;
  8948. };
  8949. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8950. if (this.parent && this.parent.getWorldMatrix) {
  8951. if (!this._transformedDirection) {
  8952. this._transformedDirection = BABYLON.Vector3.Zero();
  8953. }
  8954. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8955. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8956. return;
  8957. }
  8958. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8959. };
  8960. DirectionalLight.prototype._getWorldMatrix = function () {
  8961. if (!this._worldMatrix) {
  8962. this._worldMatrix = BABYLON.Matrix.Identity();
  8963. }
  8964. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8965. return this._worldMatrix;
  8966. };
  8967. DirectionalLight.prototype.serialize = function () {
  8968. var serializationObject = _super.prototype.serialize.call(this);
  8969. serializationObject.type = 1;
  8970. serializationObject.position = this.position.asArray();
  8971. serializationObject.direction = this.direction.asArray();
  8972. return serializationObject;
  8973. };
  8974. return DirectionalLight;
  8975. })(BABYLON.Light);
  8976. BABYLON.DirectionalLight = DirectionalLight;
  8977. })(BABYLON || (BABYLON = {}));
  8978. var BABYLON;
  8979. (function (BABYLON) {
  8980. var ShadowGenerator = (function () {
  8981. function ShadowGenerator(mapSize, light) {
  8982. var _this = this;
  8983. // Members
  8984. this._filter = ShadowGenerator.FILTER_NONE;
  8985. this.blurScale = 2;
  8986. this._blurBoxOffset = 0;
  8987. this._bias = 0.00005;
  8988. this._lightDirection = BABYLON.Vector3.Zero();
  8989. this.forceBackFacesOnly = false;
  8990. this._darkness = 0;
  8991. this._transparencyShadow = false;
  8992. this._viewMatrix = BABYLON.Matrix.Zero();
  8993. this._projectionMatrix = BABYLON.Matrix.Zero();
  8994. this._transformMatrix = BABYLON.Matrix.Zero();
  8995. this._worldViewProjection = BABYLON.Matrix.Zero();
  8996. this._currentFaceIndex = 0;
  8997. this._currentFaceIndexCache = 0;
  8998. this._light = light;
  8999. this._scene = light.getScene();
  9000. this._mapSize = mapSize;
  9001. light._shadowGenerator = this;
  9002. // Render target
  9003. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9004. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9005. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9006. this._shadowMap.anisotropicFilteringLevel = 1;
  9007. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9008. this._shadowMap.renderParticles = false;
  9009. this._shadowMap.onBeforeRender = function (faceIndex) {
  9010. _this._currentFaceIndex = faceIndex;
  9011. };
  9012. this._shadowMap.onAfterUnbind = function () {
  9013. if (!_this.useBlurVarianceShadowMap) {
  9014. return;
  9015. }
  9016. if (!_this._shadowMap2) {
  9017. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9018. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9019. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9020. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9021. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9022. _this._downSamplePostprocess.onApply = function (effect) {
  9023. effect.setTexture("textureSampler", _this._shadowMap);
  9024. };
  9025. _this.blurBoxOffset = 1;
  9026. }
  9027. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9028. };
  9029. // Custom render function
  9030. var renderSubMesh = function (subMesh) {
  9031. var mesh = subMesh.getRenderingMesh();
  9032. var scene = _this._scene;
  9033. var engine = scene.getEngine();
  9034. // Culling
  9035. engine.setState(subMesh.getMaterial().backFaceCulling);
  9036. // Managing instances
  9037. var batch = mesh._getInstancesRenderList(subMesh._id);
  9038. if (batch.mustReturn) {
  9039. return;
  9040. }
  9041. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9042. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9043. engine.enableEffect(_this._effect);
  9044. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9045. var material = subMesh.getMaterial();
  9046. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9047. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9048. if (_this.getLight().needCube()) {
  9049. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9050. }
  9051. // Alpha test
  9052. if (material && material.needAlphaTesting()) {
  9053. var alphaTexture = material.getAlphaTestTexture();
  9054. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9055. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9056. }
  9057. // Bones
  9058. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9059. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9060. }
  9061. if (_this.forceBackFacesOnly) {
  9062. engine.setState(true, 0, false, true);
  9063. }
  9064. // Draw
  9065. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9066. if (_this.forceBackFacesOnly) {
  9067. engine.setState(true, 0, false, false);
  9068. }
  9069. }
  9070. else {
  9071. // Need to reset refresh rate of the shadowMap
  9072. _this._shadowMap.resetRefreshCounter();
  9073. }
  9074. };
  9075. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9076. var index;
  9077. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9078. renderSubMesh(opaqueSubMeshes.data[index]);
  9079. }
  9080. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9081. renderSubMesh(alphaTestSubMeshes.data[index]);
  9082. }
  9083. if (_this._transparencyShadow) {
  9084. for (index = 0; index < transparentSubMeshes.length; index++) {
  9085. renderSubMesh(transparentSubMeshes.data[index]);
  9086. }
  9087. }
  9088. };
  9089. this._shadowMap.onClear = function (engine) {
  9090. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9091. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9092. }
  9093. else {
  9094. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9095. }
  9096. };
  9097. }
  9098. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9099. // Static
  9100. get: function () {
  9101. return ShadowGenerator._FILTER_NONE;
  9102. },
  9103. enumerable: true,
  9104. configurable: true
  9105. });
  9106. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9107. get: function () {
  9108. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9109. },
  9110. enumerable: true,
  9111. configurable: true
  9112. });
  9113. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9114. get: function () {
  9115. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9116. },
  9117. enumerable: true,
  9118. configurable: true
  9119. });
  9120. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9121. get: function () {
  9122. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9123. },
  9124. enumerable: true,
  9125. configurable: true
  9126. });
  9127. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9128. get: function () {
  9129. return this._bias;
  9130. },
  9131. set: function (bias) {
  9132. this._bias = bias;
  9133. },
  9134. enumerable: true,
  9135. configurable: true
  9136. });
  9137. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9138. get: function () {
  9139. return this._blurBoxOffset;
  9140. },
  9141. set: function (value) {
  9142. var _this = this;
  9143. if (this._blurBoxOffset === value) {
  9144. return;
  9145. }
  9146. this._blurBoxOffset = value;
  9147. if (this._boxBlurPostprocess) {
  9148. this._boxBlurPostprocess.dispose();
  9149. }
  9150. 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);
  9151. this._boxBlurPostprocess.onApply = function (effect) {
  9152. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9153. };
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9159. get: function () {
  9160. return this._filter;
  9161. },
  9162. set: function (value) {
  9163. if (this._filter === value) {
  9164. return;
  9165. }
  9166. this._filter = value;
  9167. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9168. this._shadowMap.anisotropicFilteringLevel = 16;
  9169. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9170. }
  9171. else {
  9172. this._shadowMap.anisotropicFilteringLevel = 1;
  9173. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9174. }
  9175. },
  9176. enumerable: true,
  9177. configurable: true
  9178. });
  9179. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9180. get: function () {
  9181. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9182. },
  9183. set: function (value) {
  9184. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9185. },
  9186. enumerable: true,
  9187. configurable: true
  9188. });
  9189. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9190. get: function () {
  9191. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9192. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9193. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9194. },
  9195. set: function (value) {
  9196. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9197. },
  9198. enumerable: true,
  9199. configurable: true
  9200. });
  9201. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9202. get: function () {
  9203. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9204. },
  9205. set: function (value) {
  9206. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9207. },
  9208. enumerable: true,
  9209. configurable: true
  9210. });
  9211. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9212. var defines = [];
  9213. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9214. defines.push("#define VSM");
  9215. }
  9216. if (this.getLight().needCube()) {
  9217. defines.push("#define CUBEMAP");
  9218. }
  9219. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9220. var mesh = subMesh.getMesh();
  9221. var material = subMesh.getMaterial();
  9222. // Alpha test
  9223. if (material && material.needAlphaTesting()) {
  9224. defines.push("#define ALPHATEST");
  9225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9226. attribs.push(BABYLON.VertexBuffer.UVKind);
  9227. defines.push("#define UV1");
  9228. }
  9229. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9230. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9231. defines.push("#define UV2");
  9232. }
  9233. }
  9234. // Bones
  9235. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9236. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9237. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9238. if (mesh.numBoneInfluencers > 4) {
  9239. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9240. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9241. }
  9242. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9243. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9244. }
  9245. else {
  9246. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9247. }
  9248. // Instances
  9249. if (useInstances) {
  9250. defines.push("#define INSTANCES");
  9251. attribs.push("world0");
  9252. attribs.push("world1");
  9253. attribs.push("world2");
  9254. attribs.push("world3");
  9255. }
  9256. // Get correct effect
  9257. var join = defines.join("\n");
  9258. if (this._cachedDefines !== join) {
  9259. this._cachedDefines = join;
  9260. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9261. }
  9262. return this._effect.isReady();
  9263. };
  9264. ShadowGenerator.prototype.getShadowMap = function () {
  9265. return this._shadowMap;
  9266. };
  9267. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9268. if (this._shadowMap2) {
  9269. return this._shadowMap2;
  9270. }
  9271. return this._shadowMap;
  9272. };
  9273. ShadowGenerator.prototype.getLight = function () {
  9274. return this._light;
  9275. };
  9276. // Methods
  9277. ShadowGenerator.prototype.getTransformMatrix = function () {
  9278. var scene = this._scene;
  9279. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9280. return this._transformMatrix;
  9281. }
  9282. this._currentRenderID = scene.getRenderId();
  9283. this._currentFaceIndexCache = this._currentFaceIndex;
  9284. var lightPosition = this._light.position;
  9285. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9286. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9287. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9288. }
  9289. if (this._light.computeTransformedPosition()) {
  9290. lightPosition = this._light.transformedPosition;
  9291. }
  9292. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9293. this._cachedPosition = lightPosition.clone();
  9294. this._cachedDirection = this._lightDirection.clone();
  9295. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9296. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9297. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9298. }
  9299. return this._transformMatrix;
  9300. };
  9301. ShadowGenerator.prototype.getDarkness = function () {
  9302. return this._darkness;
  9303. };
  9304. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9305. if (darkness >= 1.0)
  9306. this._darkness = 1.0;
  9307. else if (darkness <= 0.0)
  9308. this._darkness = 0.0;
  9309. else
  9310. this._darkness = darkness;
  9311. };
  9312. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9313. this._transparencyShadow = hasShadow;
  9314. };
  9315. ShadowGenerator.prototype._packHalf = function (depth) {
  9316. var scale = depth * 255.0;
  9317. var fract = scale - Math.floor(scale);
  9318. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9319. };
  9320. ShadowGenerator.prototype.dispose = function () {
  9321. this._shadowMap.dispose();
  9322. if (this._shadowMap2) {
  9323. this._shadowMap2.dispose();
  9324. }
  9325. if (this._downSamplePostprocess) {
  9326. this._downSamplePostprocess.dispose();
  9327. }
  9328. if (this._boxBlurPostprocess) {
  9329. this._boxBlurPostprocess.dispose();
  9330. }
  9331. };
  9332. ShadowGenerator.prototype.serialize = function () {
  9333. var serializationObject = {};
  9334. serializationObject.lightId = this._light.id;
  9335. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9336. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9337. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9338. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9339. serializationObject.renderList = [];
  9340. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9341. var mesh = this.getShadowMap().renderList[meshIndex];
  9342. serializationObject.renderList.push(mesh.id);
  9343. }
  9344. return serializationObject;
  9345. };
  9346. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9347. //casting to point light, as light is missing the position attr and typescript complains.
  9348. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9349. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9350. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9351. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9352. shadowGenerator.getShadowMap().renderList.push(mesh);
  9353. }
  9354. if (parsedShadowGenerator.usePoissonSampling) {
  9355. shadowGenerator.usePoissonSampling = true;
  9356. }
  9357. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9358. shadowGenerator.useVarianceShadowMap = true;
  9359. }
  9360. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9361. shadowGenerator.useBlurVarianceShadowMap = true;
  9362. if (parsedShadowGenerator.blurScale) {
  9363. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9364. }
  9365. if (parsedShadowGenerator.blurBoxOffset) {
  9366. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9367. }
  9368. }
  9369. if (parsedShadowGenerator.bias !== undefined) {
  9370. shadowGenerator.bias = parsedShadowGenerator.bias;
  9371. }
  9372. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9373. return shadowGenerator;
  9374. };
  9375. ShadowGenerator._FILTER_NONE = 0;
  9376. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9377. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9378. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9379. return ShadowGenerator;
  9380. })();
  9381. BABYLON.ShadowGenerator = ShadowGenerator;
  9382. })(BABYLON || (BABYLON = {}));
  9383. var BABYLON;
  9384. (function (BABYLON) {
  9385. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9386. if (boxMin.x > sphereCenter.x + sphereRadius)
  9387. return false;
  9388. if (sphereCenter.x - sphereRadius > boxMax.x)
  9389. return false;
  9390. if (boxMin.y > sphereCenter.y + sphereRadius)
  9391. return false;
  9392. if (sphereCenter.y - sphereRadius > boxMax.y)
  9393. return false;
  9394. if (boxMin.z > sphereCenter.z + sphereRadius)
  9395. return false;
  9396. if (sphereCenter.z - sphereRadius > boxMax.z)
  9397. return false;
  9398. return true;
  9399. };
  9400. var getLowestRoot = function (a, b, c, maxR) {
  9401. var determinant = b * b - 4.0 * a * c;
  9402. var result = { root: 0, found: false };
  9403. if (determinant < 0)
  9404. return result;
  9405. var sqrtD = Math.sqrt(determinant);
  9406. var r1 = (-b - sqrtD) / (2.0 * a);
  9407. var r2 = (-b + sqrtD) / (2.0 * a);
  9408. if (r1 > r2) {
  9409. var temp = r2;
  9410. r2 = r1;
  9411. r1 = temp;
  9412. }
  9413. if (r1 > 0 && r1 < maxR) {
  9414. result.root = r1;
  9415. result.found = true;
  9416. return result;
  9417. }
  9418. if (r2 > 0 && r2 < maxR) {
  9419. result.root = r2;
  9420. result.found = true;
  9421. return result;
  9422. }
  9423. return result;
  9424. };
  9425. var Collider = (function () {
  9426. function Collider() {
  9427. this.radius = new BABYLON.Vector3(1, 1, 1);
  9428. this.retry = 0;
  9429. this.basePointWorld = BABYLON.Vector3.Zero();
  9430. this.velocityWorld = BABYLON.Vector3.Zero();
  9431. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9432. this._collisionPoint = BABYLON.Vector3.Zero();
  9433. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9434. this._tempVector = BABYLON.Vector3.Zero();
  9435. this._tempVector2 = BABYLON.Vector3.Zero();
  9436. this._tempVector3 = BABYLON.Vector3.Zero();
  9437. this._tempVector4 = BABYLON.Vector3.Zero();
  9438. this._edge = BABYLON.Vector3.Zero();
  9439. this._baseToVertex = BABYLON.Vector3.Zero();
  9440. this._destinationPoint = BABYLON.Vector3.Zero();
  9441. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9442. this._displacementVector = BABYLON.Vector3.Zero();
  9443. }
  9444. // Methods
  9445. Collider.prototype._initialize = function (source, dir, e) {
  9446. this.velocity = dir;
  9447. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9448. this.basePoint = source;
  9449. source.multiplyToRef(this.radius, this.basePointWorld);
  9450. dir.multiplyToRef(this.radius, this.velocityWorld);
  9451. this.velocityWorldLength = this.velocityWorld.length();
  9452. this.epsilon = e;
  9453. this.collisionFound = false;
  9454. };
  9455. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9456. pa.subtractToRef(point, this._tempVector);
  9457. pb.subtractToRef(point, this._tempVector2);
  9458. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9459. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9460. if (d < 0)
  9461. return false;
  9462. pc.subtractToRef(point, this._tempVector3);
  9463. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9464. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9465. if (d < 0)
  9466. return false;
  9467. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9468. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9469. return d >= 0;
  9470. };
  9471. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9472. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9473. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9474. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9475. return false;
  9476. }
  9477. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9478. return false;
  9479. return true;
  9480. };
  9481. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9482. var t0;
  9483. var embeddedInPlane = false;
  9484. //defensive programming, actually not needed.
  9485. if (!trianglePlaneArray) {
  9486. trianglePlaneArray = [];
  9487. }
  9488. if (!trianglePlaneArray[faceIndex]) {
  9489. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9490. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9491. }
  9492. var trianglePlane = trianglePlaneArray[faceIndex];
  9493. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9494. return;
  9495. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9496. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9497. if (normalDotVelocity == 0) {
  9498. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9499. return;
  9500. embeddedInPlane = true;
  9501. t0 = 0;
  9502. }
  9503. else {
  9504. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9505. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9506. if (t0 > t1) {
  9507. var temp = t1;
  9508. t1 = t0;
  9509. t0 = temp;
  9510. }
  9511. if (t0 > 1.0 || t1 < 0.0)
  9512. return;
  9513. if (t0 < 0)
  9514. t0 = 0;
  9515. if (t0 > 1.0)
  9516. t0 = 1.0;
  9517. }
  9518. this._collisionPoint.copyFromFloats(0, 0, 0);
  9519. var found = false;
  9520. var t = 1.0;
  9521. if (!embeddedInPlane) {
  9522. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9523. this.velocity.scaleToRef(t0, this._tempVector);
  9524. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9525. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9526. found = true;
  9527. t = t0;
  9528. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9529. }
  9530. }
  9531. if (!found) {
  9532. var velocitySquaredLength = this.velocity.lengthSquared();
  9533. var a = velocitySquaredLength;
  9534. this.basePoint.subtractToRef(p1, this._tempVector);
  9535. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9536. var c = this._tempVector.lengthSquared() - 1.0;
  9537. var lowestRoot = getLowestRoot(a, b, c, t);
  9538. if (lowestRoot.found) {
  9539. t = lowestRoot.root;
  9540. found = true;
  9541. this._collisionPoint.copyFrom(p1);
  9542. }
  9543. this.basePoint.subtractToRef(p2, this._tempVector);
  9544. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9545. c = this._tempVector.lengthSquared() - 1.0;
  9546. lowestRoot = getLowestRoot(a, b, c, t);
  9547. if (lowestRoot.found) {
  9548. t = lowestRoot.root;
  9549. found = true;
  9550. this._collisionPoint.copyFrom(p2);
  9551. }
  9552. this.basePoint.subtractToRef(p3, this._tempVector);
  9553. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9554. c = this._tempVector.lengthSquared() - 1.0;
  9555. lowestRoot = getLowestRoot(a, b, c, t);
  9556. if (lowestRoot.found) {
  9557. t = lowestRoot.root;
  9558. found = true;
  9559. this._collisionPoint.copyFrom(p3);
  9560. }
  9561. p2.subtractToRef(p1, this._edge);
  9562. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9563. var edgeSquaredLength = this._edge.lengthSquared();
  9564. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9565. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9566. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9567. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9568. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9569. lowestRoot = getLowestRoot(a, b, c, t);
  9570. if (lowestRoot.found) {
  9571. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9572. if (f >= 0.0 && f <= 1.0) {
  9573. t = lowestRoot.root;
  9574. found = true;
  9575. this._edge.scaleInPlace(f);
  9576. p1.addToRef(this._edge, this._collisionPoint);
  9577. }
  9578. }
  9579. p3.subtractToRef(p2, this._edge);
  9580. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9581. edgeSquaredLength = this._edge.lengthSquared();
  9582. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9583. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9584. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9585. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9586. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9587. lowestRoot = getLowestRoot(a, b, c, t);
  9588. if (lowestRoot.found) {
  9589. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9590. if (f >= 0.0 && f <= 1.0) {
  9591. t = lowestRoot.root;
  9592. found = true;
  9593. this._edge.scaleInPlace(f);
  9594. p2.addToRef(this._edge, this._collisionPoint);
  9595. }
  9596. }
  9597. p1.subtractToRef(p3, this._edge);
  9598. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9599. edgeSquaredLength = this._edge.lengthSquared();
  9600. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9601. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9602. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9603. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9604. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9605. lowestRoot = getLowestRoot(a, b, c, t);
  9606. if (lowestRoot.found) {
  9607. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9608. if (f >= 0.0 && f <= 1.0) {
  9609. t = lowestRoot.root;
  9610. found = true;
  9611. this._edge.scaleInPlace(f);
  9612. p3.addToRef(this._edge, this._collisionPoint);
  9613. }
  9614. }
  9615. }
  9616. if (found) {
  9617. var distToCollision = t * this.velocity.length();
  9618. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9619. if (!this.intersectionPoint) {
  9620. this.intersectionPoint = this._collisionPoint.clone();
  9621. }
  9622. else {
  9623. this.intersectionPoint.copyFrom(this._collisionPoint);
  9624. }
  9625. this.nearestDistance = distToCollision;
  9626. this.collisionFound = true;
  9627. }
  9628. }
  9629. };
  9630. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9631. for (var i = indexStart; i < indexEnd; i += 3) {
  9632. var p1 = pts[indices[i] - decal];
  9633. var p2 = pts[indices[i + 1] - decal];
  9634. var p3 = pts[indices[i + 2] - decal];
  9635. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9636. }
  9637. };
  9638. Collider.prototype._getResponse = function (pos, vel) {
  9639. pos.addToRef(vel, this._destinationPoint);
  9640. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9641. this.basePoint.addToRef(vel, pos);
  9642. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9643. this._slidePlaneNormal.normalize();
  9644. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9645. pos.addInPlace(this._displacementVector);
  9646. this.intersectionPoint.addInPlace(this._displacementVector);
  9647. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9648. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9649. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9650. };
  9651. return Collider;
  9652. })();
  9653. BABYLON.Collider = Collider;
  9654. })(BABYLON || (BABYLON = {}));
  9655. var BABYLON;
  9656. (function (BABYLON) {
  9657. //WebWorker code will be inserted to this variable.
  9658. BABYLON.CollisionWorker = "";
  9659. (function (WorkerTaskType) {
  9660. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9661. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9662. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9663. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9664. var WorkerTaskType = BABYLON.WorkerTaskType;
  9665. (function (WorkerReplyType) {
  9666. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9667. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9668. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9669. var WorkerReplyType = BABYLON.WorkerReplyType;
  9670. var CollisionCoordinatorWorker = (function () {
  9671. function CollisionCoordinatorWorker() {
  9672. var _this = this;
  9673. this._scaledPosition = BABYLON.Vector3.Zero();
  9674. this._scaledVelocity = BABYLON.Vector3.Zero();
  9675. this.onMeshUpdated = function (mesh) {
  9676. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9677. };
  9678. this.onGeometryUpdated = function (geometry) {
  9679. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9680. };
  9681. this._afterRender = function () {
  9682. if (!_this._init)
  9683. return;
  9684. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9685. return;
  9686. }
  9687. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9688. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9689. if (_this._runningUpdated > 4) {
  9690. return;
  9691. }
  9692. ++_this._runningUpdated;
  9693. var payload = {
  9694. updatedMeshes: _this._addUpdateMeshesList,
  9695. updatedGeometries: _this._addUpdateGeometriesList,
  9696. removedGeometries: _this._toRemoveGeometryArray,
  9697. removedMeshes: _this._toRemoveMeshesArray
  9698. };
  9699. var message = {
  9700. payload: payload,
  9701. taskType: WorkerTaskType.UPDATE
  9702. };
  9703. var serializable = [];
  9704. for (var id in payload.updatedGeometries) {
  9705. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9706. //prepare transferables
  9707. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9708. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9709. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9710. }
  9711. }
  9712. _this._worker.postMessage(message, serializable);
  9713. _this._addUpdateMeshesList = {};
  9714. _this._addUpdateGeometriesList = {};
  9715. _this._toRemoveGeometryArray = [];
  9716. _this._toRemoveMeshesArray = [];
  9717. };
  9718. this._onMessageFromWorker = function (e) {
  9719. var returnData = e.data;
  9720. if (returnData.error != WorkerReplyType.SUCCESS) {
  9721. //TODO what errors can be returned from the worker?
  9722. BABYLON.Tools.Warn("error returned from worker!");
  9723. return;
  9724. }
  9725. switch (returnData.taskType) {
  9726. case WorkerTaskType.INIT:
  9727. _this._init = true;
  9728. //Update the worked with ALL of the scene's current state
  9729. _this._scene.meshes.forEach(function (mesh) {
  9730. _this.onMeshAdded(mesh);
  9731. });
  9732. _this._scene.getGeometries().forEach(function (geometry) {
  9733. _this.onGeometryAdded(geometry);
  9734. });
  9735. break;
  9736. case WorkerTaskType.UPDATE:
  9737. _this._runningUpdated--;
  9738. break;
  9739. case WorkerTaskType.COLLIDE:
  9740. _this._runningCollisionTask = false;
  9741. var returnPayload = returnData.payload;
  9742. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9743. return;
  9744. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9745. //cleanup
  9746. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9747. break;
  9748. }
  9749. };
  9750. this._collisionsCallbackArray = [];
  9751. this._init = false;
  9752. this._runningUpdated = 0;
  9753. this._runningCollisionTask = false;
  9754. this._addUpdateMeshesList = {};
  9755. this._addUpdateGeometriesList = {};
  9756. this._toRemoveGeometryArray = [];
  9757. this._toRemoveMeshesArray = [];
  9758. }
  9759. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9760. if (!this._init)
  9761. return;
  9762. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9763. return;
  9764. position.divideToRef(collider.radius, this._scaledPosition);
  9765. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9766. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9767. var payload = {
  9768. collider: {
  9769. position: this._scaledPosition.asArray(),
  9770. velocity: this._scaledVelocity.asArray(),
  9771. radius: collider.radius.asArray()
  9772. },
  9773. collisionId: collisionIndex,
  9774. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9775. maximumRetry: maximumRetry
  9776. };
  9777. var message = {
  9778. payload: payload,
  9779. taskType: WorkerTaskType.COLLIDE
  9780. };
  9781. this._worker.postMessage(message);
  9782. };
  9783. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9784. this._scene = scene;
  9785. this._scene.registerAfterRender(this._afterRender);
  9786. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9787. this._worker = new Worker(workerUrl);
  9788. this._worker.onmessage = this._onMessageFromWorker;
  9789. var message = {
  9790. payload: {},
  9791. taskType: WorkerTaskType.INIT
  9792. };
  9793. this._worker.postMessage(message);
  9794. };
  9795. CollisionCoordinatorWorker.prototype.destroy = function () {
  9796. this._scene.unregisterAfterRender(this._afterRender);
  9797. this._worker.terminate();
  9798. };
  9799. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9800. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9801. this.onMeshUpdated(mesh);
  9802. };
  9803. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9804. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9805. };
  9806. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9807. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9808. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9809. this.onGeometryUpdated(geometry);
  9810. };
  9811. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9812. this._toRemoveGeometryArray.push(geometry.id);
  9813. };
  9814. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9815. var submeshes = [];
  9816. if (mesh.subMeshes) {
  9817. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9818. return {
  9819. position: idx,
  9820. verticesStart: sm.verticesStart,
  9821. verticesCount: sm.verticesCount,
  9822. indexStart: sm.indexStart,
  9823. indexCount: sm.indexCount,
  9824. hasMaterial: !!sm.getMaterial(),
  9825. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9826. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9827. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9828. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9829. };
  9830. });
  9831. }
  9832. var geometryId = null;
  9833. if (mesh instanceof BABYLON.Mesh) {
  9834. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9835. }
  9836. else if (mesh instanceof BABYLON.InstancedMesh) {
  9837. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9838. }
  9839. return {
  9840. uniqueId: mesh.uniqueId,
  9841. id: mesh.id,
  9842. name: mesh.name,
  9843. geometryId: geometryId,
  9844. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9845. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9846. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9847. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9848. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9849. subMeshes: submeshes,
  9850. checkCollisions: mesh.checkCollisions
  9851. };
  9852. };
  9853. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9854. return {
  9855. id: geometry.id,
  9856. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9857. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9858. indices: new Int32Array(geometry.getIndices() || []),
  9859. };
  9860. };
  9861. return CollisionCoordinatorWorker;
  9862. })();
  9863. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9864. var CollisionCoordinatorLegacy = (function () {
  9865. function CollisionCoordinatorLegacy() {
  9866. this._scaledPosition = BABYLON.Vector3.Zero();
  9867. this._scaledVelocity = BABYLON.Vector3.Zero();
  9868. this._finalPosition = BABYLON.Vector3.Zero();
  9869. }
  9870. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9871. position.divideToRef(collider.radius, this._scaledPosition);
  9872. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9873. collider.collidedMesh = null;
  9874. collider.retry = 0;
  9875. collider.initialVelocity = this._scaledVelocity;
  9876. collider.initialPosition = this._scaledPosition;
  9877. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9878. this._finalPosition.multiplyInPlace(collider.radius);
  9879. //run the callback
  9880. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9881. };
  9882. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9883. this._scene = scene;
  9884. };
  9885. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9886. //Legacy need no destruction method.
  9887. };
  9888. //No update in legacy mode
  9889. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9890. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9891. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9892. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9893. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9894. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9895. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9896. if (excludedMesh === void 0) { excludedMesh = null; }
  9897. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9898. if (collider.retry >= maximumRetry) {
  9899. finalPosition.copyFrom(position);
  9900. return;
  9901. }
  9902. collider._initialize(position, velocity, closeDistance);
  9903. // Check all meshes
  9904. for (var index = 0; index < this._scene.meshes.length; index++) {
  9905. var mesh = this._scene.meshes[index];
  9906. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9907. mesh._checkCollision(collider);
  9908. }
  9909. }
  9910. if (!collider.collisionFound) {
  9911. position.addToRef(velocity, finalPosition);
  9912. return;
  9913. }
  9914. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9915. collider._getResponse(position, velocity);
  9916. }
  9917. if (velocity.length() <= closeDistance) {
  9918. finalPosition.copyFrom(position);
  9919. return;
  9920. }
  9921. collider.retry++;
  9922. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9923. };
  9924. return CollisionCoordinatorLegacy;
  9925. })();
  9926. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9927. })(BABYLON || (BABYLON = {}));
  9928. var BABYLON;
  9929. (function (BABYLON) {
  9930. var VRCameraMetrics = (function () {
  9931. function VRCameraMetrics() {
  9932. this.compensateDistortion = true;
  9933. }
  9934. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9935. get: function () {
  9936. return this.hResolution / (2 * this.vResolution);
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9942. get: function () {
  9943. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9949. get: function () {
  9950. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9951. var h = (4 * meters) / this.hScreenSize;
  9952. return BABYLON.Matrix.Translation(h, 0, 0);
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9958. get: function () {
  9959. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9960. var h = (4 * meters) / this.hScreenSize;
  9961. return BABYLON.Matrix.Translation(-h, 0, 0);
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9967. get: function () {
  9968. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9974. get: function () {
  9975. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9976. },
  9977. enumerable: true,
  9978. configurable: true
  9979. });
  9980. VRCameraMetrics.GetDefault = function () {
  9981. var result = new VRCameraMetrics();
  9982. result.hResolution = 1280;
  9983. result.vResolution = 800;
  9984. result.hScreenSize = 0.149759993;
  9985. result.vScreenSize = 0.0935999975;
  9986. result.vScreenCenter = 0.0467999987,
  9987. result.eyeToScreenDistance = 0.0410000011;
  9988. result.lensSeparationDistance = 0.0635000020;
  9989. result.interpupillaryDistance = 0.0640000030;
  9990. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9991. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9992. result.postProcessScaleFactor = 1.714605507808412;
  9993. result.lensCenterOffset = 0.151976421;
  9994. return result;
  9995. };
  9996. return VRCameraMetrics;
  9997. })();
  9998. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9999. var Camera = (function (_super) {
  10000. __extends(Camera, _super);
  10001. function Camera(name, position, scene) {
  10002. _super.call(this, name, scene);
  10003. this.position = position;
  10004. // Members
  10005. this.upVector = BABYLON.Vector3.Up();
  10006. this.orthoLeft = null;
  10007. this.orthoRight = null;
  10008. this.orthoBottom = null;
  10009. this.orthoTop = null;
  10010. this.fov = 0.8;
  10011. this.minZ = 1.0;
  10012. this.maxZ = 10000.0;
  10013. this.inertia = 0.9;
  10014. this.mode = Camera.PERSPECTIVE_CAMERA;
  10015. this.isIntermediate = false;
  10016. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10017. this.layerMask = 0x0FFFFFFF;
  10018. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10019. // Camera rig members
  10020. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10021. this._rigCameras = new Array();
  10022. // Cache
  10023. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10024. this._projectionMatrix = new BABYLON.Matrix();
  10025. this._postProcesses = new Array();
  10026. this._postProcessesTakenIndices = [];
  10027. this._activeMeshes = new BABYLON.SmartArray(256);
  10028. this._globalPosition = BABYLON.Vector3.Zero();
  10029. scene.addCamera(this);
  10030. if (!scene.activeCamera) {
  10031. scene.activeCamera = this;
  10032. }
  10033. }
  10034. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10035. get: function () {
  10036. return Camera._PERSPECTIVE_CAMERA;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10042. get: function () {
  10043. return Camera._ORTHOGRAPHIC_CAMERA;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10049. get: function () {
  10050. return Camera._FOVMODE_VERTICAL_FIXED;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10056. get: function () {
  10057. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10058. },
  10059. enumerable: true,
  10060. configurable: true
  10061. });
  10062. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10063. get: function () {
  10064. return Camera._RIG_MODE_NONE;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10070. get: function () {
  10071. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10072. },
  10073. enumerable: true,
  10074. configurable: true
  10075. });
  10076. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10077. get: function () {
  10078. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10079. },
  10080. enumerable: true,
  10081. configurable: true
  10082. });
  10083. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10084. get: function () {
  10085. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10091. get: function () {
  10092. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10093. },
  10094. enumerable: true,
  10095. configurable: true
  10096. });
  10097. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10098. get: function () {
  10099. return Camera._RIG_MODE_VR;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(Camera.prototype, "globalPosition", {
  10105. get: function () {
  10106. return this._globalPosition;
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Camera.prototype.getActiveMeshes = function () {
  10112. return this._activeMeshes;
  10113. };
  10114. Camera.prototype.isActiveMesh = function (mesh) {
  10115. return (this._activeMeshes.indexOf(mesh) !== -1);
  10116. };
  10117. //Cache
  10118. Camera.prototype._initCache = function () {
  10119. _super.prototype._initCache.call(this);
  10120. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10121. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10122. this._cache.mode = undefined;
  10123. this._cache.minZ = undefined;
  10124. this._cache.maxZ = undefined;
  10125. this._cache.fov = undefined;
  10126. this._cache.aspectRatio = undefined;
  10127. this._cache.orthoLeft = undefined;
  10128. this._cache.orthoRight = undefined;
  10129. this._cache.orthoBottom = undefined;
  10130. this._cache.orthoTop = undefined;
  10131. this._cache.renderWidth = undefined;
  10132. this._cache.renderHeight = undefined;
  10133. };
  10134. Camera.prototype._updateCache = function (ignoreParentClass) {
  10135. if (!ignoreParentClass) {
  10136. _super.prototype._updateCache.call(this);
  10137. }
  10138. var engine = this.getEngine();
  10139. this._cache.position.copyFrom(this.position);
  10140. this._cache.upVector.copyFrom(this.upVector);
  10141. this._cache.mode = this.mode;
  10142. this._cache.minZ = this.minZ;
  10143. this._cache.maxZ = this.maxZ;
  10144. this._cache.fov = this.fov;
  10145. this._cache.aspectRatio = engine.getAspectRatio(this);
  10146. this._cache.orthoLeft = this.orthoLeft;
  10147. this._cache.orthoRight = this.orthoRight;
  10148. this._cache.orthoBottom = this.orthoBottom;
  10149. this._cache.orthoTop = this.orthoTop;
  10150. this._cache.renderWidth = engine.getRenderWidth();
  10151. this._cache.renderHeight = engine.getRenderHeight();
  10152. };
  10153. Camera.prototype._updateFromScene = function () {
  10154. this.updateCache();
  10155. this._update();
  10156. };
  10157. // Synchronized
  10158. Camera.prototype._isSynchronized = function () {
  10159. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10160. };
  10161. Camera.prototype._isSynchronizedViewMatrix = function () {
  10162. if (!_super.prototype._isSynchronized.call(this))
  10163. return false;
  10164. return this._cache.position.equals(this.position)
  10165. && this._cache.upVector.equals(this.upVector)
  10166. && this.isSynchronizedWithParent();
  10167. };
  10168. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10169. var check = this._cache.mode === this.mode
  10170. && this._cache.minZ === this.minZ
  10171. && this._cache.maxZ === this.maxZ;
  10172. if (!check) {
  10173. return false;
  10174. }
  10175. var engine = this.getEngine();
  10176. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10177. check = this._cache.fov === this.fov
  10178. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10179. }
  10180. else {
  10181. check = this._cache.orthoLeft === this.orthoLeft
  10182. && this._cache.orthoRight === this.orthoRight
  10183. && this._cache.orthoBottom === this.orthoBottom
  10184. && this._cache.orthoTop === this.orthoTop
  10185. && this._cache.renderWidth === engine.getRenderWidth()
  10186. && this._cache.renderHeight === engine.getRenderHeight();
  10187. }
  10188. return check;
  10189. };
  10190. // Controls
  10191. Camera.prototype.attachControl = function (element) {
  10192. };
  10193. Camera.prototype.detachControl = function (element) {
  10194. };
  10195. Camera.prototype._update = function () {
  10196. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10197. this._updateRigCameras();
  10198. }
  10199. this._checkInputs();
  10200. };
  10201. Camera.prototype._checkInputs = function () {
  10202. };
  10203. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10204. if (insertAt === void 0) { insertAt = null; }
  10205. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10206. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10207. return 0;
  10208. }
  10209. if (insertAt == null || insertAt < 0) {
  10210. this._postProcesses.push(postProcess);
  10211. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10212. return this._postProcesses.length - 1;
  10213. }
  10214. var add = 0;
  10215. var i;
  10216. var start;
  10217. if (this._postProcesses[insertAt]) {
  10218. start = this._postProcesses.length - 1;
  10219. for (i = start; i >= insertAt + 1; --i) {
  10220. this._postProcesses[i + 1] = this._postProcesses[i];
  10221. }
  10222. add = 1;
  10223. }
  10224. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10225. if (this._postProcessesTakenIndices[i] < insertAt) {
  10226. continue;
  10227. }
  10228. start = this._postProcessesTakenIndices.length - 1;
  10229. for (var j = start; j >= i; --j) {
  10230. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10231. }
  10232. this._postProcessesTakenIndices[i] = insertAt;
  10233. break;
  10234. }
  10235. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10236. this._postProcessesTakenIndices.push(insertAt);
  10237. }
  10238. var result = insertAt + add;
  10239. this._postProcesses[result] = postProcess;
  10240. return result;
  10241. };
  10242. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10243. if (atIndices === void 0) { atIndices = null; }
  10244. var result = [];
  10245. var i;
  10246. var index;
  10247. if (!atIndices) {
  10248. var length = this._postProcesses.length;
  10249. for (i = 0; i < length; i++) {
  10250. if (this._postProcesses[i] !== postProcess) {
  10251. continue;
  10252. }
  10253. delete this._postProcesses[i];
  10254. index = this._postProcessesTakenIndices.indexOf(i);
  10255. this._postProcessesTakenIndices.splice(index, 1);
  10256. }
  10257. }
  10258. else {
  10259. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10260. for (i = 0; i < atIndices.length; i++) {
  10261. var foundPostProcess = this._postProcesses[atIndices[i]];
  10262. if (foundPostProcess !== postProcess) {
  10263. result.push(i);
  10264. continue;
  10265. }
  10266. delete this._postProcesses[atIndices[i]];
  10267. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10268. this._postProcessesTakenIndices.splice(index, 1);
  10269. }
  10270. }
  10271. return result;
  10272. };
  10273. Camera.prototype.getWorldMatrix = function () {
  10274. if (!this._worldMatrix) {
  10275. this._worldMatrix = BABYLON.Matrix.Identity();
  10276. }
  10277. var viewMatrix = this.getViewMatrix();
  10278. viewMatrix.invertToRef(this._worldMatrix);
  10279. return this._worldMatrix;
  10280. };
  10281. Camera.prototype._getViewMatrix = function () {
  10282. return BABYLON.Matrix.Identity();
  10283. };
  10284. Camera.prototype.getViewMatrix = function (force) {
  10285. this._computedViewMatrix = this._computeViewMatrix(force);
  10286. if (!force && this._isSynchronizedViewMatrix()) {
  10287. return this._computedViewMatrix;
  10288. }
  10289. if (!this.parent || !this.parent.getWorldMatrix) {
  10290. this._globalPosition.copyFrom(this.position);
  10291. }
  10292. else {
  10293. if (!this._worldMatrix) {
  10294. this._worldMatrix = BABYLON.Matrix.Identity();
  10295. }
  10296. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10297. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10298. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10299. this._computedViewMatrix.invert();
  10300. this._markSyncedWithParent();
  10301. }
  10302. this._currentRenderId = this.getScene().getRenderId();
  10303. return this._computedViewMatrix;
  10304. };
  10305. Camera.prototype._computeViewMatrix = function (force) {
  10306. if (!force && this._isSynchronizedViewMatrix()) {
  10307. return this._computedViewMatrix;
  10308. }
  10309. this._computedViewMatrix = this._getViewMatrix();
  10310. this._currentRenderId = this.getScene().getRenderId();
  10311. return this._computedViewMatrix;
  10312. };
  10313. Camera.prototype.getProjectionMatrix = function (force) {
  10314. if (!force && this._isSynchronizedProjectionMatrix()) {
  10315. return this._projectionMatrix;
  10316. }
  10317. var engine = this.getEngine();
  10318. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10319. if (this.minZ <= 0) {
  10320. this.minZ = 0.1;
  10321. }
  10322. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10323. return this._projectionMatrix;
  10324. }
  10325. var halfWidth = engine.getRenderWidth() / 2.0;
  10326. var halfHeight = engine.getRenderHeight() / 2.0;
  10327. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10328. return this._projectionMatrix;
  10329. };
  10330. Camera.prototype.dispose = function () {
  10331. // Animations
  10332. this.getScene().stopAnimation(this);
  10333. // Remove from scene
  10334. this.getScene().removeCamera(this);
  10335. while (this._rigCameras.length > 0) {
  10336. this._rigCameras.pop().dispose();
  10337. }
  10338. // Postprocesses
  10339. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10340. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10341. }
  10342. };
  10343. // ---- Camera rigs section ----
  10344. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10345. while (this._rigCameras.length > 0) {
  10346. this._rigCameras.pop().dispose();
  10347. }
  10348. this.cameraRigMode = mode;
  10349. this._cameraRigParams = {};
  10350. switch (this.cameraRigMode) {
  10351. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10352. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10353. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10354. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10355. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10356. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10357. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10358. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10359. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10360. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10361. break;
  10362. }
  10363. var postProcesses = new Array();
  10364. switch (this.cameraRigMode) {
  10365. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10366. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10367. this._rigCameras[0].isIntermediate = true;
  10368. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10369. postProcesses[1].onApply = function (effect) {
  10370. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10371. };
  10372. break;
  10373. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10374. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10375. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10376. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10377. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10378. var secondCamIndex = 1 - firstCamIndex;
  10379. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10380. this._rigCameras[firstCamIndex].isIntermediate = true;
  10381. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10382. break;
  10383. case Camera.RIG_MODE_VR:
  10384. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10385. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10386. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10387. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10388. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10389. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10390. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10391. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10392. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10393. if (metrics.compensateDistortion) {
  10394. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10395. }
  10396. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10397. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10398. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10399. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10400. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10401. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10402. if (metrics.compensateDistortion) {
  10403. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10404. }
  10405. break;
  10406. }
  10407. this._update();
  10408. };
  10409. Camera.prototype._getVRProjectionMatrix = function () {
  10410. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10411. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10412. return this._projectionMatrix;
  10413. };
  10414. Camera.prototype.setCameraRigParameter = function (name, value) {
  10415. this._cameraRigParams[name] = value;
  10416. //provisionnally:
  10417. if (name === "interaxialDistance") {
  10418. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10419. }
  10420. };
  10421. /**
  10422. * May needs to be overridden by children so sub has required properties to be copied
  10423. */
  10424. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10425. return null;
  10426. };
  10427. /**
  10428. * May needs to be overridden by children
  10429. */
  10430. Camera.prototype._updateRigCameras = function () {
  10431. for (var i = 0; i < this._rigCameras.length; i++) {
  10432. this._rigCameras[i].minZ = this.minZ;
  10433. this._rigCameras[i].maxZ = this.maxZ;
  10434. this._rigCameras[i].fov = this.fov;
  10435. }
  10436. // only update viewport when ANAGLYPH
  10437. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10438. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10439. }
  10440. };
  10441. Camera.prototype.serialize = function () {
  10442. var serializationObject = {};
  10443. serializationObject.name = this.name;
  10444. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10445. serializationObject.id = this.id;
  10446. serializationObject.position = this.position.asArray();
  10447. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10448. // Parent
  10449. if (this.parent) {
  10450. serializationObject.parentId = this.parent.id;
  10451. }
  10452. serializationObject.fov = this.fov;
  10453. serializationObject.minZ = this.minZ;
  10454. serializationObject.maxZ = this.maxZ;
  10455. serializationObject.inertia = this.inertia;
  10456. // Animations
  10457. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10458. serializationObject.ranges = this.serializeAnimationRanges();
  10459. // Layer mask
  10460. serializationObject.layerMask = this.layerMask;
  10461. return serializationObject;
  10462. };
  10463. Camera.Parse = function (parsedCamera, scene) {
  10464. var camera;
  10465. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10466. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10467. var interaxial_distance;
  10468. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10469. var alpha = parsedCamera.alpha;
  10470. var beta = parsedCamera.beta;
  10471. var radius = parsedCamera.radius;
  10472. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10473. interaxial_distance = parsedCamera.interaxial_distance;
  10474. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10475. }
  10476. else {
  10477. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10478. }
  10479. }
  10480. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10481. interaxial_distance = parsedCamera.interaxial_distance;
  10482. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10483. }
  10484. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10485. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10486. }
  10487. else if (parsedCamera.type === "FollowCamera") {
  10488. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10489. camera.heightOffset = parsedCamera.heightOffset;
  10490. camera.radius = parsedCamera.radius;
  10491. camera.rotationOffset = parsedCamera.rotationOffset;
  10492. if (lockedTargetMesh)
  10493. camera.target = lockedTargetMesh;
  10494. }
  10495. else if (parsedCamera.type === "GamepadCamera") {
  10496. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10497. }
  10498. else if (parsedCamera.type === "TouchCamera") {
  10499. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10500. }
  10501. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10502. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10503. }
  10504. else if (parsedCamera.type === "WebVRFreeCamera") {
  10505. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10506. }
  10507. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10508. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10509. }
  10510. else if (parsedCamera.type === "FreeCamera") {
  10511. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  10512. }
  10513. else {
  10514. // Touch Camera is the default value
  10515. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10516. }
  10517. // apply 3d rig, when found
  10518. if (parsedCamera.cameraRigMode) {
  10519. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10520. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10521. }
  10522. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10523. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10524. camera.lockedTarget = lockedTargetMesh;
  10525. }
  10526. camera.id = parsedCamera.id;
  10527. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10528. // Parent
  10529. if (parsedCamera.parentId) {
  10530. camera._waitingParentId = parsedCamera.parentId;
  10531. }
  10532. // Target
  10533. if (parsedCamera.target) {
  10534. if (camera.setTarget) {
  10535. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10536. }
  10537. else {
  10538. //For ArcRotate
  10539. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10540. }
  10541. }
  10542. else {
  10543. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10544. }
  10545. camera.fov = parsedCamera.fov;
  10546. camera.minZ = parsedCamera.minZ;
  10547. camera.maxZ = parsedCamera.maxZ;
  10548. camera.speed = parsedCamera.speed;
  10549. camera.inertia = parsedCamera.inertia;
  10550. camera.checkCollisions = parsedCamera.checkCollisions;
  10551. camera.applyGravity = parsedCamera.applyGravity;
  10552. if (parsedCamera.ellipsoid) {
  10553. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10554. }
  10555. // Animations
  10556. if (parsedCamera.animations) {
  10557. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10558. var parsedAnimation = parsedCamera.animations[animationIndex];
  10559. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10560. }
  10561. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10562. }
  10563. if (parsedCamera.autoAnimate) {
  10564. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10565. }
  10566. // Layer Mask
  10567. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10568. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10569. }
  10570. else {
  10571. camera.layerMask = 0x0FFFFFFF;
  10572. }
  10573. return camera;
  10574. };
  10575. // Statics
  10576. Camera._PERSPECTIVE_CAMERA = 0;
  10577. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10578. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10579. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10580. Camera._RIG_MODE_NONE = 0;
  10581. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10582. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10583. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10584. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10585. Camera._RIG_MODE_VR = 20;
  10586. return Camera;
  10587. })(BABYLON.Node);
  10588. BABYLON.Camera = Camera;
  10589. })(BABYLON || (BABYLON = {}));
  10590. var BABYLON;
  10591. (function (BABYLON) {
  10592. var TargetCamera = (function (_super) {
  10593. __extends(TargetCamera, _super);
  10594. function TargetCamera(name, position, scene) {
  10595. _super.call(this, name, position, scene);
  10596. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10597. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10598. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10599. this.speed = 2.0;
  10600. this.noRotationConstraint = false;
  10601. this.lockedTarget = null;
  10602. this._currentTarget = BABYLON.Vector3.Zero();
  10603. this._viewMatrix = BABYLON.Matrix.Zero();
  10604. this._camMatrix = BABYLON.Matrix.Zero();
  10605. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10606. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10607. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10608. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10609. this._lookAtTemp = BABYLON.Matrix.Zero();
  10610. this._tempMatrix = BABYLON.Matrix.Zero();
  10611. }
  10612. TargetCamera.prototype.getFrontPosition = function (distance) {
  10613. var direction = this.getTarget().subtract(this.position);
  10614. direction.normalize();
  10615. direction.scaleInPlace(distance);
  10616. return this.globalPosition.add(direction);
  10617. };
  10618. TargetCamera.prototype._getLockedTargetPosition = function () {
  10619. if (!this.lockedTarget) {
  10620. return null;
  10621. }
  10622. return this.lockedTarget.position || this.lockedTarget;
  10623. };
  10624. // Cache
  10625. TargetCamera.prototype._initCache = function () {
  10626. _super.prototype._initCache.call(this);
  10627. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10628. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10629. };
  10630. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10631. if (!ignoreParentClass) {
  10632. _super.prototype._updateCache.call(this);
  10633. }
  10634. var lockedTargetPosition = this._getLockedTargetPosition();
  10635. if (!lockedTargetPosition) {
  10636. this._cache.lockedTarget = null;
  10637. }
  10638. else {
  10639. if (!this._cache.lockedTarget) {
  10640. this._cache.lockedTarget = lockedTargetPosition.clone();
  10641. }
  10642. else {
  10643. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10644. }
  10645. }
  10646. this._cache.rotation.copyFrom(this.rotation);
  10647. };
  10648. // Synchronized
  10649. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10650. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10651. return false;
  10652. }
  10653. var lockedTargetPosition = this._getLockedTargetPosition();
  10654. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10655. && this._cache.rotation.equals(this.rotation);
  10656. };
  10657. // Methods
  10658. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10659. var engine = this.getEngine();
  10660. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10661. };
  10662. // Target
  10663. TargetCamera.prototype.setTarget = function (target) {
  10664. this.upVector.normalize();
  10665. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10666. this._camMatrix.invert();
  10667. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10668. var vDir = target.subtract(this.position);
  10669. if (vDir.x >= 0.0) {
  10670. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10671. }
  10672. else {
  10673. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10674. }
  10675. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10676. if (isNaN(this.rotation.x)) {
  10677. this.rotation.x = 0;
  10678. }
  10679. if (isNaN(this.rotation.y)) {
  10680. this.rotation.y = 0;
  10681. }
  10682. if (isNaN(this.rotation.z)) {
  10683. this.rotation.z = 0;
  10684. }
  10685. };
  10686. TargetCamera.prototype.getTarget = function () {
  10687. return this._currentTarget;
  10688. };
  10689. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10690. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10691. };
  10692. TargetCamera.prototype._updatePosition = function () {
  10693. this.position.addInPlace(this.cameraDirection);
  10694. };
  10695. TargetCamera.prototype._checkInputs = function () {
  10696. var needToMove = this._decideIfNeedsToMove();
  10697. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10698. // Move
  10699. if (needToMove) {
  10700. this._updatePosition();
  10701. }
  10702. // Rotate
  10703. if (needToRotate) {
  10704. this.rotation.x += this.cameraRotation.x;
  10705. this.rotation.y += this.cameraRotation.y;
  10706. if (!this.noRotationConstraint) {
  10707. var limit = (Math.PI / 2) * 0.95;
  10708. if (this.rotation.x > limit)
  10709. this.rotation.x = limit;
  10710. if (this.rotation.x < -limit)
  10711. this.rotation.x = -limit;
  10712. }
  10713. }
  10714. // Inertia
  10715. if (needToMove) {
  10716. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10717. this.cameraDirection.x = 0;
  10718. }
  10719. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10720. this.cameraDirection.y = 0;
  10721. }
  10722. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10723. this.cameraDirection.z = 0;
  10724. }
  10725. this.cameraDirection.scaleInPlace(this.inertia);
  10726. }
  10727. if (needToRotate) {
  10728. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10729. this.cameraRotation.x = 0;
  10730. }
  10731. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10732. this.cameraRotation.y = 0;
  10733. }
  10734. this.cameraRotation.scaleInPlace(this.inertia);
  10735. }
  10736. _super.prototype._checkInputs.call(this);
  10737. };
  10738. TargetCamera.prototype._getViewMatrix = function () {
  10739. if (!this.lockedTarget) {
  10740. // Compute
  10741. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10742. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10743. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10744. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10745. this._lookAtTemp.invert();
  10746. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10747. }
  10748. else {
  10749. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10750. }
  10751. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10752. // Computing target and final matrix
  10753. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10754. }
  10755. else {
  10756. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10757. }
  10758. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10759. return this._viewMatrix;
  10760. };
  10761. TargetCamera.prototype._getVRViewMatrix = function () {
  10762. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10763. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10764. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10765. // Computing target and final matrix
  10766. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10767. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10768. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10769. return this._viewMatrix;
  10770. };
  10771. /**
  10772. * @override
  10773. * Override Camera.createRigCamera
  10774. */
  10775. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10776. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10777. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10778. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10779. rigCamera._cameraRigParams = {};
  10780. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10781. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10782. }
  10783. return rigCamera;
  10784. }
  10785. return null;
  10786. };
  10787. /**
  10788. * @override
  10789. * Override Camera._updateRigCameras
  10790. */
  10791. TargetCamera.prototype._updateRigCameras = function () {
  10792. switch (this.cameraRigMode) {
  10793. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10794. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10795. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10796. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10797. case BABYLON.Camera.RIG_MODE_VR:
  10798. var camLeft = this._rigCameras[0];
  10799. var camRight = this._rigCameras[1];
  10800. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10801. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10802. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10803. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10804. camLeft.position.copyFrom(this.position);
  10805. camRight.position.copyFrom(this.position);
  10806. }
  10807. else {
  10808. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10809. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10810. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10811. camLeft.setTarget(this.getTarget());
  10812. camRight.setTarget(this.getTarget());
  10813. }
  10814. break;
  10815. }
  10816. _super.prototype._updateRigCameras.call(this);
  10817. };
  10818. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10819. if (!this._rigCamTransformMatrix) {
  10820. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10821. }
  10822. var target = this.getTarget();
  10823. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10824. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10825. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10826. };
  10827. TargetCamera.prototype.serialize = function () {
  10828. var serializationObject = _super.prototype.serialize.call(this);
  10829. serializationObject.speed = this.speed;
  10830. if (this.rotation) {
  10831. serializationObject.rotation = this.rotation.asArray();
  10832. }
  10833. if (this.lockedTarget && this.lockedTarget.id) {
  10834. serializationObject.lockedTargetId = this.lockedTarget.id;
  10835. }
  10836. return serializationObject;
  10837. };
  10838. return TargetCamera;
  10839. })(BABYLON.Camera);
  10840. BABYLON.TargetCamera = TargetCamera;
  10841. })(BABYLON || (BABYLON = {}));
  10842. var BABYLON;
  10843. (function (BABYLON) {
  10844. var FreeCamera = (function (_super) {
  10845. __extends(FreeCamera, _super);
  10846. function FreeCamera(name, position, scene) {
  10847. var _this = this;
  10848. _super.call(this, name, position, scene);
  10849. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10850. this.keysUp = [38];
  10851. this.keysDown = [40];
  10852. this.keysLeft = [37];
  10853. this.keysRight = [39];
  10854. this.checkCollisions = false;
  10855. this.applyGravity = false;
  10856. this.angularSensibility = 2000.0;
  10857. this._keys = [];
  10858. this._collider = new BABYLON.Collider();
  10859. this._needMoveForGravity = false;
  10860. this._oldPosition = BABYLON.Vector3.Zero();
  10861. this._diffPosition = BABYLON.Vector3.Zero();
  10862. this._newPosition = BABYLON.Vector3.Zero();
  10863. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10864. if (collidedMesh === void 0) { collidedMesh = null; }
  10865. //TODO move this to the collision coordinator!
  10866. if (_this.getScene().workerCollisions)
  10867. newPosition.multiplyInPlace(_this._collider.radius);
  10868. var updatePosition = function (newPos) {
  10869. _this._newPosition.copyFrom(newPos);
  10870. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10871. var oldPosition = _this.position.clone();
  10872. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10873. _this.position.addInPlace(_this._diffPosition);
  10874. if (_this.onCollide && collidedMesh) {
  10875. _this.onCollide(collidedMesh);
  10876. }
  10877. }
  10878. };
  10879. updatePosition(newPosition);
  10880. };
  10881. }
  10882. FreeCamera.prototype._onLostFocus = function (e) {
  10883. this._keys = [];
  10884. };
  10885. // Controls
  10886. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10887. var _this = this;
  10888. var previousPosition;
  10889. var engine = this.getEngine();
  10890. if (this._attachedElement) {
  10891. return;
  10892. }
  10893. this._attachedElement = element;
  10894. if (this._onMouseDown === undefined) {
  10895. this._onMouseDown = function (evt) {
  10896. previousPosition = {
  10897. x: evt.clientX,
  10898. y: evt.clientY
  10899. };
  10900. if (!noPreventDefault) {
  10901. evt.preventDefault();
  10902. }
  10903. };
  10904. this._onMouseUp = function (evt) {
  10905. previousPosition = null;
  10906. if (!noPreventDefault) {
  10907. evt.preventDefault();
  10908. }
  10909. };
  10910. this._onMouseOut = function (evt) {
  10911. previousPosition = null;
  10912. _this._keys = [];
  10913. if (!noPreventDefault) {
  10914. evt.preventDefault();
  10915. }
  10916. };
  10917. this._onMouseMove = function (evt) {
  10918. if (!previousPosition && !engine.isPointerLock) {
  10919. return;
  10920. }
  10921. var offsetX;
  10922. var offsetY;
  10923. if (!engine.isPointerLock) {
  10924. offsetX = evt.clientX - previousPosition.x;
  10925. offsetY = evt.clientY - previousPosition.y;
  10926. }
  10927. else {
  10928. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10929. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10930. }
  10931. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10932. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10933. previousPosition = {
  10934. x: evt.clientX,
  10935. y: evt.clientY
  10936. };
  10937. if (!noPreventDefault) {
  10938. evt.preventDefault();
  10939. }
  10940. };
  10941. this._onKeyDown = function (evt) {
  10942. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10943. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10944. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10945. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10946. var index = _this._keys.indexOf(evt.keyCode);
  10947. if (index === -1) {
  10948. _this._keys.push(evt.keyCode);
  10949. }
  10950. if (!noPreventDefault) {
  10951. evt.preventDefault();
  10952. }
  10953. }
  10954. };
  10955. this._onKeyUp = function (evt) {
  10956. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10957. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10958. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10959. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10960. var index = _this._keys.indexOf(evt.keyCode);
  10961. if (index >= 0) {
  10962. _this._keys.splice(index, 1);
  10963. }
  10964. if (!noPreventDefault) {
  10965. evt.preventDefault();
  10966. }
  10967. }
  10968. };
  10969. this._reset = function () {
  10970. _this._keys = [];
  10971. previousPosition = null;
  10972. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10973. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10974. };
  10975. }
  10976. element.addEventListener("mousedown", this._onMouseDown, false);
  10977. element.addEventListener("mouseup", this._onMouseUp, false);
  10978. element.addEventListener("mouseout", this._onMouseOut, false);
  10979. element.addEventListener("mousemove", this._onMouseMove, false);
  10980. BABYLON.Tools.RegisterTopRootEvents([
  10981. { name: "keydown", handler: this._onKeyDown },
  10982. { name: "keyup", handler: this._onKeyUp },
  10983. { name: "blur", handler: this._onLostFocus }
  10984. ]);
  10985. };
  10986. FreeCamera.prototype.detachControl = function (element) {
  10987. if (this._attachedElement !== element) {
  10988. return;
  10989. }
  10990. element.removeEventListener("mousedown", this._onMouseDown);
  10991. element.removeEventListener("mouseup", this._onMouseUp);
  10992. element.removeEventListener("mouseout", this._onMouseOut);
  10993. element.removeEventListener("mousemove", this._onMouseMove);
  10994. BABYLON.Tools.UnregisterTopRootEvents([
  10995. { name: "keydown", handler: this._onKeyDown },
  10996. { name: "keyup", handler: this._onKeyUp },
  10997. { name: "blur", handler: this._onLostFocus }
  10998. ]);
  10999. this._attachedElement = null;
  11000. if (this._reset) {
  11001. this._reset();
  11002. }
  11003. };
  11004. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11005. var globalPosition;
  11006. if (this.parent) {
  11007. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11008. }
  11009. else {
  11010. globalPosition = this.position;
  11011. }
  11012. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11013. this._collider.radius = this.ellipsoid;
  11014. //no need for clone, as long as gravity is not on.
  11015. var actualVelocity = velocity;
  11016. //add gravity to the velocity to prevent the dual-collision checking
  11017. if (this.applyGravity) {
  11018. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11019. actualVelocity = velocity.add(this.getScene().gravity);
  11020. }
  11021. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11022. };
  11023. FreeCamera.prototype._checkInputs = function () {
  11024. if (!this._localDirection) {
  11025. this._localDirection = BABYLON.Vector3.Zero();
  11026. this._transformedDirection = BABYLON.Vector3.Zero();
  11027. }
  11028. // Keyboard
  11029. for (var index = 0; index < this._keys.length; index++) {
  11030. var keyCode = this._keys[index];
  11031. var speed = this._computeLocalCameraSpeed();
  11032. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11033. this._localDirection.copyFromFloats(-speed, 0, 0);
  11034. }
  11035. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11036. this._localDirection.copyFromFloats(0, 0, speed);
  11037. }
  11038. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11039. this._localDirection.copyFromFloats(speed, 0, 0);
  11040. }
  11041. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11042. this._localDirection.copyFromFloats(0, 0, -speed);
  11043. }
  11044. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11045. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11046. this.cameraDirection.addInPlace(this._transformedDirection);
  11047. }
  11048. _super.prototype._checkInputs.call(this);
  11049. };
  11050. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11051. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11052. };
  11053. FreeCamera.prototype._updatePosition = function () {
  11054. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11055. this._collideWithWorld(this.cameraDirection);
  11056. }
  11057. else {
  11058. this.position.addInPlace(this.cameraDirection);
  11059. }
  11060. };
  11061. FreeCamera.prototype.serialize = function () {
  11062. var serializationObject = _super.prototype.serialize.call(this);
  11063. serializationObject.checkCollisions = this.checkCollisions;
  11064. serializationObject.applyGravity = this.applyGravity;
  11065. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11066. return serializationObject;
  11067. };
  11068. return FreeCamera;
  11069. })(BABYLON.TargetCamera);
  11070. BABYLON.FreeCamera = FreeCamera;
  11071. })(BABYLON || (BABYLON = {}));
  11072. var BABYLON;
  11073. (function (BABYLON) {
  11074. var FollowCamera = (function (_super) {
  11075. __extends(FollowCamera, _super);
  11076. function FollowCamera(name, position, scene) {
  11077. _super.call(this, name, position, scene);
  11078. this.radius = 12;
  11079. this.rotationOffset = 0;
  11080. this.heightOffset = 4;
  11081. this.cameraAcceleration = 0.05;
  11082. this.maxCameraSpeed = 20;
  11083. }
  11084. FollowCamera.prototype.getRadians = function (degrees) {
  11085. return degrees * Math.PI / 180;
  11086. };
  11087. FollowCamera.prototype.follow = function (cameraTarget) {
  11088. if (!cameraTarget)
  11089. return;
  11090. var yRotation;
  11091. if (cameraTarget.rotationQuaternion) {
  11092. var rotMatrix = new BABYLON.Matrix();
  11093. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11094. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11095. }
  11096. else {
  11097. yRotation = cameraTarget.rotation.y;
  11098. }
  11099. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11100. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11101. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11102. var dx = targetX - this.position.x;
  11103. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11104. var dz = (targetZ) - this.position.z;
  11105. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11106. var vy = dy * this.cameraAcceleration;
  11107. var vz = dz * this.cameraAcceleration * 2;
  11108. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11109. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11110. }
  11111. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11112. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11113. }
  11114. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11115. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11116. }
  11117. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11118. this.setTarget(cameraTarget.position);
  11119. };
  11120. FollowCamera.prototype._checkInputs = function () {
  11121. _super.prototype._checkInputs.call(this);
  11122. this.follow(this.target);
  11123. };
  11124. FollowCamera.prototype.serialize = function () {
  11125. var serializationObject = _super.prototype.serialize.call(this);
  11126. serializationObject.radius = this.radius;
  11127. serializationObject.heightOffset = this.heightOffset;
  11128. serializationObject.rotationOffset = this.rotationOffset;
  11129. return serializationObject;
  11130. };
  11131. return FollowCamera;
  11132. })(BABYLON.TargetCamera);
  11133. BABYLON.FollowCamera = FollowCamera;
  11134. var ArcFollowCamera = (function (_super) {
  11135. __extends(ArcFollowCamera, _super);
  11136. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11137. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11138. this.alpha = alpha;
  11139. this.beta = beta;
  11140. this.radius = radius;
  11141. this.target = target;
  11142. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11143. this.follow();
  11144. }
  11145. ArcFollowCamera.prototype.follow = function () {
  11146. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11147. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11148. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11149. this.position = this.target.position.add(this._cartesianCoordinates);
  11150. this.setTarget(this.target.position);
  11151. };
  11152. ArcFollowCamera.prototype._checkInputs = function () {
  11153. _super.prototype._checkInputs.call(this);
  11154. this.follow();
  11155. };
  11156. ArcFollowCamera.prototype.serialize = function () {
  11157. var serializationObject = _super.prototype.serialize.call(this);
  11158. serializationObject.radius = this.radius;
  11159. return serializationObject;
  11160. };
  11161. return ArcFollowCamera;
  11162. })(BABYLON.TargetCamera);
  11163. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11164. })(BABYLON || (BABYLON = {}));
  11165. var BABYLON;
  11166. (function (BABYLON) {
  11167. // We're mainly based on the logic defined into the FreeCamera code
  11168. var TouchCamera = (function (_super) {
  11169. __extends(TouchCamera, _super);
  11170. function TouchCamera(name, position, scene) {
  11171. _super.call(this, name, position, scene);
  11172. this._offsetX = null;
  11173. this._offsetY = null;
  11174. this._pointerCount = 0;
  11175. this._pointerPressed = [];
  11176. this.touchAngularSensibility = 200000.0;
  11177. this.touchMoveSensibility = 500.0;
  11178. }
  11179. TouchCamera.prototype._onLostFocus = function (e) {
  11180. this._offsetX = null;
  11181. this._offsetY = null;
  11182. _super.prototype._onLostFocus.call(this, e);
  11183. };
  11184. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11185. var _this = this;
  11186. var previousPosition;
  11187. if (this._attachedCanvas) {
  11188. return;
  11189. }
  11190. if (this._onPointerDown === undefined) {
  11191. this._onPointerDown = function (evt) {
  11192. if (evt.pointerType === "mouse") {
  11193. return;
  11194. }
  11195. if (!noPreventDefault) {
  11196. evt.preventDefault();
  11197. }
  11198. _this._pointerPressed.push(evt.pointerId);
  11199. if (_this._pointerPressed.length !== 1) {
  11200. return;
  11201. }
  11202. previousPosition = {
  11203. x: evt.clientX,
  11204. y: evt.clientY
  11205. };
  11206. };
  11207. this._onPointerUp = function (evt) {
  11208. if (evt.pointerType === "mouse") {
  11209. return;
  11210. }
  11211. if (!noPreventDefault) {
  11212. evt.preventDefault();
  11213. }
  11214. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11215. if (index === -1) {
  11216. return;
  11217. }
  11218. _this._pointerPressed.splice(index, 1);
  11219. if (index != 0) {
  11220. return;
  11221. }
  11222. previousPosition = null;
  11223. _this._offsetX = null;
  11224. _this._offsetY = null;
  11225. };
  11226. this._onPointerMove = function (evt) {
  11227. if (evt.pointerType === "mouse") {
  11228. return;
  11229. }
  11230. if (!noPreventDefault) {
  11231. evt.preventDefault();
  11232. }
  11233. if (!previousPosition) {
  11234. return;
  11235. }
  11236. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11237. if (index != 0) {
  11238. return;
  11239. }
  11240. _this._offsetX = evt.clientX - previousPosition.x;
  11241. _this._offsetY = -(evt.clientY - previousPosition.y);
  11242. };
  11243. }
  11244. canvas.addEventListener("pointerdown", this._onPointerDown);
  11245. canvas.addEventListener("pointerup", this._onPointerUp);
  11246. canvas.addEventListener("pointerout", this._onPointerUp);
  11247. canvas.addEventListener("pointermove", this._onPointerMove);
  11248. _super.prototype.attachControl.call(this, canvas);
  11249. };
  11250. TouchCamera.prototype.detachControl = function (canvas) {
  11251. if (this._attachedCanvas !== canvas) {
  11252. return;
  11253. }
  11254. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11255. canvas.removeEventListener("pointerup", this._onPointerUp);
  11256. canvas.removeEventListener("pointerout", this._onPointerUp);
  11257. canvas.removeEventListener("pointermove", this._onPointerMove);
  11258. _super.prototype.detachControl.call(this, canvas);
  11259. };
  11260. TouchCamera.prototype._checkInputs = function () {
  11261. if (this._offsetX) {
  11262. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11263. if (this._pointerPressed.length > 1) {
  11264. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11265. }
  11266. else {
  11267. var speed = this._computeLocalCameraSpeed();
  11268. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11269. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11270. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11271. }
  11272. }
  11273. _super.prototype._checkInputs.call(this);
  11274. };
  11275. return TouchCamera;
  11276. })(BABYLON.FreeCamera);
  11277. BABYLON.TouchCamera = TouchCamera;
  11278. })(BABYLON || (BABYLON = {}));
  11279. var BABYLON;
  11280. (function (BABYLON) {
  11281. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11282. var ArcRotateCamera = (function (_super) {
  11283. __extends(ArcRotateCamera, _super);
  11284. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11285. var _this = this;
  11286. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11287. this.alpha = alpha;
  11288. this.beta = beta;
  11289. this.radius = radius;
  11290. this.target = target;
  11291. this.inertialAlphaOffset = 0;
  11292. this.inertialBetaOffset = 0;
  11293. this.inertialRadiusOffset = 0;
  11294. this.lowerAlphaLimit = null;
  11295. this.upperAlphaLimit = null;
  11296. this.lowerBetaLimit = 0.01;
  11297. this.upperBetaLimit = Math.PI;
  11298. this.lowerRadiusLimit = null;
  11299. this.upperRadiusLimit = null;
  11300. this.angularSensibilityX = 1000.0;
  11301. this.angularSensibilityY = 1000.0;
  11302. this.wheelPrecision = 3.0;
  11303. this.pinchPrecision = 2.0;
  11304. this.panningSensibility = 50.0;
  11305. this.inertialPanningX = 0;
  11306. this.inertialPanningY = 0;
  11307. this.keysUp = [38];
  11308. this.keysDown = [40];
  11309. this.keysLeft = [37];
  11310. this.keysRight = [39];
  11311. this.zoomOnFactor = 1;
  11312. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11313. this.pinchInwards = true;
  11314. this.allowUpsideDown = true;
  11315. this._keys = [];
  11316. this._viewMatrix = new BABYLON.Matrix();
  11317. // Panning
  11318. this.panningAxis = new BABYLON.Vector3(1, 0, 1);
  11319. this._isRightClick = false;
  11320. this._isCtrlPushed = false;
  11321. this.checkCollisions = false;
  11322. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11323. this._collider = new BABYLON.Collider();
  11324. this._previousPosition = BABYLON.Vector3.Zero();
  11325. this._collisionVelocity = BABYLON.Vector3.Zero();
  11326. this._newPosition = BABYLON.Vector3.Zero();
  11327. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11328. if (collidedMesh === void 0) { collidedMesh = null; }
  11329. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11330. newPosition.multiplyInPlace(_this._collider.radius);
  11331. }
  11332. if (!collidedMesh) {
  11333. _this._previousPosition.copyFrom(_this.position);
  11334. }
  11335. else {
  11336. _this.setPosition(newPosition);
  11337. if (_this.onCollide) {
  11338. _this.onCollide(collidedMesh);
  11339. }
  11340. }
  11341. // Recompute because of constraints
  11342. var cosa = Math.cos(_this.alpha);
  11343. var sina = Math.sin(_this.alpha);
  11344. var cosb = Math.cos(_this.beta);
  11345. var sinb = Math.sin(_this.beta);
  11346. var target = _this._getTargetPosition();
  11347. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11348. _this.position.copyFrom(_this._newPosition);
  11349. var up = _this.upVector;
  11350. if (_this.allowUpsideDown && _this.beta < 0) {
  11351. up = up.clone();
  11352. up = up.negate();
  11353. }
  11354. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11355. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11356. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11357. _this._collisionTriggered = false;
  11358. };
  11359. if (!this.target) {
  11360. this.target = BABYLON.Vector3.Zero();
  11361. }
  11362. this.getViewMatrix();
  11363. }
  11364. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11365. //deprecated angularSensibility support
  11366. get: function () {
  11367. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11368. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11369. },
  11370. //deprecated angularSensibility support
  11371. set: function (value) {
  11372. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11373. this.angularSensibilityX = value;
  11374. this.angularSensibilityY = value;
  11375. },
  11376. enumerable: true,
  11377. configurable: true
  11378. });
  11379. ArcRotateCamera.prototype._getTargetPosition = function () {
  11380. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11381. };
  11382. // Cache
  11383. ArcRotateCamera.prototype._initCache = function () {
  11384. _super.prototype._initCache.call(this);
  11385. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11386. this._cache.alpha = undefined;
  11387. this._cache.beta = undefined;
  11388. this._cache.radius = undefined;
  11389. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11390. };
  11391. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11392. if (!ignoreParentClass) {
  11393. _super.prototype._updateCache.call(this);
  11394. }
  11395. this._cache.target.copyFrom(this._getTargetPosition());
  11396. this._cache.alpha = this.alpha;
  11397. this._cache.beta = this.beta;
  11398. this._cache.radius = this.radius;
  11399. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11400. };
  11401. // Synchronized
  11402. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11403. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11404. return false;
  11405. return this._cache.target.equals(this._getTargetPosition())
  11406. && this._cache.alpha === this.alpha
  11407. && this._cache.beta === this.beta
  11408. && this._cache.radius === this.radius
  11409. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11410. };
  11411. // Methods
  11412. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11413. var _this = this;
  11414. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11415. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11416. var previousPinchDistance = 0;
  11417. var pointers = new BABYLON.SmartCollection();
  11418. if (this._attachedElement) {
  11419. return;
  11420. }
  11421. this._attachedElement = element;
  11422. var engine = this.getEngine();
  11423. if (this._onPointerDown === undefined) {
  11424. this._onPointerDown = function (evt) {
  11425. // Manage panning with right click
  11426. _this._isRightClick = evt.button === 2;
  11427. // manage pointers
  11428. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11429. cacheSoloPointer = pointers.item(evt.pointerId);
  11430. if (!noPreventDefault) {
  11431. evt.preventDefault();
  11432. }
  11433. };
  11434. this._onPointerUp = function (evt) {
  11435. cacheSoloPointer = null;
  11436. previousPinchDistance = 0;
  11437. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11438. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11439. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11440. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11441. pointers.empty();
  11442. if (!noPreventDefault) {
  11443. evt.preventDefault();
  11444. }
  11445. };
  11446. this._onContextMenu = function (evt) {
  11447. evt.preventDefault();
  11448. };
  11449. this._onPointerMove = function (evt) {
  11450. if (!noPreventDefault) {
  11451. evt.preventDefault();
  11452. }
  11453. switch (pointers.count) {
  11454. case 1:
  11455. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11456. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11457. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11458. }
  11459. else {
  11460. var offsetX = evt.clientX - cacheSoloPointer.x;
  11461. var offsetY = evt.clientY - cacheSoloPointer.y;
  11462. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11463. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11464. }
  11465. cacheSoloPointer.x = evt.clientX;
  11466. cacheSoloPointer.y = evt.clientY;
  11467. break;
  11468. case 2:
  11469. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11470. pointers.item(evt.pointerId).x = evt.clientX;
  11471. pointers.item(evt.pointerId).y = evt.clientY;
  11472. var direction = _this.pinchInwards ? 1 : -1;
  11473. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11474. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11475. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11476. if (previousPinchDistance === 0) {
  11477. previousPinchDistance = pinchSquaredDistance;
  11478. return;
  11479. }
  11480. if (pinchSquaredDistance !== previousPinchDistance) {
  11481. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11482. previousPinchDistance = pinchSquaredDistance;
  11483. }
  11484. break;
  11485. default:
  11486. if (pointers.item(evt.pointerId)) {
  11487. pointers.item(evt.pointerId).x = evt.clientX;
  11488. pointers.item(evt.pointerId).y = evt.clientY;
  11489. }
  11490. }
  11491. };
  11492. this._onMouseMove = function (evt) {
  11493. if (!engine.isPointerLock) {
  11494. return;
  11495. }
  11496. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11497. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11498. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11499. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11500. if (!noPreventDefault) {
  11501. evt.preventDefault();
  11502. }
  11503. };
  11504. this._wheel = function (event) {
  11505. var delta = 0;
  11506. if (event.wheelDelta) {
  11507. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11508. }
  11509. else if (event.detail) {
  11510. delta = -event.detail / _this.wheelPrecision;
  11511. }
  11512. if (delta)
  11513. _this.inertialRadiusOffset += delta;
  11514. if (event.preventDefault) {
  11515. if (!noPreventDefault) {
  11516. event.preventDefault();
  11517. }
  11518. }
  11519. };
  11520. this._onKeyDown = function (evt) {
  11521. _this._isCtrlPushed = evt.ctrlKey;
  11522. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11523. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11524. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11525. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11526. var index = _this._keys.indexOf(evt.keyCode);
  11527. if (index === -1) {
  11528. _this._keys.push(evt.keyCode);
  11529. }
  11530. if (evt.preventDefault) {
  11531. if (!noPreventDefault) {
  11532. evt.preventDefault();
  11533. }
  11534. }
  11535. }
  11536. };
  11537. this._onKeyUp = function (evt) {
  11538. _this._isCtrlPushed = evt.ctrlKey;
  11539. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11540. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11541. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11542. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11543. var index = _this._keys.indexOf(evt.keyCode);
  11544. if (index >= 0) {
  11545. _this._keys.splice(index, 1);
  11546. }
  11547. if (evt.preventDefault) {
  11548. if (!noPreventDefault) {
  11549. evt.preventDefault();
  11550. }
  11551. }
  11552. }
  11553. };
  11554. this._onLostFocus = function () {
  11555. _this._keys = [];
  11556. pointers.empty();
  11557. previousPinchDistance = 0;
  11558. cacheSoloPointer = null;
  11559. };
  11560. this._onGestureStart = function (e) {
  11561. if (window.MSGesture === undefined) {
  11562. return;
  11563. }
  11564. if (!_this._MSGestureHandler) {
  11565. _this._MSGestureHandler = new MSGesture();
  11566. _this._MSGestureHandler.target = element;
  11567. }
  11568. _this._MSGestureHandler.addPointer(e.pointerId);
  11569. };
  11570. this._onGesture = function (e) {
  11571. _this.radius *= e.scale;
  11572. if (e.preventDefault) {
  11573. if (!noPreventDefault) {
  11574. e.stopPropagation();
  11575. e.preventDefault();
  11576. }
  11577. }
  11578. };
  11579. this._reset = function () {
  11580. _this._keys = [];
  11581. _this.inertialAlphaOffset = 0;
  11582. _this.inertialBetaOffset = 0;
  11583. _this.inertialRadiusOffset = 0;
  11584. pointers.empty();
  11585. previousPinchDistance = 0;
  11586. cacheSoloPointer = null;
  11587. };
  11588. }
  11589. if (!useCtrlForPanning) {
  11590. element.addEventListener("contextmenu", this._onContextMenu, false);
  11591. }
  11592. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11593. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11594. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11595. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11596. element.addEventListener("mousemove", this._onMouseMove, false);
  11597. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11598. element.addEventListener("MSGestureChange", this._onGesture, false);
  11599. element.addEventListener('mousewheel', this._wheel, false);
  11600. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11601. BABYLON.Tools.RegisterTopRootEvents([
  11602. { name: "keydown", handler: this._onKeyDown },
  11603. { name: "keyup", handler: this._onKeyUp },
  11604. { name: "blur", handler: this._onLostFocus }
  11605. ]);
  11606. };
  11607. ArcRotateCamera.prototype.detachControl = function (element) {
  11608. if (this._attachedElement !== element) {
  11609. return;
  11610. }
  11611. element.removeEventListener("contextmenu", this._onContextMenu);
  11612. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11613. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11614. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11615. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11616. element.removeEventListener("mousemove", this._onMouseMove);
  11617. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11618. element.removeEventListener("MSGestureChange", this._onGesture);
  11619. element.removeEventListener('mousewheel', this._wheel);
  11620. element.removeEventListener('DOMMouseScroll', this._wheel);
  11621. BABYLON.Tools.UnregisterTopRootEvents([
  11622. { name: "keydown", handler: this._onKeyDown },
  11623. { name: "keyup", handler: this._onKeyUp },
  11624. { name: "blur", handler: this._onLostFocus }
  11625. ]);
  11626. this._MSGestureHandler = null;
  11627. this._attachedElement = null;
  11628. if (this._reset) {
  11629. this._reset();
  11630. }
  11631. };
  11632. ArcRotateCamera.prototype._checkInputs = function () {
  11633. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11634. if (this._collisionTriggered) {
  11635. return;
  11636. }
  11637. // Keyboard
  11638. for (var index = 0; index < this._keys.length; index++) {
  11639. var keyCode = this._keys[index];
  11640. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11641. this.inertialAlphaOffset -= 0.01;
  11642. }
  11643. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11644. this.inertialBetaOffset -= 0.01;
  11645. }
  11646. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11647. this.inertialAlphaOffset += 0.01;
  11648. }
  11649. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11650. this.inertialBetaOffset += 0.01;
  11651. }
  11652. }
  11653. // Inertia
  11654. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11655. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11656. this.beta += this.inertialBetaOffset;
  11657. this.radius -= this.inertialRadiusOffset;
  11658. this.inertialAlphaOffset *= this.inertia;
  11659. this.inertialBetaOffset *= this.inertia;
  11660. this.inertialRadiusOffset *= this.inertia;
  11661. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11662. this.inertialAlphaOffset = 0;
  11663. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11664. this.inertialBetaOffset = 0;
  11665. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11666. this.inertialRadiusOffset = 0;
  11667. }
  11668. // Panning inertia
  11669. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11670. if (!this._localDirection) {
  11671. this._localDirection = BABYLON.Vector3.Zero();
  11672. this._transformedDirection = BABYLON.Vector3.Zero();
  11673. }
  11674. this.inertialPanningX *= this.inertia;
  11675. this.inertialPanningY *= this.inertia;
  11676. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11677. this.inertialPanningX = 0;
  11678. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11679. this.inertialPanningY = 0;
  11680. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11681. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11682. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11683. this._transformedDirection.multiplyInPlace(this.panningAxis);
  11684. this.target.addInPlace(this._transformedDirection);
  11685. }
  11686. // Limits
  11687. this._checkLimits();
  11688. _super.prototype._checkInputs.call(this);
  11689. };
  11690. ArcRotateCamera.prototype._checkLimits = function () {
  11691. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11692. if (this.allowUpsideDown && this.beta > Math.PI) {
  11693. this.beta = this.beta - (2 * Math.PI);
  11694. }
  11695. }
  11696. else {
  11697. if (this.beta < this.lowerBetaLimit) {
  11698. this.beta = this.lowerBetaLimit;
  11699. }
  11700. }
  11701. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11702. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11703. this.beta = this.beta + (2 * Math.PI);
  11704. }
  11705. }
  11706. else {
  11707. if (this.beta > this.upperBetaLimit) {
  11708. this.beta = this.upperBetaLimit;
  11709. }
  11710. }
  11711. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11712. this.alpha = this.lowerAlphaLimit;
  11713. }
  11714. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11715. this.alpha = this.upperAlphaLimit;
  11716. }
  11717. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11718. this.radius = this.lowerRadiusLimit;
  11719. }
  11720. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11721. this.radius = this.upperRadiusLimit;
  11722. }
  11723. };
  11724. ArcRotateCamera.prototype.setPosition = function (position) {
  11725. if (this.position.equals(position)) {
  11726. return;
  11727. }
  11728. var radiusv3 = position.subtract(this._getTargetPosition());
  11729. this.radius = radiusv3.length();
  11730. // Alpha
  11731. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11732. if (radiusv3.z < 0) {
  11733. this.alpha = 2 * Math.PI - this.alpha;
  11734. }
  11735. // Beta
  11736. this.beta = Math.acos(radiusv3.y / this.radius);
  11737. this._checkLimits();
  11738. };
  11739. ArcRotateCamera.prototype.setTarget = function (target) {
  11740. this.target = target;
  11741. };
  11742. ArcRotateCamera.prototype._getViewMatrix = function () {
  11743. // Compute
  11744. var cosa = Math.cos(this.alpha);
  11745. var sina = Math.sin(this.alpha);
  11746. var cosb = Math.cos(this.beta);
  11747. var sinb = Math.sin(this.beta);
  11748. var target = this._getTargetPosition();
  11749. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11750. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11751. this._collider.radius = this.collisionRadius;
  11752. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11753. this._collisionTriggered = true;
  11754. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11755. }
  11756. else {
  11757. this.position.copyFrom(this._newPosition);
  11758. var up = this.upVector;
  11759. if (this.allowUpsideDown && this.beta < 0) {
  11760. up = up.clone();
  11761. up = up.negate();
  11762. }
  11763. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11764. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11765. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11766. }
  11767. return this._viewMatrix;
  11768. };
  11769. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11770. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11771. meshes = meshes || this.getScene().meshes;
  11772. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11773. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11774. this.radius = distance * this.zoomOnFactor;
  11775. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11776. };
  11777. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11778. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11779. var meshesOrMinMaxVector;
  11780. var distance;
  11781. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11782. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11783. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11784. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11785. }
  11786. else {
  11787. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11788. distance = meshesOrMinMaxVectorAndDistance.distance;
  11789. }
  11790. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11791. if (!doNotUpdateMaxZ) {
  11792. this.maxZ = distance * 2;
  11793. }
  11794. };
  11795. /**
  11796. * @override
  11797. * Override Camera.createRigCamera
  11798. */
  11799. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11800. switch (this.cameraRigMode) {
  11801. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11802. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11803. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11804. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11805. case BABYLON.Camera.RIG_MODE_VR:
  11806. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11807. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11808. }
  11809. return null;
  11810. };
  11811. /**
  11812. * @override
  11813. * Override Camera._updateRigCameras
  11814. */
  11815. ArcRotateCamera.prototype._updateRigCameras = function () {
  11816. switch (this.cameraRigMode) {
  11817. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11818. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11819. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11820. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11821. case BABYLON.Camera.RIG_MODE_VR:
  11822. var camLeft = this._rigCameras[0];
  11823. var camRight = this._rigCameras[1];
  11824. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11825. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11826. camLeft.beta = camRight.beta = this.beta;
  11827. camLeft.radius = camRight.radius = this.radius;
  11828. break;
  11829. }
  11830. _super.prototype._updateRigCameras.call(this);
  11831. };
  11832. ArcRotateCamera.prototype.serialize = function () {
  11833. var serializationObject = _super.prototype.serialize.call(this);
  11834. if (this.target instanceof BABYLON.Vector3) {
  11835. serializationObject.target = this.target.asArray();
  11836. }
  11837. if (this.target && this.target.id) {
  11838. serializationObject.lockedTargetId = this.target.id;
  11839. }
  11840. serializationObject.checkCollisions = this.checkCollisions;
  11841. serializationObject.alpha = this.alpha;
  11842. serializationObject.beta = this.beta;
  11843. serializationObject.radius = this.radius;
  11844. return serializationObject;
  11845. };
  11846. return ArcRotateCamera;
  11847. })(BABYLON.TargetCamera);
  11848. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11849. })(BABYLON || (BABYLON = {}));
  11850. var BABYLON;
  11851. (function (BABYLON) {
  11852. var RenderingManager = (function () {
  11853. function RenderingManager(scene) {
  11854. this._renderingGroups = new Array();
  11855. this._scene = scene;
  11856. }
  11857. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11858. if (this._scene._activeParticleSystems.length === 0) {
  11859. return;
  11860. }
  11861. // Particles
  11862. var activeCamera = this._scene.activeCamera;
  11863. var beforeParticlesDate = BABYLON.Tools.Now;
  11864. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11865. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11866. if (particleSystem.renderingGroupId !== index) {
  11867. continue;
  11868. }
  11869. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11870. continue;
  11871. }
  11872. this._clearDepthBuffer();
  11873. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11874. this._scene._activeParticles += particleSystem.render();
  11875. }
  11876. }
  11877. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11878. };
  11879. RenderingManager.prototype._renderSprites = function (index) {
  11880. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11881. return;
  11882. }
  11883. // Sprites
  11884. var activeCamera = this._scene.activeCamera;
  11885. var beforeSpritessDate = BABYLON.Tools.Now;
  11886. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11887. var spriteManager = this._scene.spriteManagers[id];
  11888. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11889. this._clearDepthBuffer();
  11890. spriteManager.render();
  11891. }
  11892. }
  11893. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11894. };
  11895. RenderingManager.prototype._clearDepthBuffer = function () {
  11896. if (this._depthBufferAlreadyCleaned) {
  11897. return;
  11898. }
  11899. this._scene.getEngine().clear(0, false, true);
  11900. this._depthBufferAlreadyCleaned = true;
  11901. };
  11902. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11903. if (this._currentRenderSprites) {
  11904. this._renderSprites(this._currentIndex);
  11905. }
  11906. if (this._currentRenderParticles) {
  11907. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11908. }
  11909. };
  11910. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11911. this._currentActiveMeshes = activeMeshes;
  11912. this._currentRenderParticles = renderParticles;
  11913. this._currentRenderSprites = renderSprites;
  11914. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11915. this._depthBufferAlreadyCleaned = index == 0;
  11916. var renderingGroup = this._renderingGroups[index];
  11917. var needToStepBack = false;
  11918. this._currentIndex = index;
  11919. if (renderingGroup) {
  11920. this._clearDepthBuffer();
  11921. if (!renderingGroup.onBeforeTransparentRendering) {
  11922. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11923. }
  11924. if (!renderingGroup.render(customRenderFunction)) {
  11925. this._renderingGroups.splice(index, 1);
  11926. needToStepBack = true;
  11927. this._renderSpritesAndParticles();
  11928. }
  11929. }
  11930. else {
  11931. this._renderSpritesAndParticles();
  11932. }
  11933. if (needToStepBack) {
  11934. index--;
  11935. }
  11936. }
  11937. };
  11938. RenderingManager.prototype.reset = function () {
  11939. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11940. if (renderingGroup) {
  11941. renderingGroup.prepare();
  11942. }
  11943. });
  11944. };
  11945. RenderingManager.prototype.dispatch = function (subMesh) {
  11946. var mesh = subMesh.getMesh();
  11947. var renderingGroupId = mesh.renderingGroupId || 0;
  11948. if (!this._renderingGroups[renderingGroupId]) {
  11949. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11950. }
  11951. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11952. };
  11953. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11954. return RenderingManager;
  11955. })();
  11956. BABYLON.RenderingManager = RenderingManager;
  11957. })(BABYLON || (BABYLON = {}));
  11958. var BABYLON;
  11959. (function (BABYLON) {
  11960. var RenderingGroup = (function () {
  11961. function RenderingGroup(index, scene) {
  11962. this.index = index;
  11963. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11964. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11965. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11966. this._scene = scene;
  11967. }
  11968. RenderingGroup.prototype.render = function (customRenderFunction) {
  11969. if (customRenderFunction) {
  11970. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11971. return true;
  11972. }
  11973. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11974. if (this.onBeforeTransparentRendering) {
  11975. this.onBeforeTransparentRendering();
  11976. }
  11977. return false;
  11978. }
  11979. var engine = this._scene.getEngine();
  11980. // Opaque
  11981. var subIndex;
  11982. var submesh;
  11983. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11984. submesh = this._opaqueSubMeshes.data[subIndex];
  11985. submesh.render(false);
  11986. }
  11987. // Alpha test
  11988. engine.setAlphaTesting(true);
  11989. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11990. submesh = this._alphaTestSubMeshes.data[subIndex];
  11991. submesh.render(false);
  11992. }
  11993. engine.setAlphaTesting(false);
  11994. if (this.onBeforeTransparentRendering) {
  11995. this.onBeforeTransparentRendering();
  11996. }
  11997. // Transparent
  11998. if (this._transparentSubMeshes.length) {
  11999. // Sorting
  12000. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12001. submesh = this._transparentSubMeshes.data[subIndex];
  12002. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12003. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12004. }
  12005. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12006. sortedArray.sort(function (a, b) {
  12007. // Alpha index first
  12008. if (a._alphaIndex > b._alphaIndex) {
  12009. return 1;
  12010. }
  12011. if (a._alphaIndex < b._alphaIndex) {
  12012. return -1;
  12013. }
  12014. // Then distance to camera
  12015. if (a._distanceToCamera < b._distanceToCamera) {
  12016. return 1;
  12017. }
  12018. if (a._distanceToCamera > b._distanceToCamera) {
  12019. return -1;
  12020. }
  12021. return 0;
  12022. });
  12023. // Rendering
  12024. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12025. submesh = sortedArray[subIndex];
  12026. submesh.render(true);
  12027. }
  12028. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12029. }
  12030. return true;
  12031. };
  12032. RenderingGroup.prototype.prepare = function () {
  12033. this._opaqueSubMeshes.reset();
  12034. this._transparentSubMeshes.reset();
  12035. this._alphaTestSubMeshes.reset();
  12036. };
  12037. RenderingGroup.prototype.dispatch = function (subMesh) {
  12038. var material = subMesh.getMaterial();
  12039. var mesh = subMesh.getMesh();
  12040. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12041. this._transparentSubMeshes.push(subMesh);
  12042. }
  12043. else if (material.needAlphaTesting()) {
  12044. this._alphaTestSubMeshes.push(subMesh);
  12045. }
  12046. else {
  12047. this._opaqueSubMeshes.push(subMesh); // Opaque
  12048. }
  12049. };
  12050. return RenderingGroup;
  12051. })();
  12052. BABYLON.RenderingGroup = RenderingGroup;
  12053. })(BABYLON || (BABYLON = {}));
  12054. var BABYLON;
  12055. (function (BABYLON) {
  12056. /**
  12057. * Represents a scene to be rendered by the engine.
  12058. * @see http://doc.babylonjs.com/page.php?p=21911
  12059. */
  12060. var Scene = (function () {
  12061. /**
  12062. * @constructor
  12063. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12064. */
  12065. function Scene(engine) {
  12066. // Members
  12067. this.autoClear = true;
  12068. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12069. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12070. this.forceWireframe = false;
  12071. this.forcePointsCloud = false;
  12072. this.forceShowBoundingBoxes = false;
  12073. this.animationsEnabled = true;
  12074. this.constantlyUpdateMeshUnderPointer = false;
  12075. 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
  12076. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12077. this._startingPointerTime = 0;
  12078. // Fog
  12079. /**
  12080. * is fog enabled on this scene.
  12081. * @type {boolean}
  12082. */
  12083. this.fogEnabled = true;
  12084. this.fogMode = Scene.FOGMODE_NONE;
  12085. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12086. this.fogDensity = 0.1;
  12087. this.fogStart = 0;
  12088. this.fogEnd = 1000.0;
  12089. // Lights
  12090. /**
  12091. * is shadow enabled on this scene.
  12092. * @type {boolean}
  12093. */
  12094. this.shadowsEnabled = true;
  12095. /**
  12096. * is light enabled on this scene.
  12097. * @type {boolean}
  12098. */
  12099. this.lightsEnabled = true;
  12100. /**
  12101. * All of the lights added to this scene.
  12102. * @see BABYLON.Light
  12103. * @type {BABYLON.Light[]}
  12104. */
  12105. this.lights = new Array();
  12106. // Cameras
  12107. /**
  12108. * All of the cameras added to this scene.
  12109. * @see BABYLON.Camera
  12110. * @type {BABYLON.Camera[]}
  12111. */
  12112. this.cameras = new Array();
  12113. this.activeCameras = new Array();
  12114. // Meshes
  12115. /**
  12116. * All of the (abstract) meshes added to this scene.
  12117. * @see BABYLON.AbstractMesh
  12118. * @type {BABYLON.AbstractMesh[]}
  12119. */
  12120. this.meshes = new Array();
  12121. // Geometries
  12122. this._geometries = new Array();
  12123. this.materials = new Array();
  12124. this.multiMaterials = new Array();
  12125. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12126. // Textures
  12127. this.texturesEnabled = true;
  12128. this.textures = new Array();
  12129. // Particles
  12130. this.particlesEnabled = true;
  12131. this.particleSystems = new Array();
  12132. // Sprites
  12133. this.spritesEnabled = true;
  12134. this.spriteManagers = new Array();
  12135. // Layers
  12136. this.layers = new Array();
  12137. // Skeletons
  12138. this.skeletonsEnabled = true;
  12139. this.skeletons = new Array();
  12140. // Lens flares
  12141. this.lensFlaresEnabled = true;
  12142. this.lensFlareSystems = new Array();
  12143. // Collisions
  12144. this.collisionsEnabled = true;
  12145. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12146. // Postprocesses
  12147. this.postProcessesEnabled = true;
  12148. // Customs render targets
  12149. this.renderTargetsEnabled = true;
  12150. this.dumpNextRenderTargets = false;
  12151. this.customRenderTargets = new Array();
  12152. // Imported meshes
  12153. this.importedMeshesFiles = new Array();
  12154. // Probes
  12155. this.probesEnabled = true;
  12156. this.reflectionProbes = new Array();
  12157. this._actionManagers = new Array();
  12158. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12159. // Procedural textures
  12160. this.proceduralTexturesEnabled = true;
  12161. this._proceduralTextures = new Array();
  12162. this.soundTracks = new Array();
  12163. this._audioEnabled = true;
  12164. this._headphone = false;
  12165. this._totalVertices = 0;
  12166. this._activeIndices = 0;
  12167. this._activeParticles = 0;
  12168. this._lastFrameDuration = 0;
  12169. this._evaluateActiveMeshesDuration = 0;
  12170. this._renderTargetsDuration = 0;
  12171. this._particlesDuration = 0;
  12172. this._renderDuration = 0;
  12173. this._spritesDuration = 0;
  12174. this._animationRatio = 0;
  12175. this._renderId = 0;
  12176. this._executeWhenReadyTimeoutId = -1;
  12177. this._toBeDisposed = new BABYLON.SmartArray(256);
  12178. this._onReadyCallbacks = new Array();
  12179. this._pendingData = []; //ANY
  12180. this._onBeforeRenderCallbacks = new Array();
  12181. this._onAfterRenderCallbacks = new Array();
  12182. this._activeMeshes = new BABYLON.SmartArray(256);
  12183. this._processedMaterials = new BABYLON.SmartArray(256);
  12184. this._renderTargets = new BABYLON.SmartArray(256);
  12185. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12186. this._activeSkeletons = new BABYLON.SmartArray(32);
  12187. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12188. this._activeBones = 0;
  12189. this._activeAnimatables = new Array();
  12190. this._transformMatrix = BABYLON.Matrix.Zero();
  12191. this._edgesRenderers = new BABYLON.SmartArray(16);
  12192. this._uniqueIdCounter = 0;
  12193. this._engine = engine;
  12194. engine.scenes.push(this);
  12195. this._renderingManager = new BABYLON.RenderingManager(this);
  12196. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12197. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12198. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12199. if (BABYLON.OutlineRenderer) {
  12200. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12201. }
  12202. this.attachControl();
  12203. this._debugLayer = new BABYLON.DebugLayer(this);
  12204. if (BABYLON.SoundTrack) {
  12205. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12206. }
  12207. //simplification queue
  12208. if (BABYLON.SimplificationQueue) {
  12209. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12210. }
  12211. //collision coordinator initialization. For now legacy per default.
  12212. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12213. }
  12214. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12215. get: function () {
  12216. return Scene._FOGMODE_NONE;
  12217. },
  12218. enumerable: true,
  12219. configurable: true
  12220. });
  12221. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12222. get: function () {
  12223. return Scene._FOGMODE_EXP;
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12229. get: function () {
  12230. return Scene._FOGMODE_EXP2;
  12231. },
  12232. enumerable: true,
  12233. configurable: true
  12234. });
  12235. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12236. get: function () {
  12237. return Scene._FOGMODE_LINEAR;
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Object.defineProperty(Scene.prototype, "debugLayer", {
  12243. // Properties
  12244. get: function () {
  12245. return this._debugLayer;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12251. get: function () {
  12252. return this._workerCollisions;
  12253. },
  12254. set: function (enabled) {
  12255. enabled = (enabled && !!Worker);
  12256. this._workerCollisions = enabled;
  12257. if (this.collisionCoordinator) {
  12258. this.collisionCoordinator.destroy();
  12259. }
  12260. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12261. this.collisionCoordinator.init(this);
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12267. get: function () {
  12268. return this._selectionOctree;
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12274. /**
  12275. * The mesh that is currently under the pointer.
  12276. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12277. */
  12278. get: function () {
  12279. return this._meshUnderPointer;
  12280. },
  12281. enumerable: true,
  12282. configurable: true
  12283. });
  12284. Object.defineProperty(Scene.prototype, "pointerX", {
  12285. /**
  12286. * Current on-screen X position of the pointer
  12287. * @return {number} X position of the pointer
  12288. */
  12289. get: function () {
  12290. return this._pointerX;
  12291. },
  12292. enumerable: true,
  12293. configurable: true
  12294. });
  12295. Object.defineProperty(Scene.prototype, "pointerY", {
  12296. /**
  12297. * Current on-screen Y position of the pointer
  12298. * @return {number} Y position of the pointer
  12299. */
  12300. get: function () {
  12301. return this._pointerY;
  12302. },
  12303. enumerable: true,
  12304. configurable: true
  12305. });
  12306. Scene.prototype.getCachedMaterial = function () {
  12307. return this._cachedMaterial;
  12308. };
  12309. Scene.prototype.getBoundingBoxRenderer = function () {
  12310. return this._boundingBoxRenderer;
  12311. };
  12312. Scene.prototype.getOutlineRenderer = function () {
  12313. return this._outlineRenderer;
  12314. };
  12315. Scene.prototype.getEngine = function () {
  12316. return this._engine;
  12317. };
  12318. Scene.prototype.getTotalVertices = function () {
  12319. return this._totalVertices;
  12320. };
  12321. Scene.prototype.getActiveIndices = function () {
  12322. return this._activeIndices;
  12323. };
  12324. Scene.prototype.getActiveParticles = function () {
  12325. return this._activeParticles;
  12326. };
  12327. Scene.prototype.getActiveBones = function () {
  12328. return this._activeBones;
  12329. };
  12330. // Stats
  12331. Scene.prototype.getLastFrameDuration = function () {
  12332. return this._lastFrameDuration;
  12333. };
  12334. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12335. return this._evaluateActiveMeshesDuration;
  12336. };
  12337. Scene.prototype.getActiveMeshes = function () {
  12338. return this._activeMeshes;
  12339. };
  12340. Scene.prototype.getRenderTargetsDuration = function () {
  12341. return this._renderTargetsDuration;
  12342. };
  12343. Scene.prototype.getRenderDuration = function () {
  12344. return this._renderDuration;
  12345. };
  12346. Scene.prototype.getParticlesDuration = function () {
  12347. return this._particlesDuration;
  12348. };
  12349. Scene.prototype.getSpritesDuration = function () {
  12350. return this._spritesDuration;
  12351. };
  12352. Scene.prototype.getAnimationRatio = function () {
  12353. return this._animationRatio;
  12354. };
  12355. Scene.prototype.getRenderId = function () {
  12356. return this._renderId;
  12357. };
  12358. Scene.prototype.incrementRenderId = function () {
  12359. this._renderId++;
  12360. };
  12361. Scene.prototype._updatePointerPosition = function (evt) {
  12362. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12363. this._pointerX = evt.clientX - canvasRect.left;
  12364. this._pointerY = evt.clientY - canvasRect.top;
  12365. if (this.cameraToUseForPointers) {
  12366. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12367. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12368. }
  12369. };
  12370. // Pointers handling
  12371. Scene.prototype.attachControl = function () {
  12372. var _this = this;
  12373. var spritePredicate = function (sprite) {
  12374. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  12375. };
  12376. this._onPointerMove = function (evt) {
  12377. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12378. return;
  12379. }
  12380. var canvas = _this._engine.getRenderingCanvas();
  12381. _this._updatePointerPosition(evt);
  12382. // Meshes
  12383. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  12384. if (pickResult.hit && pickResult.pickedMesh) {
  12385. _this._meshUnderPointer = pickResult.pickedMesh;
  12386. _this.setPointerOverMesh(pickResult.pickedMesh);
  12387. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12388. canvas.style.cursor = "pointer";
  12389. }
  12390. else {
  12391. canvas.style.cursor = "";
  12392. }
  12393. }
  12394. else {
  12395. // Sprites
  12396. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12397. if (pickResult.hit && pickResult.pickedSprite) {
  12398. canvas.style.cursor = "pointer";
  12399. }
  12400. else {
  12401. // Restore pointer
  12402. _this.setPointerOverMesh(null);
  12403. canvas.style.cursor = "";
  12404. _this._meshUnderPointer = null;
  12405. }
  12406. }
  12407. if (_this.onPointerMove) {
  12408. _this.onPointerMove(evt, pickResult);
  12409. }
  12410. };
  12411. this._onPointerDown = function (evt) {
  12412. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12413. return;
  12414. }
  12415. _this._updatePointerPosition(evt);
  12416. _this._startingPointerPosition.x = _this._pointerX;
  12417. _this._startingPointerPosition.y = _this._pointerY;
  12418. _this._startingPointerTime = new Date().getTime();
  12419. var predicate = null;
  12420. // Meshes
  12421. if (!_this.onPointerDown) {
  12422. predicate = function (mesh) {
  12423. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12424. };
  12425. }
  12426. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12427. if (pickResult.hit && pickResult.pickedMesh) {
  12428. if (pickResult.pickedMesh.actionManager) {
  12429. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12430. switch (evt.button) {
  12431. case 0:
  12432. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12433. break;
  12434. case 1:
  12435. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12436. break;
  12437. case 2:
  12438. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12439. break;
  12440. }
  12441. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12442. }
  12443. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12444. var that = _this;
  12445. window.setTimeout(function () {
  12446. var pickResult = that.pick(that._pointerX, that._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12447. if (pickResult.hit && pickResult.pickedMesh) {
  12448. if (pickResult.pickedMesh.actionManager) {
  12449. 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)) {
  12450. that._startingPointerTime = 0;
  12451. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12452. }
  12453. }
  12454. }
  12455. }, BABYLON.ActionManager.LongPressDelay);
  12456. }
  12457. }
  12458. }
  12459. if (_this.onPointerDown) {
  12460. _this.onPointerDown(evt, pickResult);
  12461. }
  12462. // Sprites
  12463. if (_this.spriteManagers.length > 0) {
  12464. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12465. if (pickResult.hit && pickResult.pickedSprite) {
  12466. if (pickResult.pickedSprite.actionManager) {
  12467. switch (evt.button) {
  12468. case 0:
  12469. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12470. break;
  12471. case 1:
  12472. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12473. break;
  12474. case 2:
  12475. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12476. break;
  12477. }
  12478. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12479. }
  12480. }
  12481. }
  12482. };
  12483. this._onPointerUp = function (evt) {
  12484. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12485. return;
  12486. }
  12487. var predicate = null;
  12488. _this._updatePointerPosition(evt);
  12489. if (!_this.onPointerUp) {
  12490. predicate = function (mesh) {
  12491. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12492. };
  12493. }
  12494. // Meshes
  12495. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12496. if (pickResult.hit && pickResult.pickedMesh) {
  12497. if (pickResult.pickedMesh.actionManager) {
  12498. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12499. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12500. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12501. }
  12502. }
  12503. }
  12504. if (_this.onPointerUp) {
  12505. _this.onPointerUp(evt, pickResult);
  12506. }
  12507. _this._startingPointerTime = 0;
  12508. // Sprites
  12509. if (_this.spriteManagers.length > 0) {
  12510. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12511. if (pickResult.hit && pickResult.pickedSprite) {
  12512. if (pickResult.pickedSprite.actionManager) {
  12513. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12514. }
  12515. }
  12516. }
  12517. };
  12518. this._onKeyDown = function (evt) {
  12519. if (_this.actionManager) {
  12520. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12521. }
  12522. };
  12523. this._onKeyUp = function (evt) {
  12524. if (_this.actionManager) {
  12525. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12526. }
  12527. };
  12528. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12529. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12530. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12531. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12532. // Wheel
  12533. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12534. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12535. BABYLON.Tools.RegisterTopRootEvents([
  12536. { name: "keydown", handler: this._onKeyDown },
  12537. { name: "keyup", handler: this._onKeyUp }
  12538. ]);
  12539. };
  12540. Scene.prototype.detachControl = function () {
  12541. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12542. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12543. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12544. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12545. // Wheel
  12546. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12547. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12548. BABYLON.Tools.UnregisterTopRootEvents([
  12549. { name: "keydown", handler: this._onKeyDown },
  12550. { name: "keyup", handler: this._onKeyUp }
  12551. ]);
  12552. };
  12553. // Ready
  12554. Scene.prototype.isReady = function () {
  12555. if (this._pendingData.length > 0) {
  12556. return false;
  12557. }
  12558. var index;
  12559. for (index = 0; index < this._geometries.length; index++) {
  12560. var geometry = this._geometries[index];
  12561. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12562. return false;
  12563. }
  12564. }
  12565. for (index = 0; index < this.meshes.length; index++) {
  12566. var mesh = this.meshes[index];
  12567. if (!mesh.isReady()) {
  12568. return false;
  12569. }
  12570. var mat = mesh.material;
  12571. if (mat) {
  12572. if (!mat.isReady(mesh)) {
  12573. return false;
  12574. }
  12575. }
  12576. }
  12577. return true;
  12578. };
  12579. Scene.prototype.resetCachedMaterial = function () {
  12580. this._cachedMaterial = null;
  12581. };
  12582. Scene.prototype.registerBeforeRender = function (func) {
  12583. this._onBeforeRenderCallbacks.push(func);
  12584. };
  12585. Scene.prototype.unregisterBeforeRender = function (func) {
  12586. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12587. if (index > -1) {
  12588. this._onBeforeRenderCallbacks.splice(index, 1);
  12589. }
  12590. };
  12591. Scene.prototype.registerAfterRender = function (func) {
  12592. this._onAfterRenderCallbacks.push(func);
  12593. };
  12594. Scene.prototype.unregisterAfterRender = function (func) {
  12595. var index = this._onAfterRenderCallbacks.indexOf(func);
  12596. if (index > -1) {
  12597. this._onAfterRenderCallbacks.splice(index, 1);
  12598. }
  12599. };
  12600. Scene.prototype._addPendingData = function (data) {
  12601. this._pendingData.push(data);
  12602. };
  12603. Scene.prototype._removePendingData = function (data) {
  12604. var index = this._pendingData.indexOf(data);
  12605. if (index !== -1) {
  12606. this._pendingData.splice(index, 1);
  12607. }
  12608. };
  12609. Scene.prototype.getWaitingItemsCount = function () {
  12610. return this._pendingData.length;
  12611. };
  12612. /**
  12613. * Registers a function to be executed when the scene is ready.
  12614. * @param {Function} func - the function to be executed.
  12615. */
  12616. Scene.prototype.executeWhenReady = function (func) {
  12617. var _this = this;
  12618. this._onReadyCallbacks.push(func);
  12619. if (this._executeWhenReadyTimeoutId !== -1) {
  12620. return;
  12621. }
  12622. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12623. _this._checkIsReady();
  12624. }, 150);
  12625. };
  12626. Scene.prototype._checkIsReady = function () {
  12627. var _this = this;
  12628. if (this.isReady()) {
  12629. this._onReadyCallbacks.forEach(function (func) {
  12630. func();
  12631. });
  12632. this._onReadyCallbacks = [];
  12633. this._executeWhenReadyTimeoutId = -1;
  12634. return;
  12635. }
  12636. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12637. _this._checkIsReady();
  12638. }, 150);
  12639. };
  12640. // Animations
  12641. /**
  12642. * Will start the animation sequence of a given target
  12643. * @param target - the target
  12644. * @param {number} from - from which frame should animation start
  12645. * @param {number} to - till which frame should animation run.
  12646. * @param {boolean} [loop] - should the animation loop
  12647. * @param {number} [speedRatio] - the speed in which to run the animation
  12648. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12649. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12650. * @return {BABYLON.Animatable} the animatable object created for this animation
  12651. * @see BABYLON.Animatable
  12652. * @see http://doc.babylonjs.com/page.php?p=22081
  12653. */
  12654. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12655. if (speedRatio === void 0) { speedRatio = 1.0; }
  12656. this.stopAnimation(target);
  12657. if (!animatable) {
  12658. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12659. }
  12660. // Local animations
  12661. if (target.animations) {
  12662. animatable.appendAnimations(target, target.animations);
  12663. }
  12664. // Children animations
  12665. if (target.getAnimatables) {
  12666. var animatables = target.getAnimatables();
  12667. for (var index = 0; index < animatables.length; index++) {
  12668. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12669. }
  12670. }
  12671. return animatable;
  12672. };
  12673. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12674. if (speedRatio === undefined) {
  12675. speedRatio = 1.0;
  12676. }
  12677. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12678. return animatable;
  12679. };
  12680. Scene.prototype.getAnimatableByTarget = function (target) {
  12681. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12682. if (this._activeAnimatables[index].target === target) {
  12683. return this._activeAnimatables[index];
  12684. }
  12685. }
  12686. return null;
  12687. };
  12688. Object.defineProperty(Scene.prototype, "Animatables", {
  12689. get: function () {
  12690. return this._activeAnimatables;
  12691. },
  12692. enumerable: true,
  12693. configurable: true
  12694. });
  12695. /**
  12696. * Will stop the animation of the given target
  12697. * @param target - the target
  12698. * @see beginAnimation
  12699. */
  12700. Scene.prototype.stopAnimation = function (target) {
  12701. var animatable = this.getAnimatableByTarget(target);
  12702. if (animatable) {
  12703. animatable.stop();
  12704. }
  12705. };
  12706. Scene.prototype._animate = function () {
  12707. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12708. return;
  12709. }
  12710. if (!this._animationStartDate) {
  12711. if (this._pendingData.length > 0) {
  12712. return;
  12713. }
  12714. this._animationStartDate = BABYLON.Tools.Now;
  12715. }
  12716. // Getting time
  12717. var now = BABYLON.Tools.Now;
  12718. var delay = now - this._animationStartDate;
  12719. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12720. this._activeAnimatables[index]._animate(delay);
  12721. }
  12722. };
  12723. // Matrix
  12724. Scene.prototype.getViewMatrix = function () {
  12725. return this._viewMatrix;
  12726. };
  12727. Scene.prototype.getProjectionMatrix = function () {
  12728. return this._projectionMatrix;
  12729. };
  12730. Scene.prototype.getTransformMatrix = function () {
  12731. return this._transformMatrix;
  12732. };
  12733. Scene.prototype.setTransformMatrix = function (view, projection) {
  12734. this._viewMatrix = view;
  12735. this._projectionMatrix = projection;
  12736. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12737. };
  12738. // Methods
  12739. Scene.prototype.addMesh = function (newMesh) {
  12740. newMesh.uniqueId = this._uniqueIdCounter++;
  12741. var position = this.meshes.push(newMesh);
  12742. //notify the collision coordinator
  12743. this.collisionCoordinator.onMeshAdded(newMesh);
  12744. if (this.onNewMeshAdded) {
  12745. this.onNewMeshAdded(newMesh, position, this);
  12746. }
  12747. };
  12748. Scene.prototype.removeMesh = function (toRemove) {
  12749. var index = this.meshes.indexOf(toRemove);
  12750. if (index !== -1) {
  12751. // Remove from the scene if mesh found
  12752. this.meshes.splice(index, 1);
  12753. }
  12754. //notify the collision coordinator
  12755. this.collisionCoordinator.onMeshRemoved(toRemove);
  12756. if (this.onMeshRemoved) {
  12757. this.onMeshRemoved(toRemove);
  12758. }
  12759. return index;
  12760. };
  12761. Scene.prototype.removeSkeleton = function (toRemove) {
  12762. var index = this.skeletons.indexOf(toRemove);
  12763. if (index !== -1) {
  12764. // Remove from the scene if mesh found
  12765. this.skeletons.splice(index, 1);
  12766. }
  12767. return index;
  12768. };
  12769. Scene.prototype.removeLight = function (toRemove) {
  12770. var index = this.lights.indexOf(toRemove);
  12771. if (index !== -1) {
  12772. // Remove from the scene if mesh found
  12773. this.lights.splice(index, 1);
  12774. }
  12775. if (this.onLightRemoved) {
  12776. this.onLightRemoved(toRemove);
  12777. }
  12778. return index;
  12779. };
  12780. Scene.prototype.removeCamera = function (toRemove) {
  12781. var index = this.cameras.indexOf(toRemove);
  12782. if (index !== -1) {
  12783. // Remove from the scene if mesh found
  12784. this.cameras.splice(index, 1);
  12785. }
  12786. // Remove from activeCameras
  12787. var index2 = this.activeCameras.indexOf(toRemove);
  12788. if (index2 !== -1) {
  12789. // Remove from the scene if mesh found
  12790. this.activeCameras.splice(index2, 1);
  12791. }
  12792. // Reset the activeCamera
  12793. if (this.activeCamera === toRemove) {
  12794. if (this.cameras.length > 0) {
  12795. this.activeCamera = this.cameras[0];
  12796. }
  12797. else {
  12798. this.activeCamera = null;
  12799. }
  12800. }
  12801. if (this.onCameraRemoved) {
  12802. this.onCameraRemoved(toRemove);
  12803. }
  12804. return index;
  12805. };
  12806. Scene.prototype.addLight = function (newLight) {
  12807. newLight.uniqueId = this._uniqueIdCounter++;
  12808. var position = this.lights.push(newLight);
  12809. if (this.onNewLightAdded) {
  12810. this.onNewLightAdded(newLight, position, this);
  12811. }
  12812. };
  12813. Scene.prototype.addCamera = function (newCamera) {
  12814. newCamera.uniqueId = this._uniqueIdCounter++;
  12815. var position = this.cameras.push(newCamera);
  12816. if (this.onNewCameraAdded) {
  12817. this.onNewCameraAdded(newCamera, position, this);
  12818. }
  12819. };
  12820. /**
  12821. * sets the active camera of the scene using its ID
  12822. * @param {string} id - the camera's ID
  12823. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12824. * @see activeCamera
  12825. */
  12826. Scene.prototype.setActiveCameraByID = function (id) {
  12827. var camera = this.getCameraByID(id);
  12828. if (camera) {
  12829. this.activeCamera = camera;
  12830. return camera;
  12831. }
  12832. return null;
  12833. };
  12834. /**
  12835. * sets the active camera of the scene using its name
  12836. * @param {string} name - the camera's name
  12837. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12838. * @see activeCamera
  12839. */
  12840. Scene.prototype.setActiveCameraByName = function (name) {
  12841. var camera = this.getCameraByName(name);
  12842. if (camera) {
  12843. this.activeCamera = camera;
  12844. return camera;
  12845. }
  12846. return null;
  12847. };
  12848. /**
  12849. * get a material using its id
  12850. * @param {string} the material's ID
  12851. * @return {BABYLON.Material|null} the material or null if none found.
  12852. */
  12853. Scene.prototype.getMaterialByID = function (id) {
  12854. for (var index = 0; index < this.materials.length; index++) {
  12855. if (this.materials[index].id === id) {
  12856. return this.materials[index];
  12857. }
  12858. }
  12859. return null;
  12860. };
  12861. /**
  12862. * get a material using its name
  12863. * @param {string} the material's name
  12864. * @return {BABYLON.Material|null} the material or null if none found.
  12865. */
  12866. Scene.prototype.getMaterialByName = function (name) {
  12867. for (var index = 0; index < this.materials.length; index++) {
  12868. if (this.materials[index].name === name) {
  12869. return this.materials[index];
  12870. }
  12871. }
  12872. return null;
  12873. };
  12874. Scene.prototype.getLensFlareSystemByName = function (name) {
  12875. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12876. if (this.lensFlareSystems[index].name === name) {
  12877. return this.lensFlareSystems[index];
  12878. }
  12879. }
  12880. return null;
  12881. };
  12882. Scene.prototype.getCameraByID = function (id) {
  12883. for (var index = 0; index < this.cameras.length; index++) {
  12884. if (this.cameras[index].id === id) {
  12885. return this.cameras[index];
  12886. }
  12887. }
  12888. return null;
  12889. };
  12890. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12891. for (var index = 0; index < this.cameras.length; index++) {
  12892. if (this.cameras[index].uniqueId === uniqueId) {
  12893. return this.cameras[index];
  12894. }
  12895. }
  12896. return null;
  12897. };
  12898. /**
  12899. * get a camera using its name
  12900. * @param {string} the camera's name
  12901. * @return {BABYLON.Camera|null} the camera or null if none found.
  12902. */
  12903. Scene.prototype.getCameraByName = function (name) {
  12904. for (var index = 0; index < this.cameras.length; index++) {
  12905. if (this.cameras[index].name === name) {
  12906. return this.cameras[index];
  12907. }
  12908. }
  12909. return null;
  12910. };
  12911. /**
  12912. * get a bone using its id
  12913. * @param {string} the bone's id
  12914. * @return {BABYLON.Bone|null} the bone or null if not found
  12915. */
  12916. Scene.prototype.getBoneByID = function (id) {
  12917. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12918. var skeleton = this.skeletons[skeletonIndex];
  12919. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12920. if (skeleton.bones[boneIndex].id === id) {
  12921. return skeleton.bones[boneIndex];
  12922. }
  12923. }
  12924. }
  12925. return null;
  12926. };
  12927. /**
  12928. * get a bone using its id
  12929. * @param {string} the bone's name
  12930. * @return {BABYLON.Bone|null} the bone or null if not found
  12931. */
  12932. Scene.prototype.getBoneByName = function (name) {
  12933. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  12934. var skeleton = this.skeletons[skeletonIndex];
  12935. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  12936. if (skeleton.bones[boneIndex].name === name) {
  12937. return skeleton.bones[boneIndex];
  12938. }
  12939. }
  12940. }
  12941. return null;
  12942. };
  12943. /**
  12944. * get a light node using its name
  12945. * @param {string} the light's name
  12946. * @return {BABYLON.Light|null} the light or null if none found.
  12947. */
  12948. Scene.prototype.getLightByName = function (name) {
  12949. for (var index = 0; index < this.lights.length; index++) {
  12950. if (this.lights[index].name === name) {
  12951. return this.lights[index];
  12952. }
  12953. }
  12954. return null;
  12955. };
  12956. /**
  12957. * get a light node using its ID
  12958. * @param {string} the light's id
  12959. * @return {BABYLON.Light|null} the light or null if none found.
  12960. */
  12961. Scene.prototype.getLightByID = function (id) {
  12962. for (var index = 0; index < this.lights.length; index++) {
  12963. if (this.lights[index].id === id) {
  12964. return this.lights[index];
  12965. }
  12966. }
  12967. return null;
  12968. };
  12969. /**
  12970. * get a light node using its scene-generated unique ID
  12971. * @param {number} the light's unique id
  12972. * @return {BABYLON.Light|null} the light or null if none found.
  12973. */
  12974. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12975. for (var index = 0; index < this.lights.length; index++) {
  12976. if (this.lights[index].uniqueId === uniqueId) {
  12977. return this.lights[index];
  12978. }
  12979. }
  12980. return null;
  12981. };
  12982. /**
  12983. * get a particle system by id
  12984. * @param id {number} the particle system id
  12985. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  12986. */
  12987. Scene.prototype.getParticleSystemByID = function (id) {
  12988. for (var index = 0; index < this.particleSystems.length; index++) {
  12989. if (this.particleSystems[index].id === id) {
  12990. return this.particleSystems[index];
  12991. }
  12992. }
  12993. return null;
  12994. };
  12995. /**
  12996. * get a geometry using its ID
  12997. * @param {string} the geometry's id
  12998. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12999. */
  13000. Scene.prototype.getGeometryByID = function (id) {
  13001. for (var index = 0; index < this._geometries.length; index++) {
  13002. if (this._geometries[index].id === id) {
  13003. return this._geometries[index];
  13004. }
  13005. }
  13006. return null;
  13007. };
  13008. /**
  13009. * add a new geometry to this scene.
  13010. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13011. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13012. * @return {boolean} was the geometry added or not
  13013. */
  13014. Scene.prototype.pushGeometry = function (geometry, force) {
  13015. if (!force && this.getGeometryByID(geometry.id)) {
  13016. return false;
  13017. }
  13018. this._geometries.push(geometry);
  13019. //notify the collision coordinator
  13020. this.collisionCoordinator.onGeometryAdded(geometry);
  13021. if (this.onGeometryAdded) {
  13022. this.onGeometryAdded(geometry);
  13023. }
  13024. return true;
  13025. };
  13026. /**
  13027. * Removes an existing geometry
  13028. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13029. * @return {boolean} was the geometry removed or not
  13030. */
  13031. Scene.prototype.removeGeometry = function (geometry) {
  13032. var index = this._geometries.indexOf(geometry);
  13033. if (index > -1) {
  13034. this._geometries.splice(index, 1);
  13035. //notify the collision coordinator
  13036. this.collisionCoordinator.onGeometryDeleted(geometry);
  13037. if (this.onGeometryRemoved) {
  13038. this.onGeometryRemoved(geometry);
  13039. }
  13040. return true;
  13041. }
  13042. return false;
  13043. };
  13044. Scene.prototype.getGeometries = function () {
  13045. return this._geometries;
  13046. };
  13047. /**
  13048. * Get the first added mesh found of a given ID
  13049. * @param {string} id - the id to search for
  13050. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13051. */
  13052. Scene.prototype.getMeshByID = function (id) {
  13053. for (var index = 0; index < this.meshes.length; index++) {
  13054. if (this.meshes[index].id === id) {
  13055. return this.meshes[index];
  13056. }
  13057. }
  13058. return null;
  13059. };
  13060. /**
  13061. * Get a mesh with its auto-generated unique id
  13062. * @param {number} uniqueId - the unique id to search for
  13063. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13064. */
  13065. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13066. for (var index = 0; index < this.meshes.length; index++) {
  13067. if (this.meshes[index].uniqueId === uniqueId) {
  13068. return this.meshes[index];
  13069. }
  13070. }
  13071. return null;
  13072. };
  13073. /**
  13074. * Get a the last added mesh found of a given ID
  13075. * @param {string} id - the id to search for
  13076. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13077. */
  13078. Scene.prototype.getLastMeshByID = function (id) {
  13079. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13080. if (this.meshes[index].id === id) {
  13081. return this.meshes[index];
  13082. }
  13083. }
  13084. return null;
  13085. };
  13086. /**
  13087. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13088. * @param {string} id - the id to search for
  13089. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13090. */
  13091. Scene.prototype.getLastEntryByID = function (id) {
  13092. var index;
  13093. for (index = this.meshes.length - 1; index >= 0; index--) {
  13094. if (this.meshes[index].id === id) {
  13095. return this.meshes[index];
  13096. }
  13097. }
  13098. for (index = this.cameras.length - 1; index >= 0; index--) {
  13099. if (this.cameras[index].id === id) {
  13100. return this.cameras[index];
  13101. }
  13102. }
  13103. for (index = this.lights.length - 1; index >= 0; index--) {
  13104. if (this.lights[index].id === id) {
  13105. return this.lights[index];
  13106. }
  13107. }
  13108. return null;
  13109. };
  13110. Scene.prototype.getNodeByID = function (id) {
  13111. var mesh = this.getMeshByID(id);
  13112. if (mesh) {
  13113. return mesh;
  13114. }
  13115. var light = this.getLightByID(id);
  13116. if (light) {
  13117. return light;
  13118. }
  13119. var camera = this.getCameraByID(id);
  13120. if (camera) {
  13121. return camera;
  13122. }
  13123. var bone = this.getBoneByID(id);
  13124. return bone;
  13125. };
  13126. Scene.prototype.getNodeByName = function (name) {
  13127. var mesh = this.getMeshByName(name);
  13128. if (mesh) {
  13129. return mesh;
  13130. }
  13131. var light = this.getLightByName(name);
  13132. if (light) {
  13133. return light;
  13134. }
  13135. var camera = this.getCameraByName(name);
  13136. if (camera) {
  13137. return camera;
  13138. }
  13139. var bone = this.getBoneByName(name);
  13140. return bone;
  13141. };
  13142. Scene.prototype.getMeshByName = function (name) {
  13143. for (var index = 0; index < this.meshes.length; index++) {
  13144. if (this.meshes[index].name === name) {
  13145. return this.meshes[index];
  13146. }
  13147. }
  13148. return null;
  13149. };
  13150. Scene.prototype.getSoundByName = function (name) {
  13151. var index;
  13152. if (BABYLON.AudioEngine) {
  13153. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13154. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13155. return this.mainSoundTrack.soundCollection[index];
  13156. }
  13157. }
  13158. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13159. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13160. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13161. return this.soundTracks[sdIndex].soundCollection[index];
  13162. }
  13163. }
  13164. }
  13165. }
  13166. return null;
  13167. };
  13168. Scene.prototype.getLastSkeletonByID = function (id) {
  13169. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13170. if (this.skeletons[index].id === id) {
  13171. return this.skeletons[index];
  13172. }
  13173. }
  13174. return null;
  13175. };
  13176. Scene.prototype.getSkeletonById = function (id) {
  13177. for (var index = 0; index < this.skeletons.length; index++) {
  13178. if (this.skeletons[index].id === id) {
  13179. return this.skeletons[index];
  13180. }
  13181. }
  13182. return null;
  13183. };
  13184. Scene.prototype.getSkeletonByName = function (name) {
  13185. for (var index = 0; index < this.skeletons.length; index++) {
  13186. if (this.skeletons[index].name === name) {
  13187. return this.skeletons[index];
  13188. }
  13189. }
  13190. return null;
  13191. };
  13192. Scene.prototype.isActiveMesh = function (mesh) {
  13193. return (this._activeMeshes.indexOf(mesh) !== -1);
  13194. };
  13195. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13196. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13197. var material = subMesh.getMaterial();
  13198. if (mesh.showSubMeshesBoundingBox) {
  13199. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13200. }
  13201. if (material) {
  13202. // Render targets
  13203. if (material.getRenderTargetTextures) {
  13204. if (this._processedMaterials.indexOf(material) === -1) {
  13205. this._processedMaterials.push(material);
  13206. this._renderTargets.concat(material.getRenderTargetTextures());
  13207. }
  13208. }
  13209. // Dispatch
  13210. this._activeIndices += subMesh.indexCount;
  13211. this._renderingManager.dispatch(subMesh);
  13212. }
  13213. }
  13214. };
  13215. Scene.prototype._evaluateActiveMeshes = function () {
  13216. this.activeCamera._activeMeshes.reset();
  13217. this._activeMeshes.reset();
  13218. this._renderingManager.reset();
  13219. this._processedMaterials.reset();
  13220. this._activeParticleSystems.reset();
  13221. this._activeSkeletons.reset();
  13222. this._softwareSkinnedMeshes.reset();
  13223. this._boundingBoxRenderer.reset();
  13224. this._edgesRenderers.reset();
  13225. if (!this._frustumPlanes) {
  13226. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13227. }
  13228. else {
  13229. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13230. }
  13231. // Meshes
  13232. var meshes;
  13233. var len;
  13234. if (this._selectionOctree) {
  13235. var selection = this._selectionOctree.select(this._frustumPlanes);
  13236. meshes = selection.data;
  13237. len = selection.length;
  13238. }
  13239. else {
  13240. len = this.meshes.length;
  13241. meshes = this.meshes;
  13242. }
  13243. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13244. var mesh = meshes[meshIndex];
  13245. if (mesh.isBlocked) {
  13246. continue;
  13247. }
  13248. this._totalVertices += mesh.getTotalVertices();
  13249. if (!mesh.isReady() || !mesh.isEnabled()) {
  13250. continue;
  13251. }
  13252. mesh.computeWorldMatrix();
  13253. // Intersections
  13254. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13255. this._meshesForIntersections.pushNoDuplicate(mesh);
  13256. }
  13257. // Switch to current LOD
  13258. var meshLOD = mesh.getLOD(this.activeCamera);
  13259. if (!meshLOD) {
  13260. continue;
  13261. }
  13262. mesh._preActivate();
  13263. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13264. this._activeMeshes.push(mesh);
  13265. this.activeCamera._activeMeshes.push(mesh);
  13266. mesh._activate(this._renderId);
  13267. this._activeMesh(meshLOD);
  13268. }
  13269. }
  13270. // Particle systems
  13271. var beforeParticlesDate = BABYLON.Tools.Now;
  13272. if (this.particlesEnabled) {
  13273. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13274. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13275. var particleSystem = this.particleSystems[particleIndex];
  13276. if (!particleSystem.isStarted()) {
  13277. continue;
  13278. }
  13279. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13280. this._activeParticleSystems.push(particleSystem);
  13281. particleSystem.animate();
  13282. }
  13283. }
  13284. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13285. }
  13286. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13287. };
  13288. Scene.prototype._activeMesh = function (mesh) {
  13289. if (mesh.skeleton && this.skeletonsEnabled) {
  13290. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13291. if (!mesh.computeBonesUsingShaders) {
  13292. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13293. }
  13294. }
  13295. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13296. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13297. }
  13298. if (mesh._edgesRenderer) {
  13299. this._edgesRenderers.push(mesh._edgesRenderer);
  13300. }
  13301. if (mesh && mesh.subMeshes) {
  13302. // Submeshes Octrees
  13303. var len;
  13304. var subMeshes;
  13305. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13306. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13307. len = intersections.length;
  13308. subMeshes = intersections.data;
  13309. }
  13310. else {
  13311. subMeshes = mesh.subMeshes;
  13312. len = subMeshes.length;
  13313. }
  13314. for (var subIndex = 0; subIndex < len; subIndex++) {
  13315. var subMesh = subMeshes[subIndex];
  13316. this._evaluateSubMesh(subMesh, mesh);
  13317. }
  13318. }
  13319. };
  13320. Scene.prototype.updateTransformMatrix = function (force) {
  13321. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13322. };
  13323. Scene.prototype._renderForCamera = function (camera) {
  13324. var engine = this._engine;
  13325. this.activeCamera = camera;
  13326. if (!this.activeCamera)
  13327. throw new Error("Active camera not set");
  13328. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13329. // Viewport
  13330. engine.setViewport(this.activeCamera.viewport);
  13331. // Camera
  13332. this.resetCachedMaterial();
  13333. this._renderId++;
  13334. this.updateTransformMatrix();
  13335. if (this.beforeCameraRender) {
  13336. this.beforeCameraRender(this.activeCamera);
  13337. }
  13338. // Meshes
  13339. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13340. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13341. this._evaluateActiveMeshes();
  13342. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13343. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13344. // Skeletons
  13345. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13346. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13347. skeleton.prepare();
  13348. }
  13349. // Software skinning
  13350. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13351. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13352. mesh.applySkeleton(mesh.skeleton);
  13353. }
  13354. // Render targets
  13355. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13356. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13357. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13358. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13359. var renderTarget = this._renderTargets.data[renderIndex];
  13360. if (renderTarget._shouldRender()) {
  13361. this._renderId++;
  13362. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13363. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13364. }
  13365. }
  13366. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13367. this._renderId++;
  13368. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13369. }
  13370. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13371. // Prepare Frame
  13372. this.postProcessManager._prepareFrame();
  13373. var beforeRenderDate = BABYLON.Tools.Now;
  13374. // Backgrounds
  13375. var layerIndex;
  13376. var layer;
  13377. if (this.layers.length) {
  13378. engine.setDepthBuffer(false);
  13379. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13380. layer = this.layers[layerIndex];
  13381. if (layer.isBackground) {
  13382. layer.render();
  13383. }
  13384. }
  13385. engine.setDepthBuffer(true);
  13386. }
  13387. // Render
  13388. BABYLON.Tools.StartPerformanceCounter("Main render");
  13389. this._renderingManager.render(null, null, true, true);
  13390. BABYLON.Tools.EndPerformanceCounter("Main render");
  13391. // Bounding boxes
  13392. this._boundingBoxRenderer.render();
  13393. // Edges
  13394. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13395. this._edgesRenderers.data[edgesRendererIndex].render();
  13396. }
  13397. // Lens flares
  13398. if (this.lensFlaresEnabled) {
  13399. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13400. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13401. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13402. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13403. lensFlareSystem.render();
  13404. }
  13405. }
  13406. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13407. }
  13408. // Foregrounds
  13409. if (this.layers.length) {
  13410. engine.setDepthBuffer(false);
  13411. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13412. layer = this.layers[layerIndex];
  13413. if (!layer.isBackground) {
  13414. layer.render();
  13415. }
  13416. }
  13417. engine.setDepthBuffer(true);
  13418. }
  13419. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13420. // Finalize frame
  13421. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13422. // Update camera
  13423. this.activeCamera._updateFromScene();
  13424. // Reset some special arrays
  13425. this._renderTargets.reset();
  13426. if (this.afterCameraRender) {
  13427. this.afterCameraRender(this.activeCamera);
  13428. }
  13429. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13430. };
  13431. Scene.prototype._processSubCameras = function (camera) {
  13432. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13433. this._renderForCamera(camera);
  13434. return;
  13435. }
  13436. // rig cameras
  13437. for (var index = 0; index < camera._rigCameras.length; index++) {
  13438. this._renderForCamera(camera._rigCameras[index]);
  13439. }
  13440. this.activeCamera = camera;
  13441. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13442. // Update camera
  13443. this.activeCamera._updateFromScene();
  13444. };
  13445. Scene.prototype._checkIntersections = function () {
  13446. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13447. var sourceMesh = this._meshesForIntersections.data[index];
  13448. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13449. var action = sourceMesh.actionManager.actions[actionIndex];
  13450. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13451. var parameters = action.getTriggerParameter();
  13452. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13453. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13454. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13455. if (areIntersecting && currentIntersectionInProgress === -1) {
  13456. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13457. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13458. sourceMesh._intersectionsInProgress.push(otherMesh);
  13459. }
  13460. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13461. sourceMesh._intersectionsInProgress.push(otherMesh);
  13462. }
  13463. }
  13464. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13465. //They intersected, and now they don't.
  13466. //is this trigger an exit trigger? execute an event.
  13467. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13468. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13469. }
  13470. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13471. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13472. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13473. }
  13474. }
  13475. }
  13476. }
  13477. }
  13478. };
  13479. Scene.prototype.render = function () {
  13480. var startDate = BABYLON.Tools.Now;
  13481. this._particlesDuration = 0;
  13482. this._spritesDuration = 0;
  13483. this._activeParticles = 0;
  13484. this._renderDuration = 0;
  13485. this._renderTargetsDuration = 0;
  13486. this._evaluateActiveMeshesDuration = 0;
  13487. this._totalVertices = 0;
  13488. this._activeIndices = 0;
  13489. this._activeBones = 0;
  13490. this.getEngine().resetDrawCalls();
  13491. this._meshesForIntersections.reset();
  13492. this.resetCachedMaterial();
  13493. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13494. // Actions
  13495. if (this.actionManager) {
  13496. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13497. }
  13498. //Simplification Queue
  13499. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13500. this.simplificationQueue.executeNext();
  13501. }
  13502. // Animations
  13503. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13504. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13505. this._animate();
  13506. // Physics
  13507. if (this._physicsEngine) {
  13508. BABYLON.Tools.StartPerformanceCounter("Physics");
  13509. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13510. BABYLON.Tools.EndPerformanceCounter("Physics");
  13511. }
  13512. // Before render
  13513. if (this.beforeRender) {
  13514. this.beforeRender();
  13515. }
  13516. var callbackIndex;
  13517. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13518. this._onBeforeRenderCallbacks[callbackIndex]();
  13519. }
  13520. // Customs render targets
  13521. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13522. var engine = this.getEngine();
  13523. var currentActiveCamera = this.activeCamera;
  13524. if (this.renderTargetsEnabled) {
  13525. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13526. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13527. var renderTarget = this.customRenderTargets[customIndex];
  13528. if (renderTarget._shouldRender()) {
  13529. this._renderId++;
  13530. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13531. if (!this.activeCamera)
  13532. throw new Error("Active camera not set");
  13533. // Viewport
  13534. engine.setViewport(this.activeCamera.viewport);
  13535. // Camera
  13536. this.updateTransformMatrix();
  13537. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13538. }
  13539. }
  13540. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13541. this._renderId++;
  13542. }
  13543. if (this.customRenderTargets.length > 0) {
  13544. engine.restoreDefaultFramebuffer();
  13545. }
  13546. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13547. this.activeCamera = currentActiveCamera;
  13548. // Procedural textures
  13549. if (this.proceduralTexturesEnabled) {
  13550. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13551. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13552. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13553. if (proceduralTexture._shouldRender()) {
  13554. proceduralTexture.render();
  13555. }
  13556. }
  13557. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13558. }
  13559. // Clear
  13560. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13561. // Shadows
  13562. if (this.shadowsEnabled) {
  13563. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13564. var light = this.lights[lightIndex];
  13565. var shadowGenerator = light.getShadowGenerator();
  13566. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13567. this._renderTargets.push(shadowGenerator.getShadowMap());
  13568. }
  13569. }
  13570. }
  13571. // Depth renderer
  13572. if (this._depthRenderer) {
  13573. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13574. }
  13575. // RenderPipeline
  13576. this.postProcessRenderPipelineManager.update();
  13577. // Multi-cameras?
  13578. if (this.activeCameras.length > 0) {
  13579. var currentRenderId = this._renderId;
  13580. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13581. this._renderId = currentRenderId;
  13582. if (cameraIndex > 0) {
  13583. this._engine.clear(0, false, true);
  13584. }
  13585. this._processSubCameras(this.activeCameras[cameraIndex]);
  13586. }
  13587. }
  13588. else {
  13589. if (!this.activeCamera) {
  13590. throw new Error("No camera defined");
  13591. }
  13592. this._processSubCameras(this.activeCamera);
  13593. }
  13594. // Intersection checks
  13595. this._checkIntersections();
  13596. // Update the audio listener attached to the camera
  13597. if (BABYLON.AudioEngine) {
  13598. this._updateAudioParameters();
  13599. }
  13600. // After render
  13601. if (this.afterRender) {
  13602. this.afterRender();
  13603. }
  13604. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13605. this._onAfterRenderCallbacks[callbackIndex]();
  13606. }
  13607. // Cleaning
  13608. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13609. this._toBeDisposed.data[index].dispose();
  13610. this._toBeDisposed[index] = null;
  13611. }
  13612. this._toBeDisposed.reset();
  13613. if (this.dumpNextRenderTargets) {
  13614. this.dumpNextRenderTargets = false;
  13615. }
  13616. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13617. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13618. };
  13619. Scene.prototype._updateAudioParameters = function () {
  13620. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13621. return;
  13622. }
  13623. var listeningCamera;
  13624. var audioEngine = BABYLON.Engine.audioEngine;
  13625. if (this.activeCameras.length > 0) {
  13626. listeningCamera = this.activeCameras[0];
  13627. }
  13628. else {
  13629. listeningCamera = this.activeCamera;
  13630. }
  13631. if (listeningCamera && audioEngine.canUseWebAudio) {
  13632. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13633. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13634. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13635. cameraDirection.normalize();
  13636. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13637. var i;
  13638. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13639. var sound = this.mainSoundTrack.soundCollection[i];
  13640. if (sound.useCustomAttenuation) {
  13641. sound.updateDistanceFromListener();
  13642. }
  13643. }
  13644. for (i = 0; i < this.soundTracks.length; i++) {
  13645. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13646. sound = this.soundTracks[i].soundCollection[j];
  13647. if (sound.useCustomAttenuation) {
  13648. sound.updateDistanceFromListener();
  13649. }
  13650. }
  13651. }
  13652. }
  13653. };
  13654. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13655. // Audio
  13656. get: function () {
  13657. return this._audioEnabled;
  13658. },
  13659. set: function (value) {
  13660. this._audioEnabled = value;
  13661. if (BABYLON.AudioEngine) {
  13662. if (this._audioEnabled) {
  13663. this._enableAudio();
  13664. }
  13665. else {
  13666. this._disableAudio();
  13667. }
  13668. }
  13669. },
  13670. enumerable: true,
  13671. configurable: true
  13672. });
  13673. Scene.prototype._disableAudio = function () {
  13674. var i;
  13675. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13676. this.mainSoundTrack.soundCollection[i].pause();
  13677. }
  13678. for (i = 0; i < this.soundTracks.length; i++) {
  13679. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13680. this.soundTracks[i].soundCollection[j].pause();
  13681. }
  13682. }
  13683. };
  13684. Scene.prototype._enableAudio = function () {
  13685. var i;
  13686. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13687. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13688. this.mainSoundTrack.soundCollection[i].play();
  13689. }
  13690. }
  13691. for (i = 0; i < this.soundTracks.length; i++) {
  13692. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13693. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13694. this.soundTracks[i].soundCollection[j].play();
  13695. }
  13696. }
  13697. }
  13698. };
  13699. Object.defineProperty(Scene.prototype, "headphone", {
  13700. get: function () {
  13701. return this._headphone;
  13702. },
  13703. set: function (value) {
  13704. this._headphone = value;
  13705. if (BABYLON.AudioEngine) {
  13706. if (this._headphone) {
  13707. this._switchAudioModeForHeadphones();
  13708. }
  13709. else {
  13710. this._switchAudioModeForNormalSpeakers();
  13711. }
  13712. }
  13713. },
  13714. enumerable: true,
  13715. configurable: true
  13716. });
  13717. Scene.prototype._switchAudioModeForHeadphones = function () {
  13718. this.mainSoundTrack.switchPanningModelToHRTF();
  13719. for (var i = 0; i < this.soundTracks.length; i++) {
  13720. this.soundTracks[i].switchPanningModelToHRTF();
  13721. }
  13722. };
  13723. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13724. this.mainSoundTrack.switchPanningModelToEqualPower();
  13725. for (var i = 0; i < this.soundTracks.length; i++) {
  13726. this.soundTracks[i].switchPanningModelToEqualPower();
  13727. }
  13728. };
  13729. Scene.prototype.enableDepthRenderer = function () {
  13730. if (this._depthRenderer) {
  13731. return this._depthRenderer;
  13732. }
  13733. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13734. return this._depthRenderer;
  13735. };
  13736. Scene.prototype.disableDepthRenderer = function () {
  13737. if (!this._depthRenderer) {
  13738. return;
  13739. }
  13740. this._depthRenderer.dispose();
  13741. this._depthRenderer = null;
  13742. };
  13743. Scene.prototype.freezeMaterials = function () {
  13744. for (var i = 0; i < this.materials.length; i++) {
  13745. this.materials[i].freeze();
  13746. }
  13747. };
  13748. Scene.prototype.unfreezeMaterials = function () {
  13749. for (var i = 0; i < this.materials.length; i++) {
  13750. this.materials[i].unfreeze();
  13751. }
  13752. };
  13753. Scene.prototype.dispose = function () {
  13754. this.beforeRender = null;
  13755. this.afterRender = null;
  13756. this.skeletons = [];
  13757. this._boundingBoxRenderer.dispose();
  13758. if (this._depthRenderer) {
  13759. this._depthRenderer.dispose();
  13760. }
  13761. // Debug layer
  13762. this.debugLayer.hide();
  13763. // Events
  13764. if (this.onDispose) {
  13765. this.onDispose();
  13766. }
  13767. this._onBeforeRenderCallbacks = [];
  13768. this._onAfterRenderCallbacks = [];
  13769. this.detachControl();
  13770. // Release sounds & sounds tracks
  13771. if (BABYLON.AudioEngine) {
  13772. this.disposeSounds();
  13773. }
  13774. // Detach cameras
  13775. var canvas = this._engine.getRenderingCanvas();
  13776. var index;
  13777. for (index = 0; index < this.cameras.length; index++) {
  13778. this.cameras[index].detachControl(canvas);
  13779. }
  13780. // Release lights
  13781. while (this.lights.length) {
  13782. this.lights[0].dispose();
  13783. }
  13784. // Release meshes
  13785. while (this.meshes.length) {
  13786. this.meshes[0].dispose(true);
  13787. }
  13788. // Release cameras
  13789. while (this.cameras.length) {
  13790. this.cameras[0].dispose();
  13791. }
  13792. // Release materials
  13793. while (this.materials.length) {
  13794. this.materials[0].dispose();
  13795. }
  13796. // Release particles
  13797. while (this.particleSystems.length) {
  13798. this.particleSystems[0].dispose();
  13799. }
  13800. // Release sprites
  13801. while (this.spriteManagers.length) {
  13802. this.spriteManagers[0].dispose();
  13803. }
  13804. // Release layers
  13805. while (this.layers.length) {
  13806. this.layers[0].dispose();
  13807. }
  13808. // Release textures
  13809. while (this.textures.length) {
  13810. this.textures[0].dispose();
  13811. }
  13812. // Post-processes
  13813. this.postProcessManager.dispose();
  13814. // Physics
  13815. if (this._physicsEngine) {
  13816. this.disablePhysicsEngine();
  13817. }
  13818. // Remove from engine
  13819. index = this._engine.scenes.indexOf(this);
  13820. if (index > -1) {
  13821. this._engine.scenes.splice(index, 1);
  13822. }
  13823. this._engine.wipeCaches();
  13824. };
  13825. // Release sounds & sounds tracks
  13826. Scene.prototype.disposeSounds = function () {
  13827. this.mainSoundTrack.dispose();
  13828. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13829. this.soundTracks[scIndex].dispose();
  13830. }
  13831. };
  13832. // Octrees
  13833. Scene.prototype.getWorldExtends = function () {
  13834. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13835. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13836. for (var index = 0; index < this.meshes.length; index++) {
  13837. var mesh = this.meshes[index];
  13838. mesh.computeWorldMatrix(true);
  13839. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13840. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13841. BABYLON.Tools.CheckExtends(minBox, min, max);
  13842. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13843. }
  13844. return {
  13845. min: min,
  13846. max: max
  13847. };
  13848. };
  13849. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13850. if (maxCapacity === void 0) { maxCapacity = 64; }
  13851. if (maxDepth === void 0) { maxDepth = 2; }
  13852. if (!this._selectionOctree) {
  13853. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13854. }
  13855. var worldExtends = this.getWorldExtends();
  13856. // Update octree
  13857. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13858. return this._selectionOctree;
  13859. };
  13860. // Picking
  13861. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13862. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13863. var engine = this._engine;
  13864. if (!camera) {
  13865. if (!this.activeCamera)
  13866. throw new Error("Active camera not set");
  13867. camera = this.activeCamera;
  13868. }
  13869. var cameraViewport = camera.viewport;
  13870. var viewport = cameraViewport.toGlobal(engine);
  13871. // Moving coordinates to local viewport world
  13872. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13873. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13874. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13875. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13876. };
  13877. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13878. var engine = this._engine;
  13879. if (!camera) {
  13880. if (!this.activeCamera)
  13881. throw new Error("Active camera not set");
  13882. camera = this.activeCamera;
  13883. }
  13884. var cameraViewport = camera.viewport;
  13885. var viewport = cameraViewport.toGlobal(engine);
  13886. var identity = BABYLON.Matrix.Identity();
  13887. // Moving coordinates to local viewport world
  13888. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13889. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13890. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13891. };
  13892. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13893. var pickingInfo = null;
  13894. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13895. var mesh = this.meshes[meshIndex];
  13896. if (predicate) {
  13897. if (!predicate(mesh)) {
  13898. continue;
  13899. }
  13900. }
  13901. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13902. continue;
  13903. }
  13904. var world = mesh.getWorldMatrix();
  13905. var ray = rayFunction(world);
  13906. var result = mesh.intersects(ray, fastCheck);
  13907. if (!result || !result.hit)
  13908. continue;
  13909. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13910. continue;
  13911. pickingInfo = result;
  13912. if (fastCheck) {
  13913. break;
  13914. }
  13915. }
  13916. return pickingInfo || new BABYLON.PickingInfo();
  13917. };
  13918. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13919. var pickingInfo = null;
  13920. camera = camera || this.activeCamera;
  13921. if (this.spriteManagers.length > 0) {
  13922. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13923. var spriteManager = this.spriteManagers[spriteIndex];
  13924. if (!spriteManager.isPickable) {
  13925. continue;
  13926. }
  13927. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13928. if (!result || !result.hit)
  13929. continue;
  13930. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13931. continue;
  13932. pickingInfo = result;
  13933. if (fastCheck) {
  13934. break;
  13935. }
  13936. }
  13937. }
  13938. return pickingInfo || new BABYLON.PickingInfo();
  13939. };
  13940. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13941. var _this = this;
  13942. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13943. /// <param name="x">X position on screen</param>
  13944. /// <param name="y">Y position on screen</param>
  13945. /// <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>
  13946. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13947. /// <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>
  13948. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13949. };
  13950. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13951. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13952. /// <param name="x">X position on screen</param>
  13953. /// <param name="y">Y position on screen</param>
  13954. /// <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>
  13955. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13956. /// <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>
  13957. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13958. };
  13959. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13960. var _this = this;
  13961. return this._internalPick(function (world) {
  13962. if (!_this._pickWithRayInverseMatrix) {
  13963. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13964. }
  13965. world.invertToRef(_this._pickWithRayInverseMatrix);
  13966. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13967. }, predicate, fastCheck);
  13968. };
  13969. Scene.prototype.setPointerOverMesh = function (mesh) {
  13970. if (this._pointerOverMesh === mesh) {
  13971. return;
  13972. }
  13973. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13974. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13975. }
  13976. this._pointerOverMesh = mesh;
  13977. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13978. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13979. }
  13980. };
  13981. Scene.prototype.getPointerOverMesh = function () {
  13982. return this._pointerOverMesh;
  13983. };
  13984. // Physics
  13985. Scene.prototype.getPhysicsEngine = function () {
  13986. return this._physicsEngine;
  13987. };
  13988. /**
  13989. * Enables physics to the current scene
  13990. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13991. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13992. * @return {boolean} was the physics engine initialized
  13993. */
  13994. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13995. if (this._physicsEngine) {
  13996. return true;
  13997. }
  13998. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13999. if (!this._physicsEngine.isSupported()) {
  14000. this._physicsEngine = null;
  14001. return false;
  14002. }
  14003. this._physicsEngine._initialize(gravity);
  14004. return true;
  14005. };
  14006. Scene.prototype.disablePhysicsEngine = function () {
  14007. if (!this._physicsEngine) {
  14008. return;
  14009. }
  14010. this._physicsEngine.dispose();
  14011. this._physicsEngine = undefined;
  14012. };
  14013. Scene.prototype.isPhysicsEnabled = function () {
  14014. return this._physicsEngine !== undefined;
  14015. };
  14016. /**
  14017. * Sets the gravity of the physics engine (and NOT of the scene)
  14018. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14019. */
  14020. Scene.prototype.setGravity = function (gravity) {
  14021. if (!this._physicsEngine) {
  14022. return;
  14023. }
  14024. this._physicsEngine._setGravity(gravity);
  14025. };
  14026. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14027. if (parts.parts) {
  14028. options = parts;
  14029. parts = parts.parts;
  14030. }
  14031. if (!this._physicsEngine) {
  14032. return null;
  14033. }
  14034. for (var index = 0; index < parts.length; index++) {
  14035. var mesh = parts[index].mesh;
  14036. mesh._physicImpostor = parts[index].impostor;
  14037. mesh._physicsMass = options.mass / parts.length;
  14038. mesh._physicsFriction = options.friction;
  14039. mesh._physicRestitution = options.restitution;
  14040. }
  14041. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14042. };
  14043. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14044. for (var index = 0; index < compound.parts.length; index++) {
  14045. var mesh = compound.parts[index].mesh;
  14046. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14047. this._physicsEngine._unregisterMesh(mesh);
  14048. }
  14049. };
  14050. // Misc.
  14051. Scene.prototype.createDefaultCameraOrLight = function () {
  14052. // Light
  14053. if (this.lights.length === 0) {
  14054. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14055. }
  14056. // Camera
  14057. if (!this.activeCamera) {
  14058. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14059. // Compute position
  14060. var worldExtends = this.getWorldExtends();
  14061. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14062. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14063. camera.setTarget(worldCenter);
  14064. this.activeCamera = camera;
  14065. }
  14066. };
  14067. // Tags
  14068. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14069. if (tagsQuery === undefined) {
  14070. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14071. return list;
  14072. }
  14073. var listByTags = [];
  14074. forEach = forEach || (function (item) { return; });
  14075. for (var i in list) {
  14076. var item = list[i];
  14077. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14078. listByTags.push(item);
  14079. forEach(item);
  14080. }
  14081. }
  14082. return listByTags;
  14083. };
  14084. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14085. return this._getByTags(this.meshes, tagsQuery, forEach);
  14086. };
  14087. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14088. return this._getByTags(this.cameras, tagsQuery, forEach);
  14089. };
  14090. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14091. return this._getByTags(this.lights, tagsQuery, forEach);
  14092. };
  14093. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14094. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14095. };
  14096. // Statics
  14097. Scene._FOGMODE_NONE = 0;
  14098. Scene._FOGMODE_EXP = 1;
  14099. Scene._FOGMODE_EXP2 = 2;
  14100. Scene._FOGMODE_LINEAR = 3;
  14101. Scene.MinDeltaTime = 1.0;
  14102. Scene.MaxDeltaTime = 1000.0;
  14103. return Scene;
  14104. })();
  14105. BABYLON.Scene = Scene;
  14106. })(BABYLON || (BABYLON = {}));
  14107. var BABYLON;
  14108. (function (BABYLON) {
  14109. var VertexBuffer = (function () {
  14110. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14111. if (engine instanceof BABYLON.Mesh) {
  14112. this._engine = engine.getScene().getEngine();
  14113. }
  14114. else {
  14115. this._engine = engine;
  14116. }
  14117. this._updatable = updatable;
  14118. this._data = data;
  14119. if (!postponeInternalCreation) {
  14120. this.create();
  14121. }
  14122. this._kind = kind;
  14123. if (stride) {
  14124. this._strideSize = stride;
  14125. return;
  14126. }
  14127. // Deduce stride from kind
  14128. switch (kind) {
  14129. case VertexBuffer.PositionKind:
  14130. this._strideSize = 3;
  14131. break;
  14132. case VertexBuffer.NormalKind:
  14133. this._strideSize = 3;
  14134. break;
  14135. case VertexBuffer.UVKind:
  14136. case VertexBuffer.UV2Kind:
  14137. case VertexBuffer.UV3Kind:
  14138. case VertexBuffer.UV4Kind:
  14139. case VertexBuffer.UV5Kind:
  14140. case VertexBuffer.UV6Kind:
  14141. this._strideSize = 2;
  14142. break;
  14143. case VertexBuffer.ColorKind:
  14144. this._strideSize = 4;
  14145. break;
  14146. case VertexBuffer.MatricesIndicesKind:
  14147. case VertexBuffer.MatricesIndicesExtraKind:
  14148. this._strideSize = 4;
  14149. break;
  14150. case VertexBuffer.MatricesWeightsKind:
  14151. case VertexBuffer.MatricesWeightsExtraKind:
  14152. this._strideSize = 4;
  14153. break;
  14154. }
  14155. }
  14156. // Properties
  14157. VertexBuffer.prototype.isUpdatable = function () {
  14158. return this._updatable;
  14159. };
  14160. VertexBuffer.prototype.getData = function () {
  14161. return this._data;
  14162. };
  14163. VertexBuffer.prototype.getBuffer = function () {
  14164. return this._buffer;
  14165. };
  14166. VertexBuffer.prototype.getStrideSize = function () {
  14167. return this._strideSize;
  14168. };
  14169. // Methods
  14170. VertexBuffer.prototype.create = function (data) {
  14171. if (!data && this._buffer) {
  14172. return; // nothing to do
  14173. }
  14174. data = data || this._data;
  14175. if (!this._buffer) {
  14176. if (this._updatable) {
  14177. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14178. }
  14179. else {
  14180. this._buffer = this._engine.createVertexBuffer(data);
  14181. }
  14182. }
  14183. if (this._updatable) {
  14184. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14185. this._data = data;
  14186. }
  14187. };
  14188. VertexBuffer.prototype.update = function (data) {
  14189. this.create(data);
  14190. };
  14191. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14192. if (!this._buffer) {
  14193. return;
  14194. }
  14195. if (this._updatable) {
  14196. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14197. this._data = null;
  14198. }
  14199. };
  14200. VertexBuffer.prototype.dispose = function () {
  14201. if (!this._buffer) {
  14202. return;
  14203. }
  14204. if (this._engine._releaseBuffer(this._buffer)) {
  14205. this._buffer = null;
  14206. }
  14207. };
  14208. Object.defineProperty(VertexBuffer, "PositionKind", {
  14209. get: function () {
  14210. return VertexBuffer._PositionKind;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Object.defineProperty(VertexBuffer, "NormalKind", {
  14216. get: function () {
  14217. return VertexBuffer._NormalKind;
  14218. },
  14219. enumerable: true,
  14220. configurable: true
  14221. });
  14222. Object.defineProperty(VertexBuffer, "UVKind", {
  14223. get: function () {
  14224. return VertexBuffer._UVKind;
  14225. },
  14226. enumerable: true,
  14227. configurable: true
  14228. });
  14229. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14230. get: function () {
  14231. return VertexBuffer._UV2Kind;
  14232. },
  14233. enumerable: true,
  14234. configurable: true
  14235. });
  14236. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14237. get: function () {
  14238. return VertexBuffer._UV3Kind;
  14239. },
  14240. enumerable: true,
  14241. configurable: true
  14242. });
  14243. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14244. get: function () {
  14245. return VertexBuffer._UV4Kind;
  14246. },
  14247. enumerable: true,
  14248. configurable: true
  14249. });
  14250. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14251. get: function () {
  14252. return VertexBuffer._UV5Kind;
  14253. },
  14254. enumerable: true,
  14255. configurable: true
  14256. });
  14257. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14258. get: function () {
  14259. return VertexBuffer._UV6Kind;
  14260. },
  14261. enumerable: true,
  14262. configurable: true
  14263. });
  14264. Object.defineProperty(VertexBuffer, "ColorKind", {
  14265. get: function () {
  14266. return VertexBuffer._ColorKind;
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14272. get: function () {
  14273. return VertexBuffer._MatricesIndicesKind;
  14274. },
  14275. enumerable: true,
  14276. configurable: true
  14277. });
  14278. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14279. get: function () {
  14280. return VertexBuffer._MatricesWeightsKind;
  14281. },
  14282. enumerable: true,
  14283. configurable: true
  14284. });
  14285. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14286. get: function () {
  14287. return VertexBuffer._MatricesIndicesExtraKind;
  14288. },
  14289. enumerable: true,
  14290. configurable: true
  14291. });
  14292. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14293. get: function () {
  14294. return VertexBuffer._MatricesWeightsExtraKind;
  14295. },
  14296. enumerable: true,
  14297. configurable: true
  14298. });
  14299. // Enums
  14300. VertexBuffer._PositionKind = "position";
  14301. VertexBuffer._NormalKind = "normal";
  14302. VertexBuffer._UVKind = "uv";
  14303. VertexBuffer._UV2Kind = "uv2";
  14304. VertexBuffer._UV3Kind = "uv3";
  14305. VertexBuffer._UV4Kind = "uv4";
  14306. VertexBuffer._UV5Kind = "uv5";
  14307. VertexBuffer._UV6Kind = "uv6";
  14308. VertexBuffer._ColorKind = "color";
  14309. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14310. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14311. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14312. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14313. return VertexBuffer;
  14314. })();
  14315. BABYLON.VertexBuffer = VertexBuffer;
  14316. })(BABYLON || (BABYLON = {}));
  14317. var BABYLON;
  14318. (function (BABYLON) {
  14319. /**
  14320. * Creates an instance based on a source mesh.
  14321. */
  14322. var InstancedMesh = (function (_super) {
  14323. __extends(InstancedMesh, _super);
  14324. function InstancedMesh(name, source) {
  14325. _super.call(this, name, source.getScene());
  14326. source.instances.push(this);
  14327. this._sourceMesh = source;
  14328. this.position.copyFrom(source.position);
  14329. this.rotation.copyFrom(source.rotation);
  14330. this.scaling.copyFrom(source.scaling);
  14331. if (source.rotationQuaternion) {
  14332. this.rotationQuaternion = source.rotationQuaternion.clone();
  14333. }
  14334. this.infiniteDistance = source.infiniteDistance;
  14335. this.setPivotMatrix(source.getPivotMatrix());
  14336. this.refreshBoundingInfo();
  14337. this._syncSubMeshes();
  14338. }
  14339. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14340. // Methods
  14341. get: function () {
  14342. return this._sourceMesh.receiveShadows;
  14343. },
  14344. enumerable: true,
  14345. configurable: true
  14346. });
  14347. Object.defineProperty(InstancedMesh.prototype, "material", {
  14348. get: function () {
  14349. return this._sourceMesh.material;
  14350. },
  14351. enumerable: true,
  14352. configurable: true
  14353. });
  14354. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14355. get: function () {
  14356. return this._sourceMesh.visibility;
  14357. },
  14358. enumerable: true,
  14359. configurable: true
  14360. });
  14361. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14362. get: function () {
  14363. return this._sourceMesh.skeleton;
  14364. },
  14365. enumerable: true,
  14366. configurable: true
  14367. });
  14368. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14369. get: function () {
  14370. return this._sourceMesh.renderingGroupId;
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. InstancedMesh.prototype.getTotalVertices = function () {
  14376. return this._sourceMesh.getTotalVertices();
  14377. };
  14378. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14379. get: function () {
  14380. return this._sourceMesh;
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14386. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14387. };
  14388. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14389. return this._sourceMesh.isVerticesDataPresent(kind);
  14390. };
  14391. InstancedMesh.prototype.getIndices = function () {
  14392. return this._sourceMesh.getIndices();
  14393. };
  14394. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14395. get: function () {
  14396. return this._sourceMesh._positions;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14402. var meshBB = this._sourceMesh.getBoundingInfo();
  14403. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14404. this._updateBoundingInfo();
  14405. };
  14406. InstancedMesh.prototype._preActivate = function () {
  14407. if (this._currentLOD) {
  14408. this._currentLOD._preActivate();
  14409. }
  14410. };
  14411. InstancedMesh.prototype._activate = function (renderId) {
  14412. if (this._currentLOD) {
  14413. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14414. }
  14415. };
  14416. InstancedMesh.prototype.getLOD = function (camera) {
  14417. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14418. if (this._currentLOD === this.sourceMesh) {
  14419. return this;
  14420. }
  14421. return this._currentLOD;
  14422. };
  14423. InstancedMesh.prototype._syncSubMeshes = function () {
  14424. this.releaseSubMeshes();
  14425. if (this._sourceMesh.subMeshes) {
  14426. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14427. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14428. }
  14429. }
  14430. };
  14431. InstancedMesh.prototype._generatePointsArray = function () {
  14432. return this._sourceMesh._generatePointsArray();
  14433. };
  14434. // Clone
  14435. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14436. var result = this._sourceMesh.createInstance(name);
  14437. // Deep copy
  14438. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14439. // Bounding info
  14440. this.refreshBoundingInfo();
  14441. // Parent
  14442. if (newParent) {
  14443. result.parent = newParent;
  14444. }
  14445. if (!doNotCloneChildren) {
  14446. // Children
  14447. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14448. var mesh = this.getScene().meshes[index];
  14449. if (mesh.parent === this) {
  14450. mesh.clone(mesh.name, result);
  14451. }
  14452. }
  14453. }
  14454. result.computeWorldMatrix(true);
  14455. return result;
  14456. };
  14457. // Dispoe
  14458. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14459. // Remove from mesh
  14460. var index = this._sourceMesh.instances.indexOf(this);
  14461. this._sourceMesh.instances.splice(index, 1);
  14462. _super.prototype.dispose.call(this, doNotRecurse);
  14463. };
  14464. return InstancedMesh;
  14465. })(BABYLON.AbstractMesh);
  14466. BABYLON.InstancedMesh = InstancedMesh;
  14467. })(BABYLON || (BABYLON = {}));
  14468. var BABYLON;
  14469. (function (BABYLON) {
  14470. var _InstancesBatch = (function () {
  14471. function _InstancesBatch() {
  14472. this.mustReturn = false;
  14473. this.visibleInstances = new Array();
  14474. this.renderSelf = new Array();
  14475. }
  14476. return _InstancesBatch;
  14477. })();
  14478. BABYLON._InstancesBatch = _InstancesBatch;
  14479. var Mesh = (function (_super) {
  14480. __extends(Mesh, _super);
  14481. /**
  14482. * @constructor
  14483. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14484. * @param {Scene} scene - The scene to add this mesh to.
  14485. * @param {Node} parent - The parent of this mesh, if it has one
  14486. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14487. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14488. * When false, achieved by calling a clone(), also passing False.
  14489. * This will make creation of children, recursive.
  14490. */
  14491. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14492. if (parent === void 0) { parent = null; }
  14493. _super.call(this, name, scene);
  14494. // Members
  14495. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14496. this.instances = new Array();
  14497. this._LODLevels = new Array();
  14498. this._onBeforeRenderCallbacks = new Array();
  14499. this._onAfterRenderCallbacks = new Array();
  14500. this._visibleInstances = {};
  14501. this._renderIdForInstances = new Array();
  14502. this._batchCache = new _InstancesBatch();
  14503. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14504. this._sideOrientation = Mesh._DEFAULTSIDE;
  14505. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14506. if (source) {
  14507. // Geometry
  14508. if (source._geometry) {
  14509. source._geometry.applyToMesh(this);
  14510. }
  14511. // Deep copy
  14512. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14513. this.id = name + "." + source.id;
  14514. // Material
  14515. this.material = source.material;
  14516. var index;
  14517. if (!doNotCloneChildren) {
  14518. // Children
  14519. for (index = 0; index < scene.meshes.length; index++) {
  14520. var mesh = scene.meshes[index];
  14521. if (mesh.parent === source) {
  14522. // doNotCloneChildren is always going to be False
  14523. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14524. }
  14525. }
  14526. }
  14527. // Particles
  14528. for (index = 0; index < scene.particleSystems.length; index++) {
  14529. var system = scene.particleSystems[index];
  14530. if (system.emitter === source) {
  14531. system.clone(system.name, this);
  14532. }
  14533. }
  14534. this.computeWorldMatrix(true);
  14535. }
  14536. // Parent
  14537. if (parent !== null) {
  14538. this.parent = parent;
  14539. }
  14540. }
  14541. Object.defineProperty(Mesh, "FRONTSIDE", {
  14542. get: function () {
  14543. return Mesh._FRONTSIDE;
  14544. },
  14545. enumerable: true,
  14546. configurable: true
  14547. });
  14548. Object.defineProperty(Mesh, "BACKSIDE", {
  14549. get: function () {
  14550. return Mesh._BACKSIDE;
  14551. },
  14552. enumerable: true,
  14553. configurable: true
  14554. });
  14555. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14556. get: function () {
  14557. return Mesh._DOUBLESIDE;
  14558. },
  14559. enumerable: true,
  14560. configurable: true
  14561. });
  14562. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14563. get: function () {
  14564. return Mesh._DEFAULTSIDE;
  14565. },
  14566. enumerable: true,
  14567. configurable: true
  14568. });
  14569. Object.defineProperty(Mesh, "NO_CAP", {
  14570. get: function () {
  14571. return Mesh._NO_CAP;
  14572. },
  14573. enumerable: true,
  14574. configurable: true
  14575. });
  14576. Object.defineProperty(Mesh, "CAP_START", {
  14577. get: function () {
  14578. return Mesh._CAP_START;
  14579. },
  14580. enumerable: true,
  14581. configurable: true
  14582. });
  14583. Object.defineProperty(Mesh, "CAP_END", {
  14584. get: function () {
  14585. return Mesh._CAP_END;
  14586. },
  14587. enumerable: true,
  14588. configurable: true
  14589. });
  14590. Object.defineProperty(Mesh, "CAP_ALL", {
  14591. get: function () {
  14592. return Mesh._CAP_ALL;
  14593. },
  14594. enumerable: true,
  14595. configurable: true
  14596. });
  14597. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14598. // Methods
  14599. get: function () {
  14600. return this._LODLevels.length > 0;
  14601. },
  14602. enumerable: true,
  14603. configurable: true
  14604. });
  14605. Mesh.prototype._sortLODLevels = function () {
  14606. this._LODLevels.sort(function (a, b) {
  14607. if (a.distance < b.distance) {
  14608. return 1;
  14609. }
  14610. if (a.distance > b.distance) {
  14611. return -1;
  14612. }
  14613. return 0;
  14614. });
  14615. };
  14616. /**
  14617. * Add a mesh as LOD level triggered at the given distance.
  14618. * @param {number} distance - the distance from the center of the object to show this level
  14619. * @param {Mesh} mesh - the mesh to be added as LOD level
  14620. * @return {Mesh} this mesh (for chaining)
  14621. */
  14622. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14623. if (mesh && mesh._masterMesh) {
  14624. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14625. return this;
  14626. }
  14627. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14628. this._LODLevels.push(level);
  14629. if (mesh) {
  14630. mesh._masterMesh = this;
  14631. }
  14632. this._sortLODLevels();
  14633. return this;
  14634. };
  14635. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14636. for (var index = 0; index < this._LODLevels.length; index++) {
  14637. var level = this._LODLevels[index];
  14638. if (level.distance === distance) {
  14639. return level.mesh;
  14640. }
  14641. }
  14642. return null;
  14643. };
  14644. /**
  14645. * Remove a mesh from the LOD array
  14646. * @param {Mesh} mesh - the mesh to be removed.
  14647. * @return {Mesh} this mesh (for chaining)
  14648. */
  14649. Mesh.prototype.removeLODLevel = function (mesh) {
  14650. for (var index = 0; index < this._LODLevels.length; index++) {
  14651. if (this._LODLevels[index].mesh === mesh) {
  14652. this._LODLevels.splice(index, 1);
  14653. if (mesh) {
  14654. mesh._masterMesh = null;
  14655. }
  14656. }
  14657. }
  14658. this._sortLODLevels();
  14659. return this;
  14660. };
  14661. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14662. if (!this._LODLevels || this._LODLevels.length === 0) {
  14663. return this;
  14664. }
  14665. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14666. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14667. if (this.onLODLevelSelection) {
  14668. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14669. }
  14670. return this;
  14671. }
  14672. for (var index = 0; index < this._LODLevels.length; index++) {
  14673. var level = this._LODLevels[index];
  14674. if (level.distance < distanceToCamera) {
  14675. if (level.mesh) {
  14676. level.mesh._preActivate();
  14677. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14678. }
  14679. if (this.onLODLevelSelection) {
  14680. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14681. }
  14682. return level.mesh;
  14683. }
  14684. }
  14685. if (this.onLODLevelSelection) {
  14686. this.onLODLevelSelection(distanceToCamera, this, this);
  14687. }
  14688. return this;
  14689. };
  14690. Object.defineProperty(Mesh.prototype, "geometry", {
  14691. get: function () {
  14692. return this._geometry;
  14693. },
  14694. enumerable: true,
  14695. configurable: true
  14696. });
  14697. Mesh.prototype.getTotalVertices = function () {
  14698. if (!this._geometry) {
  14699. return 0;
  14700. }
  14701. return this._geometry.getTotalVertices();
  14702. };
  14703. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14704. if (!this._geometry) {
  14705. return null;
  14706. }
  14707. return this._geometry.getVerticesData(kind, copyWhenShared);
  14708. };
  14709. Mesh.prototype.getVertexBuffer = function (kind) {
  14710. if (!this._geometry) {
  14711. return undefined;
  14712. }
  14713. return this._geometry.getVertexBuffer(kind);
  14714. };
  14715. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14716. if (!this._geometry) {
  14717. if (this._delayInfo) {
  14718. return this._delayInfo.indexOf(kind) !== -1;
  14719. }
  14720. return false;
  14721. }
  14722. return this._geometry.isVerticesDataPresent(kind);
  14723. };
  14724. Mesh.prototype.getVerticesDataKinds = function () {
  14725. if (!this._geometry) {
  14726. var result = [];
  14727. if (this._delayInfo) {
  14728. for (var kind in this._delayInfo) {
  14729. result.push(kind);
  14730. }
  14731. }
  14732. return result;
  14733. }
  14734. return this._geometry.getVerticesDataKinds();
  14735. };
  14736. Mesh.prototype.getTotalIndices = function () {
  14737. if (!this._geometry) {
  14738. return 0;
  14739. }
  14740. return this._geometry.getTotalIndices();
  14741. };
  14742. Mesh.prototype.getIndices = function (copyWhenShared) {
  14743. if (!this._geometry) {
  14744. return [];
  14745. }
  14746. return this._geometry.getIndices(copyWhenShared);
  14747. };
  14748. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14749. get: function () {
  14750. return this._masterMesh !== null && this._masterMesh !== undefined;
  14751. },
  14752. enumerable: true,
  14753. configurable: true
  14754. });
  14755. Mesh.prototype.isReady = function () {
  14756. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14757. return false;
  14758. }
  14759. return _super.prototype.isReady.call(this);
  14760. };
  14761. Mesh.prototype.isDisposed = function () {
  14762. return this._isDisposed;
  14763. };
  14764. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14765. get: function () {
  14766. return this._sideOrientation;
  14767. },
  14768. set: function (sideO) {
  14769. this._sideOrientation = sideO;
  14770. },
  14771. enumerable: true,
  14772. configurable: true
  14773. });
  14774. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14775. get: function () {
  14776. return this._areNormalsFrozen;
  14777. },
  14778. enumerable: true,
  14779. configurable: true
  14780. });
  14781. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14782. Mesh.prototype.freezeNormals = function () {
  14783. this._areNormalsFrozen = true;
  14784. };
  14785. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14786. Mesh.prototype.unfreezeNormals = function () {
  14787. this._areNormalsFrozen = false;
  14788. };
  14789. // Methods
  14790. Mesh.prototype._preActivate = function () {
  14791. var sceneRenderId = this.getScene().getRenderId();
  14792. if (this._preActivateId === sceneRenderId) {
  14793. return;
  14794. }
  14795. this._preActivateId = sceneRenderId;
  14796. this._visibleInstances = null;
  14797. };
  14798. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14799. if (!this._visibleInstances) {
  14800. this._visibleInstances = {};
  14801. this._visibleInstances.defaultRenderId = renderId;
  14802. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14803. }
  14804. if (!this._visibleInstances[renderId]) {
  14805. this._visibleInstances[renderId] = new Array();
  14806. }
  14807. this._visibleInstances[renderId].push(instance);
  14808. };
  14809. Mesh.prototype.refreshBoundingInfo = function () {
  14810. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14811. if (data) {
  14812. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14813. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14814. }
  14815. if (this.subMeshes) {
  14816. for (var index = 0; index < this.subMeshes.length; index++) {
  14817. this.subMeshes[index].refreshBoundingInfo();
  14818. }
  14819. }
  14820. this._updateBoundingInfo();
  14821. };
  14822. Mesh.prototype._createGlobalSubMesh = function () {
  14823. var totalVertices = this.getTotalVertices();
  14824. if (!totalVertices || !this.getIndices()) {
  14825. return null;
  14826. }
  14827. this.releaseSubMeshes();
  14828. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14829. };
  14830. Mesh.prototype.subdivide = function (count) {
  14831. if (count < 1) {
  14832. return;
  14833. }
  14834. var totalIndices = this.getTotalIndices();
  14835. var subdivisionSize = (totalIndices / count) | 0;
  14836. var offset = 0;
  14837. // Ensure that subdivisionSize is a multiple of 3
  14838. while (subdivisionSize % 3 !== 0) {
  14839. subdivisionSize++;
  14840. }
  14841. this.releaseSubMeshes();
  14842. for (var index = 0; index < count; index++) {
  14843. if (offset >= totalIndices) {
  14844. break;
  14845. }
  14846. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14847. offset += subdivisionSize;
  14848. }
  14849. this.synchronizeInstances();
  14850. };
  14851. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14852. if (!this._geometry) {
  14853. var vertexData = new BABYLON.VertexData();
  14854. vertexData.set(data, kind);
  14855. var scene = this.getScene();
  14856. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14857. }
  14858. else {
  14859. this._geometry.setVerticesData(kind, data, updatable, stride);
  14860. }
  14861. };
  14862. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14863. if (!this._geometry) {
  14864. return;
  14865. }
  14866. if (!makeItUnique) {
  14867. this._geometry.updateVerticesData(kind, data, updateExtends);
  14868. }
  14869. else {
  14870. this.makeGeometryUnique();
  14871. this.updateVerticesData(kind, data, updateExtends, false);
  14872. }
  14873. };
  14874. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14875. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14876. if (!this._geometry) {
  14877. return;
  14878. }
  14879. if (!makeItUnique) {
  14880. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14881. }
  14882. else {
  14883. this.makeGeometryUnique();
  14884. this.updateVerticesDataDirectly(kind, data, offset, false);
  14885. }
  14886. };
  14887. // Mesh positions update function :
  14888. // updates the mesh positions according to the positionFunction returned values.
  14889. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14890. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14891. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14892. if (computeNormals === void 0) { computeNormals = true; }
  14893. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14894. positionFunction(positions);
  14895. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14896. if (computeNormals) {
  14897. var indices = this.getIndices();
  14898. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14899. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14900. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14901. }
  14902. };
  14903. Mesh.prototype.makeGeometryUnique = function () {
  14904. if (!this._geometry) {
  14905. return;
  14906. }
  14907. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14908. geometry.applyToMesh(this);
  14909. };
  14910. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14911. if (!this._geometry) {
  14912. var vertexData = new BABYLON.VertexData();
  14913. vertexData.indices = indices;
  14914. var scene = this.getScene();
  14915. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14916. }
  14917. else {
  14918. this._geometry.setIndices(indices, totalVertices);
  14919. }
  14920. };
  14921. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14922. var engine = this.getScene().getEngine();
  14923. // Wireframe
  14924. var indexToBind;
  14925. if (this._unIndexed) {
  14926. indexToBind = null;
  14927. }
  14928. else {
  14929. switch (fillMode) {
  14930. case BABYLON.Material.PointFillMode:
  14931. indexToBind = null;
  14932. break;
  14933. case BABYLON.Material.WireFrameFillMode:
  14934. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14935. break;
  14936. default:
  14937. case BABYLON.Material.TriangleFillMode:
  14938. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  14939. break;
  14940. }
  14941. }
  14942. // VBOs
  14943. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14944. };
  14945. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14946. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14947. return;
  14948. }
  14949. var engine = this.getScene().getEngine();
  14950. // Draw order
  14951. switch (fillMode) {
  14952. case BABYLON.Material.PointFillMode:
  14953. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14954. break;
  14955. case BABYLON.Material.WireFrameFillMode:
  14956. if (this._unIndexed) {
  14957. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14958. }
  14959. else {
  14960. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14961. }
  14962. break;
  14963. default:
  14964. if (this._unIndexed) {
  14965. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14966. }
  14967. else {
  14968. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14969. }
  14970. }
  14971. };
  14972. Mesh.prototype.registerBeforeRender = function (func) {
  14973. this._onBeforeRenderCallbacks.push(func);
  14974. };
  14975. Mesh.prototype.unregisterBeforeRender = function (func) {
  14976. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14977. if (index > -1) {
  14978. this._onBeforeRenderCallbacks.splice(index, 1);
  14979. }
  14980. };
  14981. Mesh.prototype.registerAfterRender = function (func) {
  14982. this._onAfterRenderCallbacks.push(func);
  14983. };
  14984. Mesh.prototype.unregisterAfterRender = function (func) {
  14985. var index = this._onAfterRenderCallbacks.indexOf(func);
  14986. if (index > -1) {
  14987. this._onAfterRenderCallbacks.splice(index, 1);
  14988. }
  14989. };
  14990. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14991. var scene = this.getScene();
  14992. this._batchCache.mustReturn = false;
  14993. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14994. this._batchCache.visibleInstances[subMeshId] = null;
  14995. if (this._visibleInstances) {
  14996. var currentRenderId = scene.getRenderId();
  14997. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14998. var selfRenderId = this._renderId;
  14999. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15000. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15001. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15002. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15003. }
  15004. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15005. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15006. this._batchCache.mustReturn = true;
  15007. return this._batchCache;
  15008. }
  15009. if (currentRenderId !== selfRenderId) {
  15010. this._batchCache.renderSelf[subMeshId] = false;
  15011. }
  15012. }
  15013. this._renderIdForInstances[subMeshId] = currentRenderId;
  15014. }
  15015. return this._batchCache;
  15016. };
  15017. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15018. var visibleInstances = batch.visibleInstances[subMesh._id];
  15019. var matricesCount = visibleInstances.length + 1;
  15020. var bufferSize = matricesCount * 16 * 4;
  15021. while (this._instancesBufferSize < bufferSize) {
  15022. this._instancesBufferSize *= 2;
  15023. }
  15024. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15025. if (this._worldMatricesInstancesBuffer) {
  15026. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15027. }
  15028. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15029. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15030. }
  15031. var offset = 0;
  15032. var instancesCount = 0;
  15033. var world = this.getWorldMatrix();
  15034. if (batch.renderSelf[subMesh._id]) {
  15035. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15036. offset += 16;
  15037. instancesCount++;
  15038. }
  15039. if (visibleInstances) {
  15040. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15041. var instance = visibleInstances[instanceIndex];
  15042. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15043. offset += 16;
  15044. instancesCount++;
  15045. }
  15046. }
  15047. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15048. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15049. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15050. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15051. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15052. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15053. this._draw(subMesh, fillMode, instancesCount);
  15054. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15055. };
  15056. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15057. var scene = this.getScene();
  15058. var engine = scene.getEngine();
  15059. if (hardwareInstancedRendering) {
  15060. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15061. }
  15062. else {
  15063. if (batch.renderSelf[subMesh._id]) {
  15064. // Draw
  15065. if (onBeforeDraw) {
  15066. onBeforeDraw(false, this.getWorldMatrix());
  15067. }
  15068. this._draw(subMesh, fillMode);
  15069. }
  15070. if (batch.visibleInstances[subMesh._id]) {
  15071. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15072. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15073. // World
  15074. var world = instance.getWorldMatrix();
  15075. if (onBeforeDraw) {
  15076. onBeforeDraw(true, world);
  15077. }
  15078. // Draw
  15079. this._draw(subMesh, fillMode);
  15080. }
  15081. }
  15082. }
  15083. };
  15084. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15085. var scene = this.getScene();
  15086. // Managing instances
  15087. var batch = this._getInstancesRenderList(subMesh._id);
  15088. if (batch.mustReturn) {
  15089. return;
  15090. }
  15091. // Checking geometry state
  15092. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15093. return;
  15094. }
  15095. var callbackIndex;
  15096. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15097. this._onBeforeRenderCallbacks[callbackIndex](this);
  15098. }
  15099. var engine = scene.getEngine();
  15100. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15101. // Material
  15102. var effectiveMaterial = subMesh.getMaterial();
  15103. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15104. return;
  15105. }
  15106. // Outline - step 1
  15107. var savedDepthWrite = engine.getDepthWrite();
  15108. if (this.renderOutline) {
  15109. engine.setDepthWrite(false);
  15110. scene.getOutlineRenderer().render(subMesh, batch);
  15111. engine.setDepthWrite(savedDepthWrite);
  15112. }
  15113. effectiveMaterial._preBind();
  15114. var effect = effectiveMaterial.getEffect();
  15115. // Bind
  15116. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15117. this._bind(subMesh, effect, fillMode);
  15118. var world = this.getWorldMatrix();
  15119. effectiveMaterial.bind(world, this);
  15120. // Alpha mode
  15121. if (enableAlphaMode) {
  15122. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15123. }
  15124. // Draw
  15125. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15126. if (isInstance) {
  15127. effectiveMaterial.bindOnlyWorldMatrix(world);
  15128. }
  15129. });
  15130. // Unbind
  15131. effectiveMaterial.unbind();
  15132. // Outline - step 2
  15133. if (this.renderOutline && savedDepthWrite) {
  15134. engine.setDepthWrite(true);
  15135. engine.setColorWrite(false);
  15136. scene.getOutlineRenderer().render(subMesh, batch);
  15137. engine.setColorWrite(true);
  15138. }
  15139. // Overlay
  15140. if (this.renderOverlay) {
  15141. var currentMode = engine.getAlphaMode();
  15142. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15143. scene.getOutlineRenderer().render(subMesh, batch, true);
  15144. engine.setAlphaMode(currentMode);
  15145. }
  15146. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15147. this._onAfterRenderCallbacks[callbackIndex](this);
  15148. }
  15149. };
  15150. Mesh.prototype.getEmittedParticleSystems = function () {
  15151. var results = new Array();
  15152. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15153. var particleSystem = this.getScene().particleSystems[index];
  15154. if (particleSystem.emitter === this) {
  15155. results.push(particleSystem);
  15156. }
  15157. }
  15158. return results;
  15159. };
  15160. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15161. var results = new Array();
  15162. var descendants = this.getDescendants();
  15163. descendants.push(this);
  15164. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15165. var particleSystem = this.getScene().particleSystems[index];
  15166. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15167. results.push(particleSystem);
  15168. }
  15169. }
  15170. return results;
  15171. };
  15172. Mesh.prototype.getChildren = function () {
  15173. var results = [];
  15174. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15175. var mesh = this.getScene().meshes[index];
  15176. if (mesh.parent === this) {
  15177. results.push(mesh);
  15178. }
  15179. }
  15180. return results;
  15181. };
  15182. Mesh.prototype._checkDelayState = function () {
  15183. var _this = this;
  15184. var that = this;
  15185. var scene = this.getScene();
  15186. if (this._geometry) {
  15187. this._geometry.load(scene);
  15188. }
  15189. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15190. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15191. scene._addPendingData(that);
  15192. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15193. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15194. if (data instanceof ArrayBuffer) {
  15195. _this._delayLoadingFunction(data, _this);
  15196. }
  15197. else {
  15198. _this._delayLoadingFunction(JSON.parse(data), _this);
  15199. }
  15200. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15201. scene._removePendingData(_this);
  15202. }, function () { }, scene.database, getBinaryData);
  15203. }
  15204. };
  15205. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15207. return false;
  15208. }
  15209. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15210. return false;
  15211. }
  15212. this._checkDelayState();
  15213. return true;
  15214. };
  15215. Mesh.prototype.setMaterialByID = function (id) {
  15216. var materials = this.getScene().materials;
  15217. var index;
  15218. for (index = 0; index < materials.length; index++) {
  15219. if (materials[index].id === id) {
  15220. this.material = materials[index];
  15221. return;
  15222. }
  15223. }
  15224. // Multi
  15225. var multiMaterials = this.getScene().multiMaterials;
  15226. for (index = 0; index < multiMaterials.length; index++) {
  15227. if (multiMaterials[index].id === id) {
  15228. this.material = multiMaterials[index];
  15229. return;
  15230. }
  15231. }
  15232. };
  15233. Mesh.prototype.getAnimatables = function () {
  15234. var results = [];
  15235. if (this.material) {
  15236. results.push(this.material);
  15237. }
  15238. if (this.skeleton) {
  15239. results.push(this.skeleton);
  15240. }
  15241. return results;
  15242. };
  15243. // Geometry
  15244. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15245. // Position
  15246. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15247. return;
  15248. }
  15249. this._resetPointsArrayCache();
  15250. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15251. var temp = [];
  15252. var index;
  15253. for (index = 0; index < data.length; index += 3) {
  15254. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15255. }
  15256. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15257. // Normals
  15258. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15259. return;
  15260. }
  15261. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15262. temp = [];
  15263. for (index = 0; index < data.length; index += 3) {
  15264. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15265. }
  15266. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15267. // flip faces?
  15268. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15269. this.flipFaces();
  15270. }
  15271. };
  15272. // Will apply current transform to mesh and reset world matrix
  15273. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15274. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15275. this.scaling.copyFromFloats(1, 1, 1);
  15276. this.position.copyFromFloats(0, 0, 0);
  15277. this.rotation.copyFromFloats(0, 0, 0);
  15278. //only if quaternion is already set
  15279. if (this.rotationQuaternion) {
  15280. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15281. }
  15282. this._worldMatrix = BABYLON.Matrix.Identity();
  15283. };
  15284. // Cache
  15285. Mesh.prototype._resetPointsArrayCache = function () {
  15286. this._positions = null;
  15287. };
  15288. Mesh.prototype._generatePointsArray = function () {
  15289. if (this._positions)
  15290. return true;
  15291. this._positions = [];
  15292. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15293. if (!data) {
  15294. return false;
  15295. }
  15296. for (var index = 0; index < data.length; index += 3) {
  15297. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15298. }
  15299. return true;
  15300. };
  15301. // Clone
  15302. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15303. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15304. };
  15305. // Dispose
  15306. Mesh.prototype.dispose = function (doNotRecurse) {
  15307. if (this._geometry) {
  15308. this._geometry.releaseForMesh(this, true);
  15309. }
  15310. // Instances
  15311. if (this._worldMatricesInstancesBuffer) {
  15312. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15313. this._worldMatricesInstancesBuffer = null;
  15314. }
  15315. while (this.instances.length) {
  15316. this.instances[0].dispose();
  15317. }
  15318. _super.prototype.dispose.call(this, doNotRecurse);
  15319. };
  15320. // Geometric tools
  15321. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15322. var _this = this;
  15323. var scene = this.getScene();
  15324. var onload = function (img) {
  15325. // Getting height map data
  15326. var canvas = document.createElement("canvas");
  15327. var context = canvas.getContext("2d");
  15328. var heightMapWidth = img.width;
  15329. var heightMapHeight = img.height;
  15330. canvas.width = heightMapWidth;
  15331. canvas.height = heightMapHeight;
  15332. context.drawImage(img, 0, 0);
  15333. // Create VertexData from map data
  15334. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15335. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15336. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15337. //execute success callback, if set
  15338. if (onSuccess) {
  15339. onSuccess(_this);
  15340. }
  15341. };
  15342. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15343. };
  15344. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15345. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15346. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15347. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15348. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15349. return;
  15350. }
  15351. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15352. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15353. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15354. var position = BABYLON.Vector3.Zero();
  15355. var normal = BABYLON.Vector3.Zero();
  15356. var uv = BABYLON.Vector2.Zero();
  15357. for (var index = 0; index < positions.length; index += 3) {
  15358. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15359. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15360. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15361. // Compute height
  15362. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15363. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15364. var pos = (u + v * heightMapWidth) * 4;
  15365. var r = buffer[pos] / 255.0;
  15366. var g = buffer[pos + 1] / 255.0;
  15367. var b = buffer[pos + 2] / 255.0;
  15368. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15369. normal.normalize();
  15370. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15371. position = position.add(normal);
  15372. position.toArray(positions, index);
  15373. }
  15374. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15375. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15376. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15377. };
  15378. Mesh.prototype.convertToFlatShadedMesh = function () {
  15379. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15380. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15381. var kinds = this.getVerticesDataKinds();
  15382. var vbs = [];
  15383. var data = [];
  15384. var newdata = [];
  15385. var updatableNormals = false;
  15386. var kindIndex;
  15387. var kind;
  15388. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15389. kind = kinds[kindIndex];
  15390. var vertexBuffer = this.getVertexBuffer(kind);
  15391. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15392. updatableNormals = vertexBuffer.isUpdatable();
  15393. kinds.splice(kindIndex, 1);
  15394. kindIndex--;
  15395. continue;
  15396. }
  15397. vbs[kind] = vertexBuffer;
  15398. data[kind] = vbs[kind].getData();
  15399. newdata[kind] = [];
  15400. }
  15401. // Save previous submeshes
  15402. var previousSubmeshes = this.subMeshes.slice(0);
  15403. var indices = this.getIndices();
  15404. var totalIndices = this.getTotalIndices();
  15405. // Generating unique vertices per face
  15406. var index;
  15407. for (index = 0; index < totalIndices; index++) {
  15408. var vertexIndex = indices[index];
  15409. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15410. kind = kinds[kindIndex];
  15411. var stride = vbs[kind].getStrideSize();
  15412. for (var offset = 0; offset < stride; offset++) {
  15413. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15414. }
  15415. }
  15416. }
  15417. // Updating faces & normal
  15418. var normals = [];
  15419. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15420. for (index = 0; index < totalIndices; index += 3) {
  15421. indices[index] = index;
  15422. indices[index + 1] = index + 1;
  15423. indices[index + 2] = index + 2;
  15424. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15425. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15426. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15427. var p1p2 = p1.subtract(p2);
  15428. var p3p2 = p3.subtract(p2);
  15429. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15430. // Store same normals for every vertex
  15431. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15432. normals.push(normal.x);
  15433. normals.push(normal.y);
  15434. normals.push(normal.z);
  15435. }
  15436. }
  15437. this.setIndices(indices);
  15438. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15439. // Updating vertex buffers
  15440. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15441. kind = kinds[kindIndex];
  15442. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15443. }
  15444. // Updating submeshes
  15445. this.releaseSubMeshes();
  15446. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15447. var previousOne = previousSubmeshes[submeshIndex];
  15448. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15449. }
  15450. this.synchronizeInstances();
  15451. };
  15452. Mesh.prototype.convertToUnIndexedMesh = function () {
  15453. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15454. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15455. var kinds = this.getVerticesDataKinds();
  15456. var vbs = [];
  15457. var data = [];
  15458. var newdata = [];
  15459. var updatableNormals = false;
  15460. var kindIndex;
  15461. var kind;
  15462. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15463. kind = kinds[kindIndex];
  15464. var vertexBuffer = this.getVertexBuffer(kind);
  15465. vbs[kind] = vertexBuffer;
  15466. data[kind] = vbs[kind].getData();
  15467. newdata[kind] = [];
  15468. }
  15469. // Save previous submeshes
  15470. var previousSubmeshes = this.subMeshes.slice(0);
  15471. var indices = this.getIndices();
  15472. var totalIndices = this.getTotalIndices();
  15473. // Generating unique vertices per face
  15474. var index;
  15475. for (index = 0; index < totalIndices; index++) {
  15476. var vertexIndex = indices[index];
  15477. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15478. kind = kinds[kindIndex];
  15479. var stride = vbs[kind].getStrideSize();
  15480. for (var offset = 0; offset < stride; offset++) {
  15481. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15482. }
  15483. }
  15484. }
  15485. // Updating indices
  15486. for (index = 0; index < totalIndices; index += 3) {
  15487. indices[index] = index;
  15488. indices[index + 1] = index + 1;
  15489. indices[index + 2] = index + 2;
  15490. }
  15491. this.setIndices(indices);
  15492. // Updating vertex buffers
  15493. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15494. kind = kinds[kindIndex];
  15495. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15496. }
  15497. // Updating submeshes
  15498. this.releaseSubMeshes();
  15499. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15500. var previousOne = previousSubmeshes[submeshIndex];
  15501. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15502. }
  15503. this._unIndexed = true;
  15504. this.synchronizeInstances();
  15505. };
  15506. // will inverse faces orientations, and invert normals too if specified
  15507. Mesh.prototype.flipFaces = function (flipNormals) {
  15508. if (flipNormals === void 0) { flipNormals = false; }
  15509. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15510. var i;
  15511. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15512. for (i = 0; i < vertex_data.normals.length; i++) {
  15513. vertex_data.normals[i] *= -1;
  15514. }
  15515. }
  15516. var temp;
  15517. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15518. // reassign indices
  15519. temp = vertex_data.indices[i + 1];
  15520. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15521. vertex_data.indices[i + 2] = temp;
  15522. }
  15523. vertex_data.applyToMesh(this);
  15524. };
  15525. // Instances
  15526. Mesh.prototype.createInstance = function (name) {
  15527. return new BABYLON.InstancedMesh(name, this);
  15528. };
  15529. Mesh.prototype.synchronizeInstances = function () {
  15530. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15531. var instance = this.instances[instanceIndex];
  15532. instance._syncSubMeshes();
  15533. }
  15534. };
  15535. /**
  15536. * Simplify the mesh according to the given array of settings.
  15537. * Function will return immediately and will simplify async.
  15538. * @param settings a collection of simplification settings.
  15539. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15540. * @param type the type of simplification to run.
  15541. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15542. */
  15543. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15544. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15545. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15546. this.getScene().simplificationQueue.addTask({
  15547. settings: settings,
  15548. parallelProcessing: parallelProcessing,
  15549. mesh: this,
  15550. simplificationType: simplificationType,
  15551. successCallback: successCallback
  15552. });
  15553. };
  15554. /**
  15555. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15556. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15557. * This should be used together with the simplification to avoid disappearing triangles.
  15558. * @param successCallback an optional success callback to be called after the optimization finished.
  15559. */
  15560. Mesh.prototype.optimizeIndices = function (successCallback) {
  15561. var _this = this;
  15562. var indices = this.getIndices();
  15563. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15564. var vectorPositions = [];
  15565. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15566. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15567. }
  15568. var dupes = [];
  15569. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15570. var realPos = vectorPositions.length - 1 - iteration;
  15571. var testedPosition = vectorPositions[realPos];
  15572. for (var j = 0; j < realPos; ++j) {
  15573. var againstPosition = vectorPositions[j];
  15574. if (testedPosition.equals(againstPosition)) {
  15575. dupes[realPos] = j;
  15576. break;
  15577. }
  15578. }
  15579. }, function () {
  15580. for (var i = 0; i < indices.length; ++i) {
  15581. indices[i] = dupes[indices[i]] || indices[i];
  15582. }
  15583. //indices are now reordered
  15584. var originalSubMeshes = _this.subMeshes.slice(0);
  15585. _this.setIndices(indices);
  15586. _this.subMeshes = originalSubMeshes;
  15587. if (successCallback) {
  15588. successCallback(_this);
  15589. }
  15590. });
  15591. };
  15592. // Statics
  15593. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15594. var mesh = new Mesh(parsedMesh.name, scene);
  15595. mesh.id = parsedMesh.id;
  15596. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15597. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15598. if (parsedMesh.rotationQuaternion) {
  15599. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15600. }
  15601. else if (parsedMesh.rotation) {
  15602. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15603. }
  15604. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15605. if (parsedMesh.localMatrix) {
  15606. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15607. }
  15608. else if (parsedMesh.pivotMatrix) {
  15609. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15610. }
  15611. mesh.setEnabled(parsedMesh.isEnabled);
  15612. mesh.isVisible = parsedMesh.isVisible;
  15613. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15614. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15615. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15616. if (parsedMesh.applyFog !== undefined) {
  15617. mesh.applyFog = parsedMesh.applyFog;
  15618. }
  15619. if (parsedMesh.pickable !== undefined) {
  15620. mesh.isPickable = parsedMesh.pickable;
  15621. }
  15622. if (parsedMesh.alphaIndex !== undefined) {
  15623. mesh.alphaIndex = parsedMesh.alphaIndex;
  15624. }
  15625. mesh.receiveShadows = parsedMesh.receiveShadows;
  15626. mesh.billboardMode = parsedMesh.billboardMode;
  15627. if (parsedMesh.visibility !== undefined) {
  15628. mesh.visibility = parsedMesh.visibility;
  15629. }
  15630. mesh.checkCollisions = parsedMesh.checkCollisions;
  15631. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15632. // freezeWorldMatrix
  15633. if (parsedMesh.freezeWorldMatrix) {
  15634. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15635. }
  15636. // Parent
  15637. if (parsedMesh.parentId) {
  15638. mesh._waitingParentId = parsedMesh.parentId;
  15639. }
  15640. // Actions
  15641. if (parsedMesh.actions !== undefined) {
  15642. mesh._waitingActions = parsedMesh.actions;
  15643. }
  15644. // Geometry
  15645. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15646. if (parsedMesh.delayLoadingFile) {
  15647. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15648. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15649. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15650. if (parsedMesh._binaryInfo) {
  15651. mesh._binaryInfo = parsedMesh._binaryInfo;
  15652. }
  15653. mesh._delayInfo = [];
  15654. if (parsedMesh.hasUVs) {
  15655. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15656. }
  15657. if (parsedMesh.hasUVs2) {
  15658. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15659. }
  15660. if (parsedMesh.hasUVs3) {
  15661. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15662. }
  15663. if (parsedMesh.hasUVs4) {
  15664. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15665. }
  15666. if (parsedMesh.hasUVs5) {
  15667. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15668. }
  15669. if (parsedMesh.hasUVs6) {
  15670. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15671. }
  15672. if (parsedMesh.hasColors) {
  15673. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15674. }
  15675. if (parsedMesh.hasMatricesIndices) {
  15676. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15677. }
  15678. if (parsedMesh.hasMatricesWeights) {
  15679. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15680. }
  15681. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15682. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15683. mesh._checkDelayState();
  15684. }
  15685. }
  15686. else {
  15687. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15688. }
  15689. // Material
  15690. if (parsedMesh.materialId) {
  15691. mesh.setMaterialByID(parsedMesh.materialId);
  15692. }
  15693. else {
  15694. mesh.material = null;
  15695. }
  15696. // Skeleton
  15697. if (parsedMesh.skeletonId > -1) {
  15698. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15699. if (parsedMesh.numBoneInfluencers) {
  15700. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15701. }
  15702. }
  15703. // Physics
  15704. if (parsedMesh.physicsImpostor) {
  15705. if (!scene.isPhysicsEnabled()) {
  15706. scene.enablePhysics();
  15707. }
  15708. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15709. }
  15710. // Animations
  15711. if (parsedMesh.animations) {
  15712. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15713. var parsedAnimation = parsedMesh.animations[animationIndex];
  15714. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15715. }
  15716. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15717. }
  15718. if (parsedMesh.autoAnimate) {
  15719. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15720. }
  15721. // Layer Mask
  15722. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15723. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15724. }
  15725. else {
  15726. mesh.layerMask = 0x0FFFFFFF;
  15727. }
  15728. // Instances
  15729. if (parsedMesh.instances) {
  15730. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15731. var parsedInstance = parsedMesh.instances[index];
  15732. var instance = mesh.createInstance(parsedInstance.name);
  15733. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15734. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15735. if (parsedInstance.rotationQuaternion) {
  15736. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15737. }
  15738. else if (parsedInstance.rotation) {
  15739. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  15740. }
  15741. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  15742. instance.checkCollisions = mesh.checkCollisions;
  15743. if (parsedMesh.animations) {
  15744. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15745. parsedAnimation = parsedMesh.animations[animationIndex];
  15746. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15747. }
  15748. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  15749. }
  15750. }
  15751. }
  15752. return mesh;
  15753. };
  15754. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  15755. return BABYLON.MeshBuilder.CreateRibbon(name, {
  15756. pathArray: pathArray,
  15757. closeArray: closeArray,
  15758. closePath: closePath,
  15759. offset: offset,
  15760. updatable: updatable,
  15761. sideOrientation: sideOrientation,
  15762. instance: instance
  15763. }, scene);
  15764. };
  15765. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15766. var options = {
  15767. radius: radius,
  15768. tessellation: tessellation,
  15769. sideOrientation: sideOrientation,
  15770. updatable: updatable
  15771. };
  15772. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  15773. };
  15774. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15775. var options = {
  15776. size: size,
  15777. sideOrientation: sideOrientation,
  15778. updatable: updatable
  15779. };
  15780. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  15781. };
  15782. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15783. var options = {
  15784. segments: segments,
  15785. diameterX: diameter,
  15786. diameterY: diameter,
  15787. diameterZ: diameter,
  15788. sideOrientation: sideOrientation,
  15789. updatable: updatable
  15790. };
  15791. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  15792. };
  15793. // Cylinder and cone
  15794. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15795. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15796. if (scene !== undefined) {
  15797. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15798. updatable = scene;
  15799. }
  15800. scene = subdivisions;
  15801. subdivisions = 1;
  15802. }
  15803. var options = {
  15804. height: height,
  15805. diameterTop: diameterTop,
  15806. diameterBottom: diameterBottom,
  15807. tessellation: tessellation,
  15808. subdivisions: subdivisions,
  15809. sideOrientation: sideOrientation,
  15810. updatable: updatable
  15811. };
  15812. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  15813. };
  15814. // Torus (Code from SharpDX.org)
  15815. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15816. var options = {
  15817. diameter: diameter,
  15818. thickness: thickness,
  15819. tessellation: tessellation,
  15820. sideOrientation: sideOrientation,
  15821. updatable: updatable
  15822. };
  15823. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  15824. };
  15825. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15826. var options = {
  15827. radius: radius,
  15828. tube: tube,
  15829. radialSegments: radialSegments,
  15830. tubularSegments: tubularSegments,
  15831. p: p,
  15832. q: q,
  15833. sideOrientation: sideOrientation,
  15834. updatable: updatable
  15835. };
  15836. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  15837. };
  15838. // Lines
  15839. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  15840. var options = {
  15841. points: points,
  15842. updatable: updatable,
  15843. instance: instance
  15844. };
  15845. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  15846. };
  15847. // Dashed Lines
  15848. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  15849. var options = {
  15850. points: points,
  15851. dashSize: dashSize,
  15852. gapSize: gapSize,
  15853. dashNb: dashNb,
  15854. updatable: updatable
  15855. };
  15856. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15857. };
  15858. // Extrusion
  15859. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15860. var options = {
  15861. shape: shape,
  15862. path: path,
  15863. scale: scale,
  15864. rotation: rotation,
  15865. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15866. sideOrientation: sideOrientation,
  15867. instance: instance,
  15868. updatable: updatable
  15869. };
  15870. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15871. };
  15872. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15873. var options = {
  15874. shape: shape,
  15875. path: path,
  15876. scaleFunction: scaleFunction,
  15877. rotationFunction: rotationFunction,
  15878. ribbonCloseArray: ribbonCloseArray,
  15879. ribbonClosePath: ribbonClosePath,
  15880. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15881. sideOrientation: sideOrientation,
  15882. instance: instance,
  15883. updatable: updatable
  15884. };
  15885. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15886. };
  15887. // Lathe
  15888. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15889. var options = {
  15890. shape: shape,
  15891. radius: radius,
  15892. tessellation: tessellation,
  15893. sideOrientation: sideOrientation,
  15894. updatable: updatable
  15895. };
  15896. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15897. };
  15898. // Plane & ground
  15899. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15900. var options = {
  15901. size: size,
  15902. width: size,
  15903. height: size,
  15904. sideOrientation: sideOrientation,
  15905. updatable: updatable
  15906. };
  15907. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15908. };
  15909. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15910. var options = {
  15911. width: width,
  15912. height: height,
  15913. subdivisions: subdivisions,
  15914. updatable: updatable
  15915. };
  15916. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15917. };
  15918. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15919. var options = {
  15920. xmin: xmin,
  15921. zmin: zmin,
  15922. xmax: xmax,
  15923. zmax: zmax,
  15924. subdivisions: subdivisions,
  15925. precision: precision,
  15926. updatable: updatable
  15927. };
  15928. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15929. };
  15930. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15931. var options = {
  15932. width: width,
  15933. height: height,
  15934. subdivisions: subdivisions,
  15935. minHeight: minHeight,
  15936. maxHeight: maxHeight,
  15937. updatable: updatable,
  15938. onReady: onReady
  15939. };
  15940. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15941. };
  15942. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15943. var options = {
  15944. path: path,
  15945. radius: radius,
  15946. tessellation: tessellation,
  15947. radiusFunction: radiusFunction,
  15948. arc: 1,
  15949. cap: cap,
  15950. updatable: updatable,
  15951. sideOrientation: sideOrientation,
  15952. instance: instance
  15953. };
  15954. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15955. };
  15956. Mesh.CreatePolyhedron = function (name, options, scene) {
  15957. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15958. };
  15959. Mesh.CreateIcoSphere = function (name, options, scene) {
  15960. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15961. };
  15962. // Decals
  15963. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15964. var options = {
  15965. position: position,
  15966. normal: normal,
  15967. size: size,
  15968. angle: angle
  15969. };
  15970. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15971. };
  15972. // Skeletons
  15973. /**
  15974. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15975. */
  15976. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15977. var source;
  15978. if (!this._sourcePositions) {
  15979. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15980. this._sourcePositions = new Float32Array(source);
  15981. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15982. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15983. }
  15984. }
  15985. return this._sourcePositions;
  15986. };
  15987. /**
  15988. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15989. */
  15990. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15991. var source;
  15992. if (!this._sourceNormals) {
  15993. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15994. this._sourceNormals = new Float32Array(source);
  15995. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15996. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15997. }
  15998. }
  15999. return this._sourceNormals;
  16000. };
  16001. /**
  16002. * Update the vertex buffers by applying transformation from the bones
  16003. * @param {skeleton} skeleton to apply
  16004. */
  16005. Mesh.prototype.applySkeleton = function (skeleton) {
  16006. if (!this.geometry) {
  16007. return;
  16008. }
  16009. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16010. return;
  16011. }
  16012. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16013. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16014. return this;
  16015. }
  16016. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16017. return this;
  16018. }
  16019. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16020. return this;
  16021. }
  16022. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16023. return this;
  16024. }
  16025. if (!this._sourcePositions) {
  16026. this.setPositionsForCPUSkinning();
  16027. }
  16028. if (!this._sourceNormals) {
  16029. this.setNormalsForCPUSkinning();
  16030. }
  16031. // positionsData checks for not being Float32Array will only pass at most once
  16032. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16033. if (!(positionsData instanceof Float32Array)) {
  16034. positionsData = new Float32Array(positionsData);
  16035. }
  16036. // normalsData checks for not being Float32Array will only pass at most once
  16037. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16038. if (!(normalsData instanceof Float32Array)) {
  16039. normalsData = new Float32Array(normalsData);
  16040. }
  16041. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16042. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16043. var needExtras = this.numBoneInfluencers > 4;
  16044. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16045. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16046. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16047. var tempVector3 = BABYLON.Vector3.Zero();
  16048. var finalMatrix = new BABYLON.Matrix();
  16049. var tempMatrix = new BABYLON.Matrix();
  16050. var matWeightIdx = 0;
  16051. var inf;
  16052. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16053. var weight;
  16054. for (inf = 0; inf < 4; inf++) {
  16055. weight = matricesWeightsData[matWeightIdx + inf];
  16056. if (weight > 0) {
  16057. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16058. finalMatrix.addToSelf(tempMatrix);
  16059. }
  16060. else
  16061. break;
  16062. }
  16063. if (needExtras) {
  16064. for (inf = 0; inf < 4; inf++) {
  16065. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16066. if (weight > 0) {
  16067. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16068. finalMatrix.addToSelf(tempMatrix);
  16069. }
  16070. else
  16071. break;
  16072. }
  16073. }
  16074. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16075. tempVector3.toArray(positionsData, index);
  16076. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16077. tempVector3.toArray(normalsData, index);
  16078. finalMatrix.reset();
  16079. }
  16080. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16081. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16082. return this;
  16083. };
  16084. // Tools
  16085. Mesh.MinMax = function (meshes) {
  16086. var minVector = null;
  16087. var maxVector = null;
  16088. for (var i in meshes) {
  16089. var mesh = meshes[i];
  16090. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16091. if (!minVector) {
  16092. minVector = boundingBox.minimumWorld;
  16093. maxVector = boundingBox.maximumWorld;
  16094. continue;
  16095. }
  16096. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16097. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16098. }
  16099. return {
  16100. min: minVector,
  16101. max: maxVector
  16102. };
  16103. };
  16104. Mesh.Center = function (meshesOrMinMaxVector) {
  16105. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16106. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16107. };
  16108. /**
  16109. * Merge the array of meshes into a single mesh for performance reasons.
  16110. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16111. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16112. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16113. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16114. */
  16115. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16116. if (disposeSource === void 0) { disposeSource = true; }
  16117. var index;
  16118. if (!allow32BitsIndices) {
  16119. var totalVertices = 0;
  16120. // Counting vertices
  16121. for (index = 0; index < meshes.length; index++) {
  16122. if (meshes[index]) {
  16123. totalVertices += meshes[index].getTotalVertices();
  16124. if (totalVertices > 65536) {
  16125. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16126. return null;
  16127. }
  16128. }
  16129. }
  16130. }
  16131. // Merge
  16132. var vertexData;
  16133. var otherVertexData;
  16134. var source;
  16135. for (index = 0; index < meshes.length; index++) {
  16136. if (meshes[index]) {
  16137. meshes[index].computeWorldMatrix(true);
  16138. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16139. otherVertexData.transform(meshes[index].getWorldMatrix());
  16140. if (vertexData) {
  16141. vertexData.merge(otherVertexData);
  16142. }
  16143. else {
  16144. vertexData = otherVertexData;
  16145. source = meshes[index];
  16146. }
  16147. }
  16148. }
  16149. if (!meshSubclass) {
  16150. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16151. }
  16152. vertexData.applyToMesh(meshSubclass);
  16153. // Setting properties
  16154. meshSubclass.material = source.material;
  16155. meshSubclass.checkCollisions = source.checkCollisions;
  16156. // Cleaning
  16157. if (disposeSource) {
  16158. for (index = 0; index < meshes.length; index++) {
  16159. if (meshes[index]) {
  16160. meshes[index].dispose();
  16161. }
  16162. }
  16163. }
  16164. return meshSubclass;
  16165. };
  16166. // Consts
  16167. Mesh._FRONTSIDE = 0;
  16168. Mesh._BACKSIDE = 1;
  16169. Mesh._DOUBLESIDE = 2;
  16170. Mesh._DEFAULTSIDE = 0;
  16171. Mesh._NO_CAP = 0;
  16172. Mesh._CAP_START = 1;
  16173. Mesh._CAP_END = 2;
  16174. Mesh._CAP_ALL = 3;
  16175. return Mesh;
  16176. })(BABYLON.AbstractMesh);
  16177. BABYLON.Mesh = Mesh;
  16178. })(BABYLON || (BABYLON = {}));
  16179. var BABYLON;
  16180. (function (BABYLON) {
  16181. var SubMesh = (function () {
  16182. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16183. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16184. this.materialIndex = materialIndex;
  16185. this.verticesStart = verticesStart;
  16186. this.verticesCount = verticesCount;
  16187. this.indexStart = indexStart;
  16188. this.indexCount = indexCount;
  16189. this._renderId = 0;
  16190. this._mesh = mesh;
  16191. this._renderingMesh = renderingMesh || mesh;
  16192. mesh.subMeshes.push(this);
  16193. this._trianglePlanes = [];
  16194. this._id = mesh.subMeshes.length - 1;
  16195. if (createBoundingBox) {
  16196. this.refreshBoundingInfo();
  16197. mesh.computeWorldMatrix(true);
  16198. }
  16199. }
  16200. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16201. get: function () {
  16202. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16203. },
  16204. enumerable: true,
  16205. configurable: true
  16206. });
  16207. SubMesh.prototype.getBoundingInfo = function () {
  16208. if (this.IsGlobal) {
  16209. return this._mesh.getBoundingInfo();
  16210. }
  16211. return this._boundingInfo;
  16212. };
  16213. SubMesh.prototype.getMesh = function () {
  16214. return this._mesh;
  16215. };
  16216. SubMesh.prototype.getRenderingMesh = function () {
  16217. return this._renderingMesh;
  16218. };
  16219. SubMesh.prototype.getMaterial = function () {
  16220. var rootMaterial = this._renderingMesh.material;
  16221. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16222. var multiMaterial = rootMaterial;
  16223. return multiMaterial.getSubMaterial(this.materialIndex);
  16224. }
  16225. if (!rootMaterial) {
  16226. return this._mesh.getScene().defaultMaterial;
  16227. }
  16228. return rootMaterial;
  16229. };
  16230. // Methods
  16231. SubMesh.prototype.refreshBoundingInfo = function () {
  16232. if (this.IsGlobal) {
  16233. return;
  16234. }
  16235. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16236. if (!data) {
  16237. this._boundingInfo = this._mesh._boundingInfo;
  16238. return;
  16239. }
  16240. var indices = this._renderingMesh.getIndices();
  16241. var extend;
  16242. //is this the only submesh?
  16243. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16244. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16245. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16246. }
  16247. else {
  16248. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16249. }
  16250. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16251. };
  16252. SubMesh.prototype._checkCollision = function (collider) {
  16253. return this.getBoundingInfo()._checkCollision(collider);
  16254. };
  16255. SubMesh.prototype.updateBoundingInfo = function (world) {
  16256. if (!this.getBoundingInfo()) {
  16257. this.refreshBoundingInfo();
  16258. }
  16259. this.getBoundingInfo()._update(world);
  16260. };
  16261. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16262. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16263. };
  16264. SubMesh.prototype.render = function (enableAlphaMode) {
  16265. this._renderingMesh.render(this, enableAlphaMode);
  16266. };
  16267. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16268. if (!this._linesIndexBuffer) {
  16269. var linesIndices = [];
  16270. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16271. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16272. }
  16273. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16274. this.linesIndexCount = linesIndices.length;
  16275. }
  16276. return this._linesIndexBuffer;
  16277. };
  16278. SubMesh.prototype.canIntersects = function (ray) {
  16279. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16280. };
  16281. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16282. var intersectInfo = null;
  16283. // Triangles test
  16284. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16285. var p0 = positions[indices[index]];
  16286. var p1 = positions[indices[index + 1]];
  16287. var p2 = positions[indices[index + 2]];
  16288. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16289. if (currentIntersectInfo) {
  16290. if (currentIntersectInfo.distance < 0) {
  16291. continue;
  16292. }
  16293. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16294. intersectInfo = currentIntersectInfo;
  16295. intersectInfo.faceId = index / 3;
  16296. if (fastCheck) {
  16297. break;
  16298. }
  16299. }
  16300. }
  16301. }
  16302. return intersectInfo;
  16303. };
  16304. // Clone
  16305. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16306. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16307. if (!this.IsGlobal) {
  16308. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16309. }
  16310. return result;
  16311. };
  16312. // Dispose
  16313. SubMesh.prototype.dispose = function () {
  16314. if (this._linesIndexBuffer) {
  16315. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16316. this._linesIndexBuffer = null;
  16317. }
  16318. // Remove from mesh
  16319. var index = this._mesh.subMeshes.indexOf(this);
  16320. this._mesh.subMeshes.splice(index, 1);
  16321. };
  16322. // Statics
  16323. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16324. var minVertexIndex = Number.MAX_VALUE;
  16325. var maxVertexIndex = -Number.MAX_VALUE;
  16326. renderingMesh = renderingMesh || mesh;
  16327. var indices = renderingMesh.getIndices();
  16328. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16329. var vertexIndex = indices[index];
  16330. if (vertexIndex < minVertexIndex)
  16331. minVertexIndex = vertexIndex;
  16332. if (vertexIndex > maxVertexIndex)
  16333. maxVertexIndex = vertexIndex;
  16334. }
  16335. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16336. };
  16337. return SubMesh;
  16338. })();
  16339. BABYLON.SubMesh = SubMesh;
  16340. })(BABYLON || (BABYLON = {}));
  16341. var BABYLON;
  16342. (function (BABYLON) {
  16343. var MeshBuilder = (function () {
  16344. function MeshBuilder() {
  16345. }
  16346. MeshBuilder.CreateBox = function (name, options, scene) {
  16347. var box = new BABYLON.Mesh(name, scene);
  16348. var vertexData = BABYLON.VertexData.CreateBox(options);
  16349. vertexData.applyToMesh(box, options.updatable);
  16350. return box;
  16351. };
  16352. MeshBuilder.CreateSphere = function (name, options, scene) {
  16353. var sphere = new BABYLON.Mesh(name, scene);
  16354. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16355. vertexData.applyToMesh(sphere, options.updatable);
  16356. return sphere;
  16357. };
  16358. MeshBuilder.CreateDisc = function (name, options, scene) {
  16359. var disc = new BABYLON.Mesh(name, scene);
  16360. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16361. vertexData.applyToMesh(disc, options.updatable);
  16362. return disc;
  16363. };
  16364. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16365. var sphere = new BABYLON.Mesh(name, scene);
  16366. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16367. vertexData.applyToMesh(sphere, options.updatable);
  16368. return sphere;
  16369. };
  16370. ;
  16371. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16372. var pathArray = options.pathArray;
  16373. var closeArray = options.closeArray;
  16374. var closePath = options.closePath;
  16375. var offset = options.offset;
  16376. var sideOrientation = options.sideOrientation;
  16377. var instance = options.instance;
  16378. var updatable = options.updatable;
  16379. if (instance) {
  16380. // positionFunction : ribbon case
  16381. // only pathArray and sideOrientation parameters are taken into account for positions update
  16382. var positionFunction = function (positions) {
  16383. var minlg = pathArray[0].length;
  16384. var i = 0;
  16385. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16386. for (var si = 1; si <= ns; si++) {
  16387. for (var p = 0; p < pathArray.length; p++) {
  16388. var path = pathArray[p];
  16389. var l = path.length;
  16390. minlg = (minlg < l) ? minlg : l;
  16391. var j = 0;
  16392. while (j < minlg) {
  16393. positions[i] = path[j].x;
  16394. positions[i + 1] = path[j].y;
  16395. positions[i + 2] = path[j].z;
  16396. j++;
  16397. i += 3;
  16398. }
  16399. if (instance._closePath) {
  16400. positions[i] = path[0].x;
  16401. positions[i + 1] = path[0].y;
  16402. positions[i + 2] = path[0].z;
  16403. i += 3;
  16404. }
  16405. }
  16406. }
  16407. };
  16408. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16409. positionFunction(positions);
  16410. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16411. if (!(instance.areNormalsFrozen)) {
  16412. var indices = instance.getIndices();
  16413. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16414. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16415. if (instance._closePath) {
  16416. var indexFirst = 0;
  16417. var indexLast = 0;
  16418. for (var p = 0; p < pathArray.length; p++) {
  16419. indexFirst = instance._idx[p] * 3;
  16420. if (p + 1 < pathArray.length) {
  16421. indexLast = (instance._idx[p + 1] - 1) * 3;
  16422. }
  16423. else {
  16424. indexLast = normals.length - 3;
  16425. }
  16426. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16427. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16428. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16429. normals[indexLast] = normals[indexFirst];
  16430. normals[indexLast + 1] = normals[indexFirst + 1];
  16431. normals[indexLast + 2] = normals[indexFirst + 2];
  16432. }
  16433. }
  16434. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16435. }
  16436. return instance;
  16437. }
  16438. else {
  16439. var ribbon = new BABYLON.Mesh(name, scene);
  16440. ribbon.sideOrientation = sideOrientation;
  16441. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16442. if (closePath) {
  16443. ribbon._idx = vertexData._idx;
  16444. }
  16445. ribbon._closePath = closePath;
  16446. ribbon._closeArray = closeArray;
  16447. vertexData.applyToMesh(ribbon, updatable);
  16448. return ribbon;
  16449. }
  16450. };
  16451. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16452. var cylinder = new BABYLON.Mesh(name, scene);
  16453. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16454. vertexData.applyToMesh(cylinder, options.updatable);
  16455. return cylinder;
  16456. };
  16457. MeshBuilder.CreateTorus = function (name, options, scene) {
  16458. var torus = new BABYLON.Mesh(name, scene);
  16459. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16460. vertexData.applyToMesh(torus, options.updatable);
  16461. return torus;
  16462. };
  16463. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16464. var torusKnot = new BABYLON.Mesh(name, scene);
  16465. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16466. vertexData.applyToMesh(torusKnot, options.updatable);
  16467. return torusKnot;
  16468. };
  16469. MeshBuilder.CreateLines = function (name, options, scene) {
  16470. var instance = options.instance;
  16471. var points = options.points;
  16472. if (instance) {
  16473. var positionFunction = function (positions) {
  16474. var i = 0;
  16475. for (var p = 0; p < points.length; p++) {
  16476. positions[i] = points[p].x;
  16477. positions[i + 1] = points[p].y;
  16478. positions[i + 2] = points[p].z;
  16479. i += 3;
  16480. }
  16481. };
  16482. instance.updateMeshPositions(positionFunction, false);
  16483. return instance;
  16484. }
  16485. // lines creation
  16486. var lines = new BABYLON.LinesMesh(name, scene);
  16487. var vertexData = BABYLON.VertexData.CreateLines(options);
  16488. vertexData.applyToMesh(lines, options.updatable);
  16489. return lines;
  16490. };
  16491. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16492. var points = options.points;
  16493. var instance = options.instance;
  16494. var gapSize = options.gapSize;
  16495. var dashNb = options.dashNb;
  16496. var dashSize = options.dashSize;
  16497. if (instance) {
  16498. var positionFunction = function (positions) {
  16499. var curvect = BABYLON.Vector3.Zero();
  16500. var nbSeg = positions.length / 6;
  16501. var lg = 0;
  16502. var nb = 0;
  16503. var shft = 0;
  16504. var dashshft = 0;
  16505. var curshft = 0;
  16506. var p = 0;
  16507. var i = 0;
  16508. var j = 0;
  16509. for (i = 0; i < points.length - 1; i++) {
  16510. points[i + 1].subtractToRef(points[i], curvect);
  16511. lg += curvect.length();
  16512. }
  16513. shft = lg / nbSeg;
  16514. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16515. for (i = 0; i < points.length - 1; i++) {
  16516. points[i + 1].subtractToRef(points[i], curvect);
  16517. nb = Math.floor(curvect.length() / shft);
  16518. curvect.normalize();
  16519. j = 0;
  16520. while (j < nb && p < positions.length) {
  16521. curshft = shft * j;
  16522. positions[p] = points[i].x + curshft * curvect.x;
  16523. positions[p + 1] = points[i].y + curshft * curvect.y;
  16524. positions[p + 2] = points[i].z + curshft * curvect.z;
  16525. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16526. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16527. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16528. p += 6;
  16529. j++;
  16530. }
  16531. }
  16532. while (p < positions.length) {
  16533. positions[p] = points[i].x;
  16534. positions[p + 1] = points[i].y;
  16535. positions[p + 2] = points[i].z;
  16536. p += 3;
  16537. }
  16538. };
  16539. instance.updateMeshPositions(positionFunction, false);
  16540. return instance;
  16541. }
  16542. // dashed lines creation
  16543. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16544. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16545. vertexData.applyToMesh(dashedLines, options.updatable);
  16546. dashedLines.dashSize = dashSize;
  16547. dashedLines.gapSize = gapSize;
  16548. return dashedLines;
  16549. };
  16550. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16551. var path = options.path;
  16552. var shape = options.shape;
  16553. var scale = options.scale || 1;
  16554. var rotation = options.rotation || 0;
  16555. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16556. var updatable = options.updatable;
  16557. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16558. var instance = options.instance;
  16559. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16560. };
  16561. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16562. var path = options.path;
  16563. var shape = options.shape;
  16564. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16565. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16566. var ribbonCloseArray = options.ribbonCloseArray || false;
  16567. var ribbonClosePath = options.ribbonClosePath || false;
  16568. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16569. var updatable = options.updatable;
  16570. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16571. var instance = options.instance;
  16572. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16573. };
  16574. MeshBuilder.CreateLathe = function (name, options, scene) {
  16575. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16576. var closed = (options.closed === undefined) ? true : options.closed;
  16577. var shape = options.shape;
  16578. var radius = options.radius || 1;
  16579. var tessellation = options.tessellation || 64;
  16580. var updatable = options.updatable;
  16581. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16582. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16583. var pi2 = Math.PI * 2;
  16584. var paths = new Array();
  16585. var i = 0;
  16586. var p = 0;
  16587. var step = pi2 / tessellation * arc;
  16588. var rotated;
  16589. var path = new Array();
  16590. ;
  16591. for (i = 0; i <= tessellation; i++) {
  16592. var path = [];
  16593. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16594. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16595. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16596. }
  16597. for (p = 0; p < shape.length; p++) {
  16598. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16599. path.push(rotated);
  16600. }
  16601. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16602. 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));
  16603. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16604. }
  16605. paths.push(path);
  16606. }
  16607. // lathe ribbon
  16608. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16609. return lathe;
  16610. };
  16611. MeshBuilder.CreatePlane = function (name, options, scene) {
  16612. var plane = new BABYLON.Mesh(name, scene);
  16613. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16614. vertexData.applyToMesh(plane, options.updatable);
  16615. if (options.sourcePlane) {
  16616. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16617. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16618. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16619. plane.rotate(vectorProduct, product);
  16620. }
  16621. return plane;
  16622. };
  16623. MeshBuilder.CreateGround = function (name, options, scene) {
  16624. var ground = new BABYLON.GroundMesh(name, scene);
  16625. ground._setReady(false);
  16626. ground._subdivisions = options.subdivisions || 1;
  16627. ground._width = options.width || 1;
  16628. ground._height = options.height || 1;
  16629. ground._maxX = ground._width / 2;
  16630. ground._maxZ = ground._height / 2;
  16631. ground._minX = -ground._maxX;
  16632. ground._minZ = -ground._maxZ;
  16633. var vertexData = BABYLON.VertexData.CreateGround(options);
  16634. vertexData.applyToMesh(ground, options.updatable);
  16635. ground._setReady(true);
  16636. return ground;
  16637. };
  16638. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16639. var tiledGround = new BABYLON.Mesh(name, scene);
  16640. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16641. vertexData.applyToMesh(tiledGround, options.updatable);
  16642. return tiledGround;
  16643. };
  16644. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16645. var width = options.width || 10;
  16646. var height = options.height || 10;
  16647. var subdivisions = options.subdivisions || 1;
  16648. var minHeight = options.minHeight;
  16649. var maxHeight = options.maxHeight || 10;
  16650. var updatable = options.updatable;
  16651. var onReady = options.onReady;
  16652. var ground = new BABYLON.GroundMesh(name, scene);
  16653. ground._subdivisions = subdivisions;
  16654. ground._width = width;
  16655. ground._height = height;
  16656. ground._maxX = ground._width / 2;
  16657. ground._maxZ = ground._height / 2;
  16658. ground._minX = -ground._maxX;
  16659. ground._minZ = -ground._maxZ;
  16660. ground._setReady(false);
  16661. var onload = function (img) {
  16662. // Getting height map data
  16663. var canvas = document.createElement("canvas");
  16664. var context = canvas.getContext("2d");
  16665. var bufferWidth = img.width;
  16666. var bufferHeight = img.height;
  16667. canvas.width = bufferWidth;
  16668. canvas.height = bufferHeight;
  16669. context.drawImage(img, 0, 0);
  16670. // Create VertexData from map data
  16671. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16672. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16673. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16674. width: width, height: height,
  16675. subdivisions: subdivisions,
  16676. minHeight: minHeight, maxHeight: maxHeight,
  16677. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16678. });
  16679. vertexData.applyToMesh(ground, updatable);
  16680. ground._setReady(true);
  16681. //execute ready callback, if set
  16682. if (onReady) {
  16683. onReady(ground);
  16684. }
  16685. };
  16686. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16687. return ground;
  16688. };
  16689. MeshBuilder.CreateTube = function (name, options, scene) {
  16690. var path = options.path;
  16691. var radius = options.radius || 1;
  16692. var tessellation = options.tessellation || 64;
  16693. var radiusFunction = options.radiusFunction;
  16694. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16695. var updatable = options.updatable;
  16696. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16697. var instance = options.instance;
  16698. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16699. // tube geometry
  16700. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16701. var tangents = path3D.getTangents();
  16702. var normals = path3D.getNormals();
  16703. var distances = path3D.getDistances();
  16704. var pi2 = Math.PI * 2;
  16705. var step = pi2 / tessellation * arc;
  16706. var returnRadius = function () { return radius; };
  16707. var radiusFunctionFinal = radiusFunction || returnRadius;
  16708. var circlePath;
  16709. var rad;
  16710. var normal;
  16711. var rotated;
  16712. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16713. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16714. for (var i = 0; i < path.length; i++) {
  16715. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16716. circlePath = Array(); // current circle array
  16717. normal = normals[i]; // current normal
  16718. for (var t = 0; t < tessellation; t++) {
  16719. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16720. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16721. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16722. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16723. circlePath[t] = rotated;
  16724. }
  16725. circlePaths[index] = circlePath;
  16726. index++;
  16727. }
  16728. // cap
  16729. var capPath = function (nbPoints, pathIndex) {
  16730. var pointCap = Array();
  16731. for (var i = 0; i < nbPoints; i++) {
  16732. pointCap.push(path[pathIndex]);
  16733. }
  16734. return pointCap;
  16735. };
  16736. switch (cap) {
  16737. case BABYLON.Mesh.NO_CAP:
  16738. break;
  16739. case BABYLON.Mesh.CAP_START:
  16740. circlePaths[0] = capPath(tessellation, 0);
  16741. circlePaths[1] = circlePaths[2].slice(0);
  16742. break;
  16743. case BABYLON.Mesh.CAP_END:
  16744. circlePaths[index] = circlePaths[index - 1].slice(0);
  16745. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16746. break;
  16747. case BABYLON.Mesh.CAP_ALL:
  16748. circlePaths[0] = capPath(tessellation, 0);
  16749. circlePaths[1] = circlePaths[2].slice(0);
  16750. circlePaths[index] = circlePaths[index - 1].slice(0);
  16751. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16752. break;
  16753. default:
  16754. break;
  16755. }
  16756. return circlePaths;
  16757. };
  16758. var path3D;
  16759. var pathArray;
  16760. if (instance) {
  16761. var arc = options.arc || instance.arc;
  16762. path3D = (instance.path3D).update(path);
  16763. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16764. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16765. instance.path3D = path3D;
  16766. instance.pathArray = pathArray;
  16767. instance.arc = arc;
  16768. return instance;
  16769. }
  16770. // tube creation
  16771. path3D = new BABYLON.Path3D(path);
  16772. var newPathArray = new Array();
  16773. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16774. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  16775. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16776. tube.pathArray = pathArray;
  16777. tube.path3D = path3D;
  16778. tube.tessellation = tessellation;
  16779. tube.cap = cap;
  16780. tube.arc = options.arc;
  16781. return tube;
  16782. };
  16783. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  16784. var polyhedron = new BABYLON.Mesh(name, scene);
  16785. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  16786. vertexData.applyToMesh(polyhedron, options.updatable);
  16787. return polyhedron;
  16788. };
  16789. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  16790. var indices = sourceMesh.getIndices();
  16791. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16792. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16793. var position = options.position || BABYLON.Vector3.Zero();
  16794. var normal = options.normal || BABYLON.Vector3.Up();
  16795. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  16796. var angle = options.angle || 0;
  16797. // Getting correct rotation
  16798. if (!normal) {
  16799. var target = new BABYLON.Vector3(0, 0, 1);
  16800. var camera = sourceMesh.getScene().activeCamera;
  16801. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16802. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16803. }
  16804. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16805. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16806. var pitch = Math.atan2(normal.y, len);
  16807. // Matrix
  16808. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16809. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16810. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16811. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16812. var vertexData = new BABYLON.VertexData();
  16813. vertexData.indices = [];
  16814. vertexData.positions = [];
  16815. vertexData.normals = [];
  16816. vertexData.uvs = [];
  16817. var currentVertexDataIndex = 0;
  16818. var extractDecalVector3 = function (indexId) {
  16819. var vertexId = indices[indexId];
  16820. var result = new BABYLON.PositionNormalVertex();
  16821. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16822. // Send vector to decal local world
  16823. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16824. // Get normal
  16825. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16826. return result;
  16827. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16828. var clip = function (vertices, axis) {
  16829. if (vertices.length === 0) {
  16830. return vertices;
  16831. }
  16832. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16833. var clipVertices = function (v0, v1) {
  16834. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16835. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16836. };
  16837. var result = new Array();
  16838. for (var index = 0; index < vertices.length; index += 3) {
  16839. var v1Out;
  16840. var v2Out;
  16841. var v3Out;
  16842. var total = 0;
  16843. var nV1, nV2, nV3, nV4;
  16844. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16845. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16846. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16847. v1Out = d1 > 0;
  16848. v2Out = d2 > 0;
  16849. v3Out = d3 > 0;
  16850. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16851. switch (total) {
  16852. case 0:
  16853. result.push(vertices[index]);
  16854. result.push(vertices[index + 1]);
  16855. result.push(vertices[index + 2]);
  16856. break;
  16857. case 1:
  16858. if (v1Out) {
  16859. nV1 = vertices[index + 1];
  16860. nV2 = vertices[index + 2];
  16861. nV3 = clipVertices(vertices[index], nV1);
  16862. nV4 = clipVertices(vertices[index], nV2);
  16863. }
  16864. if (v2Out) {
  16865. nV1 = vertices[index];
  16866. nV2 = vertices[index + 2];
  16867. nV3 = clipVertices(vertices[index + 1], nV1);
  16868. nV4 = clipVertices(vertices[index + 1], nV2);
  16869. result.push(nV3);
  16870. result.push(nV2.clone());
  16871. result.push(nV1.clone());
  16872. result.push(nV2.clone());
  16873. result.push(nV3.clone());
  16874. result.push(nV4);
  16875. break;
  16876. }
  16877. if (v3Out) {
  16878. nV1 = vertices[index];
  16879. nV2 = vertices[index + 1];
  16880. nV3 = clipVertices(vertices[index + 2], nV1);
  16881. nV4 = clipVertices(vertices[index + 2], nV2);
  16882. }
  16883. result.push(nV1.clone());
  16884. result.push(nV2.clone());
  16885. result.push(nV3);
  16886. result.push(nV4);
  16887. result.push(nV3.clone());
  16888. result.push(nV2.clone());
  16889. break;
  16890. case 2:
  16891. if (!v1Out) {
  16892. nV1 = vertices[index].clone();
  16893. nV2 = clipVertices(nV1, vertices[index + 1]);
  16894. nV3 = clipVertices(nV1, vertices[index + 2]);
  16895. result.push(nV1);
  16896. result.push(nV2);
  16897. result.push(nV3);
  16898. }
  16899. if (!v2Out) {
  16900. nV1 = vertices[index + 1].clone();
  16901. nV2 = clipVertices(nV1, vertices[index + 2]);
  16902. nV3 = clipVertices(nV1, vertices[index]);
  16903. result.push(nV1);
  16904. result.push(nV2);
  16905. result.push(nV3);
  16906. }
  16907. if (!v3Out) {
  16908. nV1 = vertices[index + 2].clone();
  16909. nV2 = clipVertices(nV1, vertices[index]);
  16910. nV3 = clipVertices(nV1, vertices[index + 1]);
  16911. result.push(nV1);
  16912. result.push(nV2);
  16913. result.push(nV3);
  16914. }
  16915. break;
  16916. case 3:
  16917. break;
  16918. }
  16919. }
  16920. return result;
  16921. };
  16922. for (var index = 0; index < indices.length; index += 3) {
  16923. var faceVertices = new Array();
  16924. faceVertices.push(extractDecalVector3(index));
  16925. faceVertices.push(extractDecalVector3(index + 1));
  16926. faceVertices.push(extractDecalVector3(index + 2));
  16927. // Clip
  16928. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16929. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16930. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16931. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16932. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16933. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16934. if (faceVertices.length === 0) {
  16935. continue;
  16936. }
  16937. // Add UVs and get back to world
  16938. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16939. var vertex = faceVertices[vIndex];
  16940. //TODO check for Int32Array
  16941. vertexData.indices.push(currentVertexDataIndex);
  16942. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16943. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16944. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16945. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16946. currentVertexDataIndex++;
  16947. }
  16948. }
  16949. // Return mesh
  16950. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16951. vertexData.applyToMesh(decal);
  16952. decal.position = position.clone();
  16953. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16954. return decal;
  16955. };
  16956. // Privates
  16957. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16958. // extrusion geometry
  16959. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16960. var tangents = path3D.getTangents();
  16961. var normals = path3D.getNormals();
  16962. var binormals = path3D.getBinormals();
  16963. var distances = path3D.getDistances();
  16964. var angle = 0;
  16965. var returnScale = function () { return scale; };
  16966. var returnRotation = function () { return rotation; };
  16967. var rotate = custom ? rotateFunction : returnRotation;
  16968. var scl = custom ? scaleFunction : returnScale;
  16969. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16970. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16971. for (var i = 0; i < curve.length; i++) {
  16972. var shapePath = new Array();
  16973. var angleStep = rotate(i, distances[i]);
  16974. var scaleRatio = scl(i, distances[i]);
  16975. for (var p = 0; p < shape.length; p++) {
  16976. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16977. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16978. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  16979. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  16980. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  16981. shapePath[p] = rotated;
  16982. }
  16983. shapePaths[index] = shapePath;
  16984. angle += angleStep;
  16985. index++;
  16986. }
  16987. // cap
  16988. var capPath = function (shapePath) {
  16989. var pointCap = Array();
  16990. var barycenter = BABYLON.Vector3.Zero();
  16991. var i;
  16992. for (i = 0; i < shapePath.length; i++) {
  16993. barycenter.addInPlace(shapePath[i]);
  16994. }
  16995. barycenter.scaleInPlace(1 / shapePath.length);
  16996. for (i = 0; i < shapePath.length; i++) {
  16997. pointCap.push(barycenter);
  16998. }
  16999. return pointCap;
  17000. };
  17001. switch (cap) {
  17002. case BABYLON.Mesh.NO_CAP:
  17003. break;
  17004. case BABYLON.Mesh.CAP_START:
  17005. shapePaths[0] = capPath(shapePaths[2]);
  17006. shapePaths[1] = shapePaths[2].slice(0);
  17007. break;
  17008. case BABYLON.Mesh.CAP_END:
  17009. shapePaths[index] = shapePaths[index - 1];
  17010. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17011. break;
  17012. case BABYLON.Mesh.CAP_ALL:
  17013. shapePaths[0] = capPath(shapePaths[2]);
  17014. shapePaths[1] = shapePaths[2].slice(0);
  17015. shapePaths[index] = shapePaths[index - 1];
  17016. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17017. break;
  17018. default:
  17019. break;
  17020. }
  17021. return shapePaths;
  17022. };
  17023. var path3D;
  17024. var pathArray;
  17025. if (instance) {
  17026. path3D = (instance.path3D).update(curve);
  17027. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17028. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17029. return instance;
  17030. }
  17031. // extruded shape creation
  17032. path3D = new BABYLON.Path3D(curve);
  17033. var newShapePaths = new Array();
  17034. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17035. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17036. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17037. extrudedGeneric.pathArray = pathArray;
  17038. extrudedGeneric.path3D = path3D;
  17039. extrudedGeneric.cap = cap;
  17040. return extrudedGeneric;
  17041. };
  17042. return MeshBuilder;
  17043. })();
  17044. BABYLON.MeshBuilder = MeshBuilder;
  17045. })(BABYLON || (BABYLON = {}));
  17046. var BABYLON;
  17047. (function (BABYLON) {
  17048. var BaseTexture = (function () {
  17049. function BaseTexture(scene) {
  17050. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17051. this.hasAlpha = false;
  17052. this.getAlphaFromRGB = false;
  17053. this.level = 1;
  17054. this.isCube = false;
  17055. this.isRenderTarget = false;
  17056. this.animations = new Array();
  17057. this.coordinatesIndex = 0;
  17058. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17059. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17060. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17061. this.anisotropicFilteringLevel = 4;
  17062. this._scene = scene;
  17063. this._scene.textures.push(this);
  17064. }
  17065. BaseTexture.prototype.getScene = function () {
  17066. return this._scene;
  17067. };
  17068. BaseTexture.prototype.getTextureMatrix = function () {
  17069. return null;
  17070. };
  17071. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17072. return null;
  17073. };
  17074. BaseTexture.prototype.getInternalTexture = function () {
  17075. return this._texture;
  17076. };
  17077. BaseTexture.prototype.isReady = function () {
  17078. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17079. return true;
  17080. }
  17081. if (this._texture) {
  17082. return this._texture.isReady;
  17083. }
  17084. return false;
  17085. };
  17086. BaseTexture.prototype.getSize = function () {
  17087. if (this._texture._width) {
  17088. return { width: this._texture._width, height: this._texture._height };
  17089. }
  17090. if (this._texture._size) {
  17091. return { width: this._texture._size, height: this._texture._size };
  17092. }
  17093. return { width: 0, height: 0 };
  17094. };
  17095. BaseTexture.prototype.getBaseSize = function () {
  17096. if (!this.isReady())
  17097. return { width: 0, height: 0 };
  17098. if (this._texture._size) {
  17099. return { width: this._texture._size, height: this._texture._size };
  17100. }
  17101. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17102. };
  17103. BaseTexture.prototype.scale = function (ratio) {
  17104. };
  17105. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17106. get: function () {
  17107. return false;
  17108. },
  17109. enumerable: true,
  17110. configurable: true
  17111. });
  17112. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17113. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17114. for (var index = 0; index < texturesCache.length; index++) {
  17115. var texturesCacheEntry = texturesCache[index];
  17116. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17117. texturesCache.splice(index, 1);
  17118. return;
  17119. }
  17120. }
  17121. };
  17122. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17123. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17124. for (var index = 0; index < texturesCache.length; index++) {
  17125. var texturesCacheEntry = texturesCache[index];
  17126. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17127. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17128. texturesCacheEntry.references++;
  17129. return texturesCacheEntry;
  17130. }
  17131. }
  17132. }
  17133. return null;
  17134. };
  17135. BaseTexture.prototype.delayLoad = function () {
  17136. };
  17137. BaseTexture.prototype.clone = function () {
  17138. return null;
  17139. };
  17140. BaseTexture.prototype.releaseInternalTexture = function () {
  17141. if (this._texture) {
  17142. this._scene.getEngine().releaseInternalTexture(this._texture);
  17143. delete this._texture;
  17144. }
  17145. };
  17146. BaseTexture.prototype.dispose = function () {
  17147. // Animations
  17148. this.getScene().stopAnimation(this);
  17149. // Remove from scene
  17150. var index = this._scene.textures.indexOf(this);
  17151. if (index >= 0) {
  17152. this._scene.textures.splice(index, 1);
  17153. }
  17154. if (this._texture === undefined) {
  17155. return;
  17156. }
  17157. // Release
  17158. this.releaseInternalTexture();
  17159. // Callback
  17160. if (this.onDispose) {
  17161. this.onDispose();
  17162. }
  17163. };
  17164. BaseTexture.prototype.serialize = function () {
  17165. var serializationObject = {};
  17166. if (!this.name) {
  17167. return null;
  17168. }
  17169. serializationObject.name = this.name;
  17170. serializationObject.hasAlpha = this.hasAlpha;
  17171. serializationObject.level = this.level;
  17172. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17173. serializationObject.coordinatesMode = this.coordinatesMode;
  17174. serializationObject.wrapU = this.wrapU;
  17175. serializationObject.wrapV = this.wrapV;
  17176. // Animations
  17177. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17178. return serializationObject;
  17179. };
  17180. return BaseTexture;
  17181. })();
  17182. BABYLON.BaseTexture = BaseTexture;
  17183. })(BABYLON || (BABYLON = {}));
  17184. var BABYLON;
  17185. (function (BABYLON) {
  17186. var Texture = (function (_super) {
  17187. __extends(Texture, _super);
  17188. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17189. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17190. if (onLoad === void 0) { onLoad = null; }
  17191. if (onError === void 0) { onError = null; }
  17192. if (buffer === void 0) { buffer = null; }
  17193. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17194. _super.call(this, scene);
  17195. this.uOffset = 0;
  17196. this.vOffset = 0;
  17197. this.uScale = 1.0;
  17198. this.vScale = 1.0;
  17199. this.uAng = 0;
  17200. this.vAng = 0;
  17201. this.wAng = 0;
  17202. this.name = url;
  17203. this.url = url;
  17204. this._noMipmap = noMipmap;
  17205. this._invertY = invertY;
  17206. this._samplingMode = samplingMode;
  17207. this._buffer = buffer;
  17208. this._deleteBuffer = deleteBuffer;
  17209. if (!url) {
  17210. return;
  17211. }
  17212. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17213. if (!this._texture) {
  17214. if (!scene.useDelayedTextureLoading) {
  17215. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17216. if (deleteBuffer) {
  17217. delete this._buffer;
  17218. }
  17219. }
  17220. else {
  17221. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17222. }
  17223. }
  17224. else {
  17225. BABYLON.Tools.SetImmediate(function () {
  17226. if (onLoad) {
  17227. onLoad();
  17228. }
  17229. });
  17230. }
  17231. }
  17232. Texture.prototype.delayLoad = function () {
  17233. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17234. return;
  17235. }
  17236. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17237. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17238. if (!this._texture) {
  17239. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17240. if (this._deleteBuffer) {
  17241. delete this._buffer;
  17242. }
  17243. }
  17244. };
  17245. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17246. if (!this._texture) {
  17247. return;
  17248. }
  17249. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17250. };
  17251. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17252. x *= this.uScale;
  17253. y *= this.vScale;
  17254. x -= 0.5 * this.uScale;
  17255. y -= 0.5 * this.vScale;
  17256. z -= 0.5;
  17257. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17258. t.x += 0.5 * this.uScale + this.uOffset;
  17259. t.y += 0.5 * this.vScale + this.vOffset;
  17260. t.z += 0.5;
  17261. };
  17262. Texture.prototype.getTextureMatrix = function () {
  17263. if (this.uOffset === this._cachedUOffset &&
  17264. this.vOffset === this._cachedVOffset &&
  17265. this.uScale === this._cachedUScale &&
  17266. this.vScale === this._cachedVScale &&
  17267. this.uAng === this._cachedUAng &&
  17268. this.vAng === this._cachedVAng &&
  17269. this.wAng === this._cachedWAng) {
  17270. return this._cachedTextureMatrix;
  17271. }
  17272. this._cachedUOffset = this.uOffset;
  17273. this._cachedVOffset = this.vOffset;
  17274. this._cachedUScale = this.uScale;
  17275. this._cachedVScale = this.vScale;
  17276. this._cachedUAng = this.uAng;
  17277. this._cachedVAng = this.vAng;
  17278. this._cachedWAng = this.wAng;
  17279. if (!this._cachedTextureMatrix) {
  17280. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17281. this._rowGenerationMatrix = new BABYLON.Matrix();
  17282. this._t0 = BABYLON.Vector3.Zero();
  17283. this._t1 = BABYLON.Vector3.Zero();
  17284. this._t2 = BABYLON.Vector3.Zero();
  17285. }
  17286. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17287. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17288. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17289. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17290. this._t1.subtractInPlace(this._t0);
  17291. this._t2.subtractInPlace(this._t0);
  17292. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17293. this._cachedTextureMatrix.m[0] = this._t1.x;
  17294. this._cachedTextureMatrix.m[1] = this._t1.y;
  17295. this._cachedTextureMatrix.m[2] = this._t1.z;
  17296. this._cachedTextureMatrix.m[4] = this._t2.x;
  17297. this._cachedTextureMatrix.m[5] = this._t2.y;
  17298. this._cachedTextureMatrix.m[6] = this._t2.z;
  17299. this._cachedTextureMatrix.m[8] = this._t0.x;
  17300. this._cachedTextureMatrix.m[9] = this._t0.y;
  17301. this._cachedTextureMatrix.m[10] = this._t0.z;
  17302. return this._cachedTextureMatrix;
  17303. };
  17304. Texture.prototype.getReflectionTextureMatrix = function () {
  17305. if (this.uOffset === this._cachedUOffset &&
  17306. this.vOffset === this._cachedVOffset &&
  17307. this.uScale === this._cachedUScale &&
  17308. this.vScale === this._cachedVScale &&
  17309. this.coordinatesMode === this._cachedCoordinatesMode) {
  17310. return this._cachedTextureMatrix;
  17311. }
  17312. if (!this._cachedTextureMatrix) {
  17313. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17314. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17315. }
  17316. this._cachedCoordinatesMode = this.coordinatesMode;
  17317. switch (this.coordinatesMode) {
  17318. case Texture.PLANAR_MODE:
  17319. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17320. this._cachedTextureMatrix[0] = this.uScale;
  17321. this._cachedTextureMatrix[5] = this.vScale;
  17322. this._cachedTextureMatrix[12] = this.uOffset;
  17323. this._cachedTextureMatrix[13] = this.vOffset;
  17324. break;
  17325. case Texture.PROJECTION_MODE:
  17326. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17327. this._projectionModeMatrix.m[0] = 0.5;
  17328. this._projectionModeMatrix.m[5] = -0.5;
  17329. this._projectionModeMatrix.m[10] = 0.0;
  17330. this._projectionModeMatrix.m[12] = 0.5;
  17331. this._projectionModeMatrix.m[13] = 0.5;
  17332. this._projectionModeMatrix.m[14] = 1.0;
  17333. this._projectionModeMatrix.m[15] = 1.0;
  17334. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17335. break;
  17336. default:
  17337. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17338. break;
  17339. }
  17340. return this._cachedTextureMatrix;
  17341. };
  17342. Texture.prototype.clone = function () {
  17343. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17344. // Base texture
  17345. newTexture.hasAlpha = this.hasAlpha;
  17346. newTexture.level = this.level;
  17347. newTexture.wrapU = this.wrapU;
  17348. newTexture.wrapV = this.wrapV;
  17349. newTexture.coordinatesIndex = this.coordinatesIndex;
  17350. newTexture.coordinatesMode = this.coordinatesMode;
  17351. // Texture
  17352. newTexture.uOffset = this.uOffset;
  17353. newTexture.vOffset = this.vOffset;
  17354. newTexture.uScale = this.uScale;
  17355. newTexture.vScale = this.vScale;
  17356. newTexture.uAng = this.uAng;
  17357. newTexture.vAng = this.vAng;
  17358. newTexture.wAng = this.wAng;
  17359. return newTexture;
  17360. };
  17361. Texture.prototype.serialize = function () {
  17362. if (!this.name) {
  17363. return null;
  17364. }
  17365. var serializationObject = _super.prototype.serialize.call(this);
  17366. serializationObject.uOffset = this.uOffset;
  17367. serializationObject.vOffset = this.vOffset;
  17368. serializationObject.uScale = this.uScale;
  17369. serializationObject.vScale = this.vScale;
  17370. serializationObject.uAng = this.uAng;
  17371. serializationObject.vAng = this.vAng;
  17372. serializationObject.wAng = this.wAng;
  17373. return serializationObject;
  17374. };
  17375. // Statics
  17376. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17377. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17378. if (onLoad === void 0) { onLoad = null; }
  17379. if (onError === void 0) { onError = null; }
  17380. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17381. };
  17382. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17383. if (parsedTexture.isCube) {
  17384. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17385. }
  17386. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17387. return null;
  17388. }
  17389. var texture;
  17390. if (parsedTexture.mirrorPlane) {
  17391. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17392. texture._waitingRenderList = parsedTexture.renderList;
  17393. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17394. }
  17395. else if (parsedTexture.isRenderTarget) {
  17396. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17397. texture._waitingRenderList = parsedTexture.renderList;
  17398. }
  17399. else {
  17400. if (parsedTexture.base64String) {
  17401. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17402. }
  17403. else {
  17404. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17405. }
  17406. }
  17407. texture.name = parsedTexture.name;
  17408. texture.hasAlpha = parsedTexture.hasAlpha;
  17409. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17410. texture.level = parsedTexture.level;
  17411. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17412. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17413. texture.uOffset = parsedTexture.uOffset;
  17414. texture.vOffset = parsedTexture.vOffset;
  17415. texture.uScale = parsedTexture.uScale;
  17416. texture.vScale = parsedTexture.vScale;
  17417. texture.uAng = parsedTexture.uAng;
  17418. texture.vAng = parsedTexture.vAng;
  17419. texture.wAng = parsedTexture.wAng;
  17420. texture.wrapU = parsedTexture.wrapU;
  17421. texture.wrapV = parsedTexture.wrapV;
  17422. // Animations
  17423. if (parsedTexture.animations) {
  17424. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17425. var parsedAnimation = parsedTexture.animations[animationIndex];
  17426. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17427. }
  17428. }
  17429. return texture;
  17430. };
  17431. // Constants
  17432. Texture.NEAREST_SAMPLINGMODE = 1;
  17433. Texture.BILINEAR_SAMPLINGMODE = 2;
  17434. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17435. Texture.EXPLICIT_MODE = 0;
  17436. Texture.SPHERICAL_MODE = 1;
  17437. Texture.PLANAR_MODE = 2;
  17438. Texture.CUBIC_MODE = 3;
  17439. Texture.PROJECTION_MODE = 4;
  17440. Texture.SKYBOX_MODE = 5;
  17441. Texture.INVCUBIC_MODE = 6;
  17442. Texture.EQUIRECTANGULAR_MODE = 7;
  17443. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17444. Texture.CLAMP_ADDRESSMODE = 0;
  17445. Texture.WRAP_ADDRESSMODE = 1;
  17446. Texture.MIRROR_ADDRESSMODE = 2;
  17447. return Texture;
  17448. })(BABYLON.BaseTexture);
  17449. BABYLON.Texture = Texture;
  17450. })(BABYLON || (BABYLON = {}));
  17451. var BABYLON;
  17452. (function (BABYLON) {
  17453. var CubeTexture = (function (_super) {
  17454. __extends(CubeTexture, _super);
  17455. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17456. _super.call(this, scene);
  17457. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17458. this.name = rootUrl;
  17459. this.url = rootUrl;
  17460. this._noMipmap = noMipmap;
  17461. this.hasAlpha = false;
  17462. if (!rootUrl) {
  17463. return;
  17464. }
  17465. this._texture = this._getFromCache(rootUrl, noMipmap);
  17466. if (!extensions) {
  17467. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17468. }
  17469. this._extensions = extensions;
  17470. if (!this._texture) {
  17471. if (!scene.useDelayedTextureLoading) {
  17472. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17473. }
  17474. else {
  17475. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17476. }
  17477. }
  17478. this.isCube = true;
  17479. this._textureMatrix = BABYLON.Matrix.Identity();
  17480. }
  17481. CubeTexture.prototype.clone = function () {
  17482. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17483. // Base texture
  17484. newTexture.level = this.level;
  17485. newTexture.wrapU = this.wrapU;
  17486. newTexture.wrapV = this.wrapV;
  17487. newTexture.coordinatesIndex = this.coordinatesIndex;
  17488. newTexture.coordinatesMode = this.coordinatesMode;
  17489. return newTexture;
  17490. };
  17491. // Methods
  17492. CubeTexture.prototype.delayLoad = function () {
  17493. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17494. return;
  17495. }
  17496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17497. this._texture = this._getFromCache(this.url, this._noMipmap);
  17498. if (!this._texture) {
  17499. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17500. }
  17501. };
  17502. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17503. return this._textureMatrix;
  17504. };
  17505. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17506. var texture = null;
  17507. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17508. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17509. texture.name = parsedTexture.name;
  17510. texture.hasAlpha = parsedTexture.hasAlpha;
  17511. texture.level = parsedTexture.level;
  17512. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17513. }
  17514. return texture;
  17515. };
  17516. CubeTexture.prototype.serialize = function () {
  17517. if (!this.name) {
  17518. return null;
  17519. }
  17520. var serializationObject = {};
  17521. serializationObject.name = this.name;
  17522. serializationObject.hasAlpha = this.hasAlpha;
  17523. serializationObject.isCube = true;
  17524. serializationObject.level = this.level;
  17525. serializationObject.coordinatesMode = this.coordinatesMode;
  17526. return serializationObject;
  17527. };
  17528. return CubeTexture;
  17529. })(BABYLON.BaseTexture);
  17530. BABYLON.CubeTexture = CubeTexture;
  17531. })(BABYLON || (BABYLON = {}));
  17532. var BABYLON;
  17533. (function (BABYLON) {
  17534. var RenderTargetTexture = (function (_super) {
  17535. __extends(RenderTargetTexture, _super);
  17536. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17537. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17538. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17539. if (isCube === void 0) { isCube = false; }
  17540. _super.call(this, null, scene, !generateMipMaps);
  17541. this.isCube = isCube;
  17542. this.renderList = new Array();
  17543. this.renderParticles = true;
  17544. this.renderSprites = false;
  17545. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17546. this._currentRefreshId = -1;
  17547. this._refreshRate = 1;
  17548. this.name = name;
  17549. this.isRenderTarget = true;
  17550. this._size = size;
  17551. this._generateMipMaps = generateMipMaps;
  17552. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17553. if (isCube) {
  17554. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17555. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17556. this._textureMatrix = BABYLON.Matrix.Identity();
  17557. }
  17558. else {
  17559. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17560. }
  17561. // Rendering groups
  17562. this._renderingManager = new BABYLON.RenderingManager(scene);
  17563. }
  17564. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17565. get: function () {
  17566. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17567. },
  17568. enumerable: true,
  17569. configurable: true
  17570. });
  17571. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17572. get: function () {
  17573. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17574. },
  17575. enumerable: true,
  17576. configurable: true
  17577. });
  17578. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17579. get: function () {
  17580. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17581. },
  17582. enumerable: true,
  17583. configurable: true
  17584. });
  17585. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17586. this._currentRefreshId = -1;
  17587. };
  17588. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17589. get: function () {
  17590. return this._refreshRate;
  17591. },
  17592. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17593. set: function (value) {
  17594. this._refreshRate = value;
  17595. this.resetRefreshCounter();
  17596. },
  17597. enumerable: true,
  17598. configurable: true
  17599. });
  17600. RenderTargetTexture.prototype._shouldRender = function () {
  17601. if (this._currentRefreshId === -1) {
  17602. this._currentRefreshId = 1;
  17603. return true;
  17604. }
  17605. if (this.refreshRate === this._currentRefreshId) {
  17606. this._currentRefreshId = 1;
  17607. return true;
  17608. }
  17609. this._currentRefreshId++;
  17610. return false;
  17611. };
  17612. RenderTargetTexture.prototype.isReady = function () {
  17613. if (!this.getScene().renderTargetsEnabled) {
  17614. return false;
  17615. }
  17616. return _super.prototype.isReady.call(this);
  17617. };
  17618. RenderTargetTexture.prototype.getRenderSize = function () {
  17619. return this._size;
  17620. };
  17621. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17622. get: function () {
  17623. return true;
  17624. },
  17625. enumerable: true,
  17626. configurable: true
  17627. });
  17628. RenderTargetTexture.prototype.scale = function (ratio) {
  17629. var newSize = this._size * ratio;
  17630. this.resize(newSize, this._generateMipMaps);
  17631. };
  17632. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17633. if (this.isCube) {
  17634. return this._textureMatrix;
  17635. }
  17636. return _super.prototype.getReflectionTextureMatrix.call(this);
  17637. };
  17638. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17639. this.releaseInternalTexture();
  17640. if (this.isCube) {
  17641. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17642. }
  17643. else {
  17644. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17645. }
  17646. };
  17647. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17648. var scene = this.getScene();
  17649. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17650. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17651. }
  17652. if (this._waitingRenderList) {
  17653. this.renderList = [];
  17654. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17655. var id = this._waitingRenderList[index];
  17656. this.renderList.push(scene.getMeshByID(id));
  17657. }
  17658. delete this._waitingRenderList;
  17659. }
  17660. if (this.renderList && this.renderList.length === 0) {
  17661. return;
  17662. }
  17663. // Prepare renderingManager
  17664. this._renderingManager.reset();
  17665. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17666. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17667. var mesh = currentRenderList[meshIndex];
  17668. if (mesh) {
  17669. if (!mesh.isReady()) {
  17670. // Reset _currentRefreshId
  17671. this.resetRefreshCounter();
  17672. continue;
  17673. }
  17674. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17675. mesh._activate(scene.getRenderId());
  17676. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17677. var subMesh = mesh.subMeshes[subIndex];
  17678. scene._activeIndices += subMesh.indexCount;
  17679. this._renderingManager.dispatch(subMesh);
  17680. }
  17681. }
  17682. }
  17683. }
  17684. if (this.isCube) {
  17685. for (var face = 0; face < 6; face++) {
  17686. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17687. scene.incrementRenderId();
  17688. }
  17689. }
  17690. else {
  17691. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17692. }
  17693. if (this.onAfterUnbind) {
  17694. this.onAfterUnbind();
  17695. }
  17696. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17697. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17698. }
  17699. scene.resetCachedMaterial();
  17700. };
  17701. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17702. var scene = this.getScene();
  17703. var engine = scene.getEngine();
  17704. // Bind
  17705. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17706. if (this.isCube) {
  17707. engine.bindFramebuffer(this._texture, faceIndex);
  17708. }
  17709. else {
  17710. engine.bindFramebuffer(this._texture);
  17711. }
  17712. }
  17713. if (this.onBeforeRender) {
  17714. this.onBeforeRender(faceIndex);
  17715. }
  17716. // Clear
  17717. if (this.onClear) {
  17718. this.onClear(engine);
  17719. }
  17720. else {
  17721. engine.clear(scene.clearColor, true, true);
  17722. }
  17723. if (!this._doNotChangeAspectRatio) {
  17724. scene.updateTransformMatrix(true);
  17725. }
  17726. // Render
  17727. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17728. if (useCameraPostProcess) {
  17729. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17730. }
  17731. if (!this._doNotChangeAspectRatio) {
  17732. scene.updateTransformMatrix(true);
  17733. }
  17734. if (this.onAfterRender) {
  17735. this.onAfterRender(faceIndex);
  17736. }
  17737. // Dump ?
  17738. if (dumpForDebug) {
  17739. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17740. }
  17741. // Unbind
  17742. if (!this.isCube || faceIndex === 5) {
  17743. if (this.isCube) {
  17744. if (faceIndex === 5) {
  17745. engine.generateMipMapsForCubemap(this._texture);
  17746. }
  17747. }
  17748. engine.unBindFramebuffer(this._texture, this.isCube);
  17749. }
  17750. };
  17751. RenderTargetTexture.prototype.clone = function () {
  17752. var textureSize = this.getSize();
  17753. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17754. // Base texture
  17755. newTexture.hasAlpha = this.hasAlpha;
  17756. newTexture.level = this.level;
  17757. // RenderTarget Texture
  17758. newTexture.coordinatesMode = this.coordinatesMode;
  17759. newTexture.renderList = this.renderList.slice(0);
  17760. return newTexture;
  17761. };
  17762. RenderTargetTexture.prototype.serialize = function () {
  17763. if (!this.name) {
  17764. return null;
  17765. }
  17766. var serializationObject = _super.prototype.serialize.call(this);
  17767. serializationObject.renderTargetSize = this.getRenderSize();
  17768. serializationObject.renderList = [];
  17769. for (var index = 0; index < this.renderList.length; index++) {
  17770. serializationObject.renderList.push(this.renderList[index].id);
  17771. }
  17772. return serializationObject;
  17773. };
  17774. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  17775. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  17776. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  17777. return RenderTargetTexture;
  17778. })(BABYLON.Texture);
  17779. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17780. })(BABYLON || (BABYLON = {}));
  17781. var BABYLON;
  17782. (function (BABYLON) {
  17783. var ProceduralTexture = (function (_super) {
  17784. __extends(ProceduralTexture, _super);
  17785. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17786. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17787. _super.call(this, null, scene, !generateMipMaps);
  17788. this.isEnabled = true;
  17789. this._currentRefreshId = -1;
  17790. this._refreshRate = 1;
  17791. this._vertexDeclaration = [2];
  17792. this._vertexStrideSize = 2 * 4;
  17793. this._uniforms = new Array();
  17794. this._samplers = new Array();
  17795. this._textures = new Array();
  17796. this._floats = new Array();
  17797. this._floatsArrays = {};
  17798. this._colors3 = new Array();
  17799. this._colors4 = new Array();
  17800. this._vectors2 = new Array();
  17801. this._vectors3 = new Array();
  17802. this._matrices = new Array();
  17803. this._fallbackTextureUsed = false;
  17804. scene._proceduralTextures.push(this);
  17805. this.name = name;
  17806. this.isRenderTarget = true;
  17807. this._size = size;
  17808. this._generateMipMaps = generateMipMaps;
  17809. this.setFragment(fragment);
  17810. this._fallbackTexture = fallbackTexture;
  17811. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17812. // VBO
  17813. var vertices = [];
  17814. vertices.push(1, 1);
  17815. vertices.push(-1, 1);
  17816. vertices.push(-1, -1);
  17817. vertices.push(1, -1);
  17818. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17819. // Indices
  17820. var indices = [];
  17821. indices.push(0);
  17822. indices.push(1);
  17823. indices.push(2);
  17824. indices.push(0);
  17825. indices.push(2);
  17826. indices.push(3);
  17827. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17828. }
  17829. ProceduralTexture.prototype.reset = function () {
  17830. if (this._effect === undefined) {
  17831. return;
  17832. }
  17833. var engine = this.getScene().getEngine();
  17834. engine._releaseEffect(this._effect);
  17835. };
  17836. ProceduralTexture.prototype.isReady = function () {
  17837. var _this = this;
  17838. var engine = this.getScene().getEngine();
  17839. var shaders;
  17840. if (!this._fragment) {
  17841. return false;
  17842. }
  17843. if (this._fallbackTextureUsed) {
  17844. return true;
  17845. }
  17846. if (this._fragment.fragmentElement !== undefined) {
  17847. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17848. }
  17849. else {
  17850. shaders = { vertex: "procedural", fragment: this._fragment };
  17851. }
  17852. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17853. _this.releaseInternalTexture();
  17854. if (_this._fallbackTexture) {
  17855. _this._texture = _this._fallbackTexture._texture;
  17856. _this._texture.references++;
  17857. }
  17858. _this._fallbackTextureUsed = true;
  17859. });
  17860. return this._effect.isReady();
  17861. };
  17862. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17863. this._currentRefreshId = -1;
  17864. };
  17865. ProceduralTexture.prototype.setFragment = function (fragment) {
  17866. this._fragment = fragment;
  17867. };
  17868. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17869. get: function () {
  17870. return this._refreshRate;
  17871. },
  17872. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17873. set: function (value) {
  17874. this._refreshRate = value;
  17875. this.resetRefreshCounter();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. ProceduralTexture.prototype._shouldRender = function () {
  17881. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17882. return false;
  17883. }
  17884. if (this._fallbackTextureUsed) {
  17885. return false;
  17886. }
  17887. if (this._currentRefreshId === -1) {
  17888. this._currentRefreshId = 1;
  17889. return true;
  17890. }
  17891. if (this.refreshRate === this._currentRefreshId) {
  17892. this._currentRefreshId = 1;
  17893. return true;
  17894. }
  17895. this._currentRefreshId++;
  17896. return false;
  17897. };
  17898. ProceduralTexture.prototype.getRenderSize = function () {
  17899. return this._size;
  17900. };
  17901. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17902. if (this._fallbackTextureUsed) {
  17903. return;
  17904. }
  17905. this.releaseInternalTexture();
  17906. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17907. };
  17908. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17909. if (this._uniforms.indexOf(uniformName) === -1) {
  17910. this._uniforms.push(uniformName);
  17911. }
  17912. };
  17913. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17914. if (this._samplers.indexOf(name) === -1) {
  17915. this._samplers.push(name);
  17916. }
  17917. this._textures[name] = texture;
  17918. return this;
  17919. };
  17920. ProceduralTexture.prototype.setFloat = function (name, value) {
  17921. this._checkUniform(name);
  17922. this._floats[name] = value;
  17923. return this;
  17924. };
  17925. ProceduralTexture.prototype.setFloats = function (name, value) {
  17926. this._checkUniform(name);
  17927. this._floatsArrays[name] = value;
  17928. return this;
  17929. };
  17930. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17931. this._checkUniform(name);
  17932. this._colors3[name] = value;
  17933. return this;
  17934. };
  17935. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17936. this._checkUniform(name);
  17937. this._colors4[name] = value;
  17938. return this;
  17939. };
  17940. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17941. this._checkUniform(name);
  17942. this._vectors2[name] = value;
  17943. return this;
  17944. };
  17945. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17946. this._checkUniform(name);
  17947. this._vectors3[name] = value;
  17948. return this;
  17949. };
  17950. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17951. this._checkUniform(name);
  17952. this._matrices[name] = value;
  17953. return this;
  17954. };
  17955. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17956. var scene = this.getScene();
  17957. var engine = scene.getEngine();
  17958. engine.bindFramebuffer(this._texture);
  17959. // Clear
  17960. engine.clear(scene.clearColor, true, true);
  17961. // Render
  17962. engine.enableEffect(this._effect);
  17963. engine.setState(false);
  17964. // Texture
  17965. for (var name in this._textures) {
  17966. this._effect.setTexture(name, this._textures[name]);
  17967. }
  17968. // Float
  17969. for (name in this._floats) {
  17970. this._effect.setFloat(name, this._floats[name]);
  17971. }
  17972. // Floats
  17973. for (name in this._floatsArrays) {
  17974. this._effect.setArray(name, this._floatsArrays[name]);
  17975. }
  17976. // Color3
  17977. for (name in this._colors3) {
  17978. this._effect.setColor3(name, this._colors3[name]);
  17979. }
  17980. // Color4
  17981. for (name in this._colors4) {
  17982. var color = this._colors4[name];
  17983. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17984. }
  17985. // Vector2
  17986. for (name in this._vectors2) {
  17987. this._effect.setVector2(name, this._vectors2[name]);
  17988. }
  17989. // Vector3
  17990. for (name in this._vectors3) {
  17991. this._effect.setVector3(name, this._vectors3[name]);
  17992. }
  17993. // Matrix
  17994. for (name in this._matrices) {
  17995. this._effect.setMatrix(name, this._matrices[name]);
  17996. }
  17997. // VBOs
  17998. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17999. // Draw order
  18000. engine.draw(true, 0, 6);
  18001. // Unbind
  18002. engine.unBindFramebuffer(this._texture);
  18003. };
  18004. ProceduralTexture.prototype.clone = function () {
  18005. var textureSize = this.getSize();
  18006. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18007. // Base texture
  18008. newTexture.hasAlpha = this.hasAlpha;
  18009. newTexture.level = this.level;
  18010. // RenderTarget Texture
  18011. newTexture.coordinatesMode = this.coordinatesMode;
  18012. return newTexture;
  18013. };
  18014. ProceduralTexture.prototype.dispose = function () {
  18015. var index = this.getScene()._proceduralTextures.indexOf(this);
  18016. if (index >= 0) {
  18017. this.getScene()._proceduralTextures.splice(index, 1);
  18018. }
  18019. _super.prototype.dispose.call(this);
  18020. };
  18021. return ProceduralTexture;
  18022. })(BABYLON.Texture);
  18023. BABYLON.ProceduralTexture = ProceduralTexture;
  18024. })(BABYLON || (BABYLON = {}));
  18025. var BABYLON;
  18026. (function (BABYLON) {
  18027. var MirrorTexture = (function (_super) {
  18028. __extends(MirrorTexture, _super);
  18029. function MirrorTexture(name, size, scene, generateMipMaps) {
  18030. var _this = this;
  18031. _super.call(this, name, size, scene, generateMipMaps, true);
  18032. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18033. this._transformMatrix = BABYLON.Matrix.Zero();
  18034. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18035. this.onBeforeRender = function () {
  18036. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18037. _this._savedViewMatrix = scene.getViewMatrix();
  18038. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18039. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18040. scene.clipPlane = _this.mirrorPlane;
  18041. scene.getEngine().cullBackFaces = false;
  18042. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18043. };
  18044. this.onAfterRender = function () {
  18045. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18046. scene.getEngine().cullBackFaces = true;
  18047. scene._mirroredCameraPosition = null;
  18048. delete scene.clipPlane;
  18049. };
  18050. }
  18051. MirrorTexture.prototype.clone = function () {
  18052. var textureSize = this.getSize();
  18053. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18054. // Base texture
  18055. newTexture.hasAlpha = this.hasAlpha;
  18056. newTexture.level = this.level;
  18057. // Mirror Texture
  18058. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18059. newTexture.renderList = this.renderList.slice(0);
  18060. return newTexture;
  18061. };
  18062. MirrorTexture.prototype.serialize = function () {
  18063. if (!this.name) {
  18064. return null;
  18065. }
  18066. var serializationObject = _super.prototype.serialize.call(this);
  18067. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18068. return serializationObject;
  18069. };
  18070. return MirrorTexture;
  18071. })(BABYLON.RenderTargetTexture);
  18072. BABYLON.MirrorTexture = MirrorTexture;
  18073. })(BABYLON || (BABYLON = {}));
  18074. var BABYLON;
  18075. (function (BABYLON) {
  18076. var DynamicTexture = (function (_super) {
  18077. __extends(DynamicTexture, _super);
  18078. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18080. _super.call(this, null, scene, !generateMipMaps);
  18081. this.name = name;
  18082. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18083. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18084. this._generateMipMaps = generateMipMaps;
  18085. if (options.getContext) {
  18086. this._canvas = options;
  18087. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18088. }
  18089. else {
  18090. this._canvas = document.createElement("canvas");
  18091. if (options.width) {
  18092. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18093. }
  18094. else {
  18095. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18096. }
  18097. }
  18098. var textureSize = this.getSize();
  18099. this._canvas.width = textureSize.width;
  18100. this._canvas.height = textureSize.height;
  18101. this._context = this._canvas.getContext("2d");
  18102. }
  18103. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18104. get: function () {
  18105. return true;
  18106. },
  18107. enumerable: true,
  18108. configurable: true
  18109. });
  18110. DynamicTexture.prototype.scale = function (ratio) {
  18111. var textureSize = this.getSize();
  18112. textureSize.width *= ratio;
  18113. textureSize.height *= ratio;
  18114. this._canvas.width = textureSize.width;
  18115. this._canvas.height = textureSize.height;
  18116. this.releaseInternalTexture();
  18117. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18118. };
  18119. DynamicTexture.prototype.getContext = function () {
  18120. return this._context;
  18121. };
  18122. DynamicTexture.prototype.clear = function () {
  18123. var size = this.getSize();
  18124. this._context.fillRect(0, 0, size.width, size.height);
  18125. };
  18126. DynamicTexture.prototype.update = function (invertY) {
  18127. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18128. };
  18129. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18130. if (update === void 0) { update = true; }
  18131. var size = this.getSize();
  18132. if (clearColor) {
  18133. this._context.fillStyle = clearColor;
  18134. this._context.fillRect(0, 0, size.width, size.height);
  18135. }
  18136. this._context.font = font;
  18137. if (x === null) {
  18138. var textSize = this._context.measureText(text);
  18139. x = (size.width - textSize.width) / 2;
  18140. }
  18141. this._context.fillStyle = color;
  18142. this._context.fillText(text, x, y);
  18143. if (update) {
  18144. this.update(invertY);
  18145. }
  18146. };
  18147. DynamicTexture.prototype.clone = function () {
  18148. var textureSize = this.getSize();
  18149. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18150. // Base texture
  18151. newTexture.hasAlpha = this.hasAlpha;
  18152. newTexture.level = this.level;
  18153. // Dynamic Texture
  18154. newTexture.wrapU = this.wrapU;
  18155. newTexture.wrapV = this.wrapV;
  18156. return newTexture;
  18157. };
  18158. return DynamicTexture;
  18159. })(BABYLON.Texture);
  18160. BABYLON.DynamicTexture = DynamicTexture;
  18161. })(BABYLON || (BABYLON = {}));
  18162. var BABYLON;
  18163. (function (BABYLON) {
  18164. var VideoTexture = (function (_super) {
  18165. __extends(VideoTexture, _super);
  18166. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18167. var _this = this;
  18168. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18169. if (invertY === void 0) { invertY = false; }
  18170. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18171. _super.call(this, null, scene, !generateMipMaps, invertY);
  18172. this._autoLaunch = true;
  18173. this.name = name;
  18174. this.video = document.createElement("video");
  18175. this.video.autoplay = false;
  18176. this.video.loop = true;
  18177. this.video.addEventListener("canplaythrough", function () {
  18178. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18179. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18180. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18181. }
  18182. else {
  18183. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18184. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18185. generateMipMaps = false;
  18186. }
  18187. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18188. _this._texture.isReady = true;
  18189. });
  18190. urls.forEach(function (url) {
  18191. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18192. var source = document.createElement("source");
  18193. source.src = url;
  18194. _this.video.appendChild(source);
  18195. });
  18196. this._lastUpdate = BABYLON.Tools.Now;
  18197. }
  18198. VideoTexture.prototype.update = function () {
  18199. if (this._autoLaunch) {
  18200. this._autoLaunch = false;
  18201. this.video.play();
  18202. }
  18203. var now = BABYLON.Tools.Now;
  18204. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18205. return false;
  18206. }
  18207. this._lastUpdate = now;
  18208. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18209. return true;
  18210. };
  18211. return VideoTexture;
  18212. })(BABYLON.Texture);
  18213. BABYLON.VideoTexture = VideoTexture;
  18214. })(BABYLON || (BABYLON = {}));
  18215. var BABYLON;
  18216. (function (BABYLON) {
  18217. var CustomProceduralTexture = (function (_super) {
  18218. __extends(CustomProceduralTexture, _super);
  18219. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18220. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18221. this._animate = true;
  18222. this._time = 0;
  18223. this._texturePath = texturePath;
  18224. //Try to load json
  18225. this.loadJson(texturePath);
  18226. this.refreshRate = 1;
  18227. }
  18228. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18229. var _this = this;
  18230. var that = this;
  18231. function noConfigFile() {
  18232. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18233. try {
  18234. that.setFragment(that._texturePath);
  18235. }
  18236. catch (ex) {
  18237. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18238. }
  18239. }
  18240. var configFileUrl = jsonUrl + "/config.json";
  18241. var xhr = new XMLHttpRequest();
  18242. xhr.open("GET", configFileUrl, true);
  18243. xhr.addEventListener("load", function () {
  18244. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18245. try {
  18246. _this._config = JSON.parse(xhr.response);
  18247. _this.updateShaderUniforms();
  18248. _this.updateTextures();
  18249. _this.setFragment(_this._texturePath + "/custom");
  18250. _this._animate = _this._config.animate;
  18251. _this.refreshRate = _this._config.refreshrate;
  18252. }
  18253. catch (ex) {
  18254. noConfigFile();
  18255. }
  18256. }
  18257. else {
  18258. noConfigFile();
  18259. }
  18260. }, false);
  18261. xhr.addEventListener("error", function () {
  18262. noConfigFile();
  18263. }, false);
  18264. try {
  18265. xhr.send();
  18266. }
  18267. catch (ex) {
  18268. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18269. }
  18270. };
  18271. CustomProceduralTexture.prototype.isReady = function () {
  18272. if (!_super.prototype.isReady.call(this)) {
  18273. return false;
  18274. }
  18275. for (var name in this._textures) {
  18276. var texture = this._textures[name];
  18277. if (!texture.isReady()) {
  18278. return false;
  18279. }
  18280. }
  18281. return true;
  18282. };
  18283. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18284. if (this._animate) {
  18285. this._time += this.getScene().getAnimationRatio() * 0.03;
  18286. this.updateShaderUniforms();
  18287. }
  18288. _super.prototype.render.call(this, useCameraPostProcess);
  18289. };
  18290. CustomProceduralTexture.prototype.updateTextures = function () {
  18291. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18292. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18293. }
  18294. };
  18295. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18296. if (this._config) {
  18297. for (var j = 0; j < this._config.uniforms.length; j++) {
  18298. var uniform = this._config.uniforms[j];
  18299. switch (uniform.type) {
  18300. case "float":
  18301. this.setFloat(uniform.name, uniform.value);
  18302. break;
  18303. case "color3":
  18304. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18305. break;
  18306. case "color4":
  18307. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18308. break;
  18309. case "vector2":
  18310. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18311. break;
  18312. case "vector3":
  18313. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18314. break;
  18315. }
  18316. }
  18317. }
  18318. this.setFloat("time", this._time);
  18319. };
  18320. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18321. get: function () {
  18322. return this._animate;
  18323. },
  18324. set: function (value) {
  18325. this._animate = value;
  18326. },
  18327. enumerable: true,
  18328. configurable: true
  18329. });
  18330. return CustomProceduralTexture;
  18331. })(BABYLON.ProceduralTexture);
  18332. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18333. })(BABYLON || (BABYLON = {}));
  18334. var BABYLON;
  18335. (function (BABYLON) {
  18336. var EffectFallbacks = (function () {
  18337. function EffectFallbacks() {
  18338. this._defines = {};
  18339. this._currentRank = 32;
  18340. this._maxRank = -1;
  18341. }
  18342. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18343. if (!this._defines[rank]) {
  18344. if (rank < this._currentRank) {
  18345. this._currentRank = rank;
  18346. }
  18347. if (rank > this._maxRank) {
  18348. this._maxRank = rank;
  18349. }
  18350. this._defines[rank] = new Array();
  18351. }
  18352. this._defines[rank].push(define);
  18353. };
  18354. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18355. this._meshRank = rank;
  18356. this._mesh = mesh;
  18357. if (rank > this._maxRank) {
  18358. this._maxRank = rank;
  18359. }
  18360. };
  18361. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18362. get: function () {
  18363. return this._currentRank <= this._maxRank;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18369. var currentFallbacks = this._defines[this._currentRank];
  18370. for (var index = 0; index < currentFallbacks.length; index++) {
  18371. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18372. }
  18373. if (this._mesh && this._currentRank === this._meshRank) {
  18374. this._mesh.computeBonesUsingShaders = false;
  18375. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18376. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18377. }
  18378. this._currentRank++;
  18379. return currentDefines;
  18380. };
  18381. return EffectFallbacks;
  18382. })();
  18383. BABYLON.EffectFallbacks = EffectFallbacks;
  18384. var Effect = (function () {
  18385. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18386. var _this = this;
  18387. this._isReady = false;
  18388. this._compilationError = "";
  18389. this._valueCache = [];
  18390. this._engine = engine;
  18391. this.name = baseName;
  18392. this.defines = defines;
  18393. this._uniformsNames = uniformsNames.concat(samplers);
  18394. this._samplers = samplers;
  18395. this._attributesNames = attributesNames;
  18396. this.onError = onError;
  18397. this.onCompiled = onCompiled;
  18398. var vertexSource;
  18399. var fragmentSource;
  18400. if (baseName.vertexElement) {
  18401. vertexSource = document.getElementById(baseName.vertexElement);
  18402. if (!vertexSource) {
  18403. vertexSource = baseName.vertexElement;
  18404. }
  18405. }
  18406. else {
  18407. vertexSource = baseName.vertex || baseName;
  18408. }
  18409. if (baseName.fragmentElement) {
  18410. fragmentSource = document.getElementById(baseName.fragmentElement);
  18411. if (!fragmentSource) {
  18412. fragmentSource = baseName.fragmentElement;
  18413. }
  18414. }
  18415. else {
  18416. fragmentSource = baseName.fragment || baseName;
  18417. }
  18418. this._loadVertexShader(vertexSource, function (vertexCode) {
  18419. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18420. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18421. });
  18422. });
  18423. }
  18424. // Properties
  18425. Effect.prototype.isReady = function () {
  18426. return this._isReady;
  18427. };
  18428. Effect.prototype.getProgram = function () {
  18429. return this._program;
  18430. };
  18431. Effect.prototype.getAttributesNames = function () {
  18432. return this._attributesNames;
  18433. };
  18434. Effect.prototype.getAttributeLocation = function (index) {
  18435. return this._attributes[index];
  18436. };
  18437. Effect.prototype.getAttributeLocationByName = function (name) {
  18438. var index = this._attributesNames.indexOf(name);
  18439. return this._attributes[index];
  18440. };
  18441. Effect.prototype.getAttributesCount = function () {
  18442. return this._attributes.length;
  18443. };
  18444. Effect.prototype.getUniformIndex = function (uniformName) {
  18445. return this._uniformsNames.indexOf(uniformName);
  18446. };
  18447. Effect.prototype.getUniform = function (uniformName) {
  18448. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18449. };
  18450. Effect.prototype.getSamplers = function () {
  18451. return this._samplers;
  18452. };
  18453. Effect.prototype.getCompilationError = function () {
  18454. return this._compilationError;
  18455. };
  18456. // Methods
  18457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18458. // DOM element ?
  18459. if (vertex instanceof HTMLElement) {
  18460. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18461. callback(vertexCode);
  18462. return;
  18463. }
  18464. // Is in local store ?
  18465. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18466. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18467. return;
  18468. }
  18469. var vertexShaderUrl;
  18470. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18471. vertexShaderUrl = vertex;
  18472. }
  18473. else {
  18474. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18475. }
  18476. // Vertex shader
  18477. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18478. };
  18479. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18480. // DOM element ?
  18481. if (fragment instanceof HTMLElement) {
  18482. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18483. callback(fragmentCode);
  18484. return;
  18485. }
  18486. // Is in local store ?
  18487. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18488. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18489. return;
  18490. }
  18491. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18492. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18493. return;
  18494. }
  18495. var fragmentShaderUrl;
  18496. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18497. fragmentShaderUrl = fragment;
  18498. }
  18499. else {
  18500. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18501. }
  18502. // Fragment shader
  18503. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18504. };
  18505. Effect.prototype._dumpShadersName = function () {
  18506. if (this.name.vertexElement) {
  18507. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18508. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18509. }
  18510. else if (this.name.vertex) {
  18511. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18512. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18513. }
  18514. else {
  18515. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18516. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18517. }
  18518. };
  18519. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18520. try {
  18521. var engine = this._engine;
  18522. if (!engine.getCaps().highPrecisionShaderSupported) {
  18523. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18524. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18525. }
  18526. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18527. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18528. this._attributes = engine.getAttributes(this._program, attributesNames);
  18529. for (var index = 0; index < this._samplers.length; index++) {
  18530. var sampler = this.getUniform(this._samplers[index]);
  18531. if (sampler == null) {
  18532. this._samplers.splice(index, 1);
  18533. index--;
  18534. }
  18535. }
  18536. engine.bindSamplers(this);
  18537. this._isReady = true;
  18538. if (this.onCompiled) {
  18539. this.onCompiled(this);
  18540. }
  18541. }
  18542. catch (e) {
  18543. // Is it a problem with precision?
  18544. if (e.message.indexOf("highp") !== -1) {
  18545. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18546. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18547. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18548. return;
  18549. }
  18550. // Let's go through fallbacks then
  18551. if (fallbacks && fallbacks.isMoreFallbacks) {
  18552. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18553. this._dumpShadersName();
  18554. defines = fallbacks.reduce(defines);
  18555. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18556. }
  18557. else {
  18558. BABYLON.Tools.Error("Unable to compile effect: ");
  18559. this._dumpShadersName();
  18560. BABYLON.Tools.Error("Defines: " + defines);
  18561. BABYLON.Tools.Error("Error: " + e.message);
  18562. this._compilationError = e.message;
  18563. if (this.onError) {
  18564. this.onError(this, this._compilationError);
  18565. }
  18566. }
  18567. }
  18568. };
  18569. Object.defineProperty(Effect.prototype, "isSupported", {
  18570. get: function () {
  18571. return this._compilationError === "";
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Effect.prototype._bindTexture = function (channel, texture) {
  18577. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18578. };
  18579. Effect.prototype.setTexture = function (channel, texture) {
  18580. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18581. };
  18582. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18583. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18584. };
  18585. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18586. if (!this._valueCache[uniformName]) {
  18587. this._valueCache[uniformName] = new BABYLON.Matrix();
  18588. }
  18589. for (var index = 0; index < 16; index++) {
  18590. this._valueCache[uniformName].m[index] = matrix.m[index];
  18591. }
  18592. };
  18593. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18594. if (!this._valueCache[uniformName]) {
  18595. this._valueCache[uniformName] = [x, y];
  18596. return;
  18597. }
  18598. this._valueCache[uniformName][0] = x;
  18599. this._valueCache[uniformName][1] = y;
  18600. };
  18601. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18602. if (!this._valueCache[uniformName]) {
  18603. this._valueCache[uniformName] = [x, y, z];
  18604. return;
  18605. }
  18606. this._valueCache[uniformName][0] = x;
  18607. this._valueCache[uniformName][1] = y;
  18608. this._valueCache[uniformName][2] = z;
  18609. };
  18610. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18611. if (!this._valueCache[uniformName]) {
  18612. this._valueCache[uniformName] = [x, y, z, w];
  18613. return;
  18614. }
  18615. this._valueCache[uniformName][0] = x;
  18616. this._valueCache[uniformName][1] = y;
  18617. this._valueCache[uniformName][2] = z;
  18618. this._valueCache[uniformName][3] = w;
  18619. };
  18620. Effect.prototype.setArray = function (uniformName, array) {
  18621. this._engine.setArray(this.getUniform(uniformName), array);
  18622. return this;
  18623. };
  18624. Effect.prototype.setArray2 = function (uniformName, array) {
  18625. this._engine.setArray2(this.getUniform(uniformName), array);
  18626. return this;
  18627. };
  18628. Effect.prototype.setArray3 = function (uniformName, array) {
  18629. this._engine.setArray3(this.getUniform(uniformName), array);
  18630. return this;
  18631. };
  18632. Effect.prototype.setArray4 = function (uniformName, array) {
  18633. this._engine.setArray4(this.getUniform(uniformName), array);
  18634. return this;
  18635. };
  18636. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18637. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18638. return this;
  18639. };
  18640. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18641. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18642. // return this;
  18643. // this._cacheMatrix(uniformName, matrix);
  18644. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18645. return this;
  18646. };
  18647. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18648. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18649. return this;
  18650. };
  18651. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18652. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18653. return this;
  18654. };
  18655. Effect.prototype.setFloat = function (uniformName, value) {
  18656. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18657. return this;
  18658. this._valueCache[uniformName] = value;
  18659. this._engine.setFloat(this.getUniform(uniformName), value);
  18660. return this;
  18661. };
  18662. Effect.prototype.setBool = function (uniformName, bool) {
  18663. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18664. return this;
  18665. this._valueCache[uniformName] = bool;
  18666. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18667. return this;
  18668. };
  18669. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18670. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18671. return this;
  18672. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18673. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18674. return this;
  18675. };
  18676. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18677. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18678. return this;
  18679. this._cacheFloat2(uniformName, x, y);
  18680. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18681. return this;
  18682. };
  18683. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18684. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18685. return this;
  18686. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18687. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18688. return this;
  18689. };
  18690. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18691. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18692. return this;
  18693. this._cacheFloat3(uniformName, x, y, z);
  18694. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18695. return this;
  18696. };
  18697. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18698. 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)
  18699. return this;
  18700. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18701. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18702. return this;
  18703. };
  18704. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18705. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18706. return this;
  18707. this._cacheFloat4(uniformName, x, y, z, w);
  18708. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18709. return this;
  18710. };
  18711. Effect.prototype.setColor3 = function (uniformName, color3) {
  18712. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18713. return this;
  18714. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18715. this._engine.setColor3(this.getUniform(uniformName), color3);
  18716. return this;
  18717. };
  18718. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18719. 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)
  18720. return this;
  18721. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18722. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18723. return this;
  18724. };
  18725. // Statics
  18726. Effect.ShadersStore = {};
  18727. return Effect;
  18728. })();
  18729. BABYLON.Effect = Effect;
  18730. })(BABYLON || (BABYLON = {}));
  18731. var BABYLON;
  18732. (function (BABYLON) {
  18733. var MaterialDefines = (function () {
  18734. function MaterialDefines() {
  18735. }
  18736. MaterialDefines.prototype.isEqual = function (other) {
  18737. for (var index = 0; index < this._keys.length; index++) {
  18738. var prop = this._keys[index];
  18739. if (this[prop] !== other[prop]) {
  18740. return false;
  18741. }
  18742. }
  18743. return true;
  18744. };
  18745. MaterialDefines.prototype.cloneTo = function (other) {
  18746. for (var index = 0; index < this._keys.length; index++) {
  18747. var prop = this._keys[index];
  18748. other[prop] = this[prop];
  18749. }
  18750. };
  18751. MaterialDefines.prototype.reset = function () {
  18752. for (var index = 0; index < this._keys.length; index++) {
  18753. var prop = this._keys[index];
  18754. if (typeof (this[prop]) === "number") {
  18755. this[prop] = 0;
  18756. }
  18757. else {
  18758. this[prop] = false;
  18759. }
  18760. }
  18761. };
  18762. MaterialDefines.prototype.toString = function () {
  18763. var result = "";
  18764. for (var index = 0; index < this._keys.length; index++) {
  18765. var prop = this._keys[index];
  18766. if (typeof (this[prop]) === "number") {
  18767. result += "#define " + prop + " " + this[prop] + "\n";
  18768. }
  18769. else if (this[prop]) {
  18770. result += "#define " + prop + "\n";
  18771. }
  18772. }
  18773. return result;
  18774. };
  18775. return MaterialDefines;
  18776. })();
  18777. BABYLON.MaterialDefines = MaterialDefines;
  18778. var Material = (function () {
  18779. function Material(name, scene, doNotAdd) {
  18780. this.name = name;
  18781. this.checkReadyOnEveryCall = false;
  18782. this.checkReadyOnlyOnce = false;
  18783. this.state = "";
  18784. this.alpha = 1.0;
  18785. this.backFaceCulling = true;
  18786. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18787. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18788. this.disableDepthWrite = false;
  18789. this.fogEnabled = true;
  18790. this._wasPreviouslyReady = false;
  18791. this._fillMode = Material.TriangleFillMode;
  18792. this.pointSize = 1.0;
  18793. this.zOffset = 0;
  18794. this.id = name;
  18795. this._scene = scene;
  18796. if (!doNotAdd) {
  18797. scene.materials.push(this);
  18798. }
  18799. }
  18800. Object.defineProperty(Material, "TriangleFillMode", {
  18801. get: function () {
  18802. return Material._TriangleFillMode;
  18803. },
  18804. enumerable: true,
  18805. configurable: true
  18806. });
  18807. Object.defineProperty(Material, "WireFrameFillMode", {
  18808. get: function () {
  18809. return Material._WireFrameFillMode;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. Object.defineProperty(Material, "PointFillMode", {
  18815. get: function () {
  18816. return Material._PointFillMode;
  18817. },
  18818. enumerable: true,
  18819. configurable: true
  18820. });
  18821. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18822. get: function () {
  18823. return Material._ClockWiseSideOrientation;
  18824. },
  18825. enumerable: true,
  18826. configurable: true
  18827. });
  18828. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18829. get: function () {
  18830. return Material._CounterClockWiseSideOrientation;
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Object.defineProperty(Material.prototype, "wireframe", {
  18836. get: function () {
  18837. return this._fillMode === Material.WireFrameFillMode;
  18838. },
  18839. set: function (value) {
  18840. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18841. },
  18842. enumerable: true,
  18843. configurable: true
  18844. });
  18845. Object.defineProperty(Material.prototype, "pointsCloud", {
  18846. get: function () {
  18847. return this._fillMode === Material.PointFillMode;
  18848. },
  18849. set: function (value) {
  18850. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18851. },
  18852. enumerable: true,
  18853. configurable: true
  18854. });
  18855. Object.defineProperty(Material.prototype, "fillMode", {
  18856. get: function () {
  18857. return this._fillMode;
  18858. },
  18859. set: function (value) {
  18860. this._fillMode = value;
  18861. },
  18862. enumerable: true,
  18863. configurable: true
  18864. });
  18865. Object.defineProperty(Material.prototype, "isFrozen", {
  18866. get: function () {
  18867. return this.checkReadyOnlyOnce;
  18868. },
  18869. enumerable: true,
  18870. configurable: true
  18871. });
  18872. Material.prototype.freeze = function () {
  18873. this.checkReadyOnlyOnce = true;
  18874. };
  18875. Material.prototype.unfreeze = function () {
  18876. this.checkReadyOnlyOnce = false;
  18877. };
  18878. Material.prototype.isReady = function (mesh, useInstances) {
  18879. return true;
  18880. };
  18881. Material.prototype.getEffect = function () {
  18882. return this._effect;
  18883. };
  18884. Material.prototype.getScene = function () {
  18885. return this._scene;
  18886. };
  18887. Material.prototype.needAlphaBlending = function () {
  18888. return (this.alpha < 1.0);
  18889. };
  18890. Material.prototype.needAlphaTesting = function () {
  18891. return false;
  18892. };
  18893. Material.prototype.getAlphaTestTexture = function () {
  18894. return null;
  18895. };
  18896. Material.prototype.trackCreation = function (onCompiled, onError) {
  18897. };
  18898. Material.prototype.markDirty = function () {
  18899. this._wasPreviouslyReady = false;
  18900. };
  18901. Material.prototype._preBind = function () {
  18902. var engine = this._scene.getEngine();
  18903. engine.enableEffect(this._effect);
  18904. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18905. };
  18906. Material.prototype.bind = function (world, mesh) {
  18907. this._scene._cachedMaterial = this;
  18908. if (this.onBind) {
  18909. this.onBind(this, mesh);
  18910. }
  18911. if (this.disableDepthWrite) {
  18912. var engine = this._scene.getEngine();
  18913. this._cachedDepthWriteState = engine.getDepthWrite();
  18914. engine.setDepthWrite(false);
  18915. }
  18916. };
  18917. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18918. };
  18919. Material.prototype.unbind = function () {
  18920. if (this.disableDepthWrite) {
  18921. var engine = this._scene.getEngine();
  18922. engine.setDepthWrite(this._cachedDepthWriteState);
  18923. }
  18924. };
  18925. Material.prototype.clone = function (name) {
  18926. return null;
  18927. };
  18928. Material.prototype.getBindedMeshes = function () {
  18929. var result = new Array();
  18930. for (var index = 0; index < this._scene.meshes.length; index++) {
  18931. var mesh = this._scene.meshes[index];
  18932. if (mesh.material === this) {
  18933. result.push(mesh);
  18934. }
  18935. }
  18936. return result;
  18937. };
  18938. Material.prototype.dispose = function (forceDisposeEffect) {
  18939. // Animations
  18940. this.getScene().stopAnimation(this);
  18941. // Remove from scene
  18942. var index = this._scene.materials.indexOf(this);
  18943. if (index >= 0) {
  18944. this._scene.materials.splice(index, 1);
  18945. }
  18946. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18947. if (forceDisposeEffect && this._effect) {
  18948. this._scene.getEngine()._releaseEffect(this._effect);
  18949. this._effect = null;
  18950. }
  18951. // Remove from meshes
  18952. for (index = 0; index < this._scene.meshes.length; index++) {
  18953. var mesh = this._scene.meshes[index];
  18954. if (mesh.material === this) {
  18955. mesh.material = null;
  18956. }
  18957. }
  18958. // Callback
  18959. if (this.onDispose) {
  18960. this.onDispose();
  18961. }
  18962. };
  18963. Material.prototype.copyTo = function (other) {
  18964. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18965. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18966. other.alpha = this.alpha;
  18967. other.fillMode = this.fillMode;
  18968. other.backFaceCulling = this.backFaceCulling;
  18969. other.fogEnabled = this.fogEnabled;
  18970. other.wireframe = this.wireframe;
  18971. other.zOffset = this.zOffset;
  18972. other.alphaMode = this.alphaMode;
  18973. other.sideOrientation = this.sideOrientation;
  18974. other.disableDepthWrite = this.disableDepthWrite;
  18975. other.pointSize = this.pointSize;
  18976. other.pointsCloud = this.pointsCloud;
  18977. };
  18978. Material.prototype.serialize = function () {
  18979. var serializationObject = {};
  18980. serializationObject.name = this.name;
  18981. serializationObject.alpha = this.alpha;
  18982. serializationObject.id = this.id;
  18983. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18984. serializationObject.backFaceCulling = this.backFaceCulling;
  18985. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18986. serializationObject.disableDepthWrite = this.disableDepthWrite;
  18987. return serializationObject;
  18988. };
  18989. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  18990. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18991. multiMaterial.id = parsedMultiMaterial.id;
  18992. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18993. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18994. var subMatId = parsedMultiMaterial.materials[matIndex];
  18995. if (subMatId) {
  18996. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18997. }
  18998. else {
  18999. multiMaterial.subMaterials.push(null);
  19000. }
  19001. }
  19002. return multiMaterial;
  19003. };
  19004. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19005. if (!parsedMaterial.customType) {
  19006. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19007. }
  19008. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19009. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19010. ;
  19011. };
  19012. Material._TriangleFillMode = 0;
  19013. Material._WireFrameFillMode = 1;
  19014. Material._PointFillMode = 2;
  19015. Material._ClockWiseSideOrientation = 0;
  19016. Material._CounterClockWiseSideOrientation = 1;
  19017. return Material;
  19018. })();
  19019. BABYLON.Material = Material;
  19020. })(BABYLON || (BABYLON = {}));
  19021. var BABYLON;
  19022. (function (BABYLON) {
  19023. var maxSimultaneousLights = 4;
  19024. var FresnelParameters = (function () {
  19025. function FresnelParameters() {
  19026. this.isEnabled = true;
  19027. this.leftColor = BABYLON.Color3.White();
  19028. this.rightColor = BABYLON.Color3.Black();
  19029. this.bias = 0;
  19030. this.power = 1;
  19031. }
  19032. FresnelParameters.prototype.clone = function () {
  19033. var newFresnelParameters = new FresnelParameters();
  19034. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19035. return new FresnelParameters;
  19036. };
  19037. FresnelParameters.prototype.serialize = function () {
  19038. var serializationObject = {};
  19039. serializationObject.isEnabled = this.isEnabled;
  19040. serializationObject.leftColor = this.leftColor;
  19041. serializationObject.rightColor = this.rightColor;
  19042. serializationObject.bias = this.bias;
  19043. serializationObject.power = this.power;
  19044. return serializationObject;
  19045. };
  19046. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19047. var fresnelParameters = new FresnelParameters();
  19048. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19049. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19050. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19051. fresnelParameters.bias = parsedFresnelParameters.bias;
  19052. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19053. return fresnelParameters;
  19054. };
  19055. return FresnelParameters;
  19056. })();
  19057. BABYLON.FresnelParameters = FresnelParameters;
  19058. var StandardMaterialDefines = (function (_super) {
  19059. __extends(StandardMaterialDefines, _super);
  19060. function StandardMaterialDefines() {
  19061. _super.call(this);
  19062. this.DIFFUSE = false;
  19063. this.AMBIENT = false;
  19064. this.OPACITY = false;
  19065. this.OPACITYRGB = false;
  19066. this.REFLECTION = false;
  19067. this.EMISSIVE = false;
  19068. this.SPECULAR = false;
  19069. this.BUMP = false;
  19070. this.SPECULAROVERALPHA = false;
  19071. this.CLIPPLANE = false;
  19072. this.ALPHATEST = false;
  19073. this.ALPHAFROMDIFFUSE = false;
  19074. this.POINTSIZE = false;
  19075. this.FOG = false;
  19076. this.LIGHT0 = false;
  19077. this.LIGHT1 = false;
  19078. this.LIGHT2 = false;
  19079. this.LIGHT3 = false;
  19080. this.SPOTLIGHT0 = false;
  19081. this.SPOTLIGHT1 = false;
  19082. this.SPOTLIGHT2 = false;
  19083. this.SPOTLIGHT3 = false;
  19084. this.HEMILIGHT0 = false;
  19085. this.HEMILIGHT1 = false;
  19086. this.HEMILIGHT2 = false;
  19087. this.HEMILIGHT3 = false;
  19088. this.POINTLIGHT0 = false;
  19089. this.POINTLIGHT1 = false;
  19090. this.POINTLIGHT2 = false;
  19091. this.POINTLIGHT3 = false;
  19092. this.DIRLIGHT0 = false;
  19093. this.DIRLIGHT1 = false;
  19094. this.DIRLIGHT2 = false;
  19095. this.DIRLIGHT3 = false;
  19096. this.SPECULARTERM = false;
  19097. this.SHADOW0 = false;
  19098. this.SHADOW1 = false;
  19099. this.SHADOW2 = false;
  19100. this.SHADOW3 = false;
  19101. this.SHADOWS = false;
  19102. this.SHADOWVSM0 = false;
  19103. this.SHADOWVSM1 = false;
  19104. this.SHADOWVSM2 = false;
  19105. this.SHADOWVSM3 = false;
  19106. this.SHADOWPCF0 = false;
  19107. this.SHADOWPCF1 = false;
  19108. this.SHADOWPCF2 = false;
  19109. this.SHADOWPCF3 = false;
  19110. this.DIFFUSEFRESNEL = false;
  19111. this.OPACITYFRESNEL = false;
  19112. this.REFLECTIONFRESNEL = false;
  19113. this.EMISSIVEFRESNEL = false;
  19114. this.FRESNEL = false;
  19115. this.NORMAL = false;
  19116. this.UV1 = false;
  19117. this.UV2 = false;
  19118. this.VERTEXCOLOR = false;
  19119. this.VERTEXALPHA = false;
  19120. this.NUM_BONE_INFLUENCERS = 0;
  19121. this.BonesPerMesh = 0;
  19122. this.INSTANCES = false;
  19123. this.GLOSSINESS = false;
  19124. this.ROUGHNESS = false;
  19125. this.EMISSIVEASILLUMINATION = false;
  19126. this.LINKEMISSIVEWITHDIFFUSE = false;
  19127. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19128. this.LIGHTMAP = false;
  19129. this.USELIGHTMAPASSHADOWMAP = false;
  19130. this.REFLECTIONMAP_3D = false;
  19131. this.REFLECTIONMAP_SPHERICAL = false;
  19132. this.REFLECTIONMAP_PLANAR = false;
  19133. this.REFLECTIONMAP_CUBIC = false;
  19134. this.REFLECTIONMAP_PROJECTION = false;
  19135. this.REFLECTIONMAP_SKYBOX = false;
  19136. this.REFLECTIONMAP_EXPLICIT = false;
  19137. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19138. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19139. this.INVERTCUBICMAP = false;
  19140. this.LOGARITHMICDEPTH = false;
  19141. this._keys = Object.keys(this);
  19142. }
  19143. return StandardMaterialDefines;
  19144. })(BABYLON.MaterialDefines);
  19145. var StandardMaterial = (function (_super) {
  19146. __extends(StandardMaterial, _super);
  19147. function StandardMaterial(name, scene) {
  19148. var _this = this;
  19149. _super.call(this, name, scene);
  19150. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19151. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19152. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19153. this.specularPower = 64;
  19154. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19155. this.useAlphaFromDiffuseTexture = false;
  19156. this.useEmissiveAsIllumination = false;
  19157. this.linkEmissiveWithDiffuse = false;
  19158. this.useReflectionFresnelFromSpecular = false;
  19159. this.useSpecularOverAlpha = false;
  19160. this.disableLighting = false;
  19161. this.roughness = 0;
  19162. this.useLightmapAsShadowmap = false;
  19163. this.useGlossinessFromSpecularMapAlpha = false;
  19164. this._renderTargets = new BABYLON.SmartArray(16);
  19165. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19166. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19167. this._defines = new StandardMaterialDefines();
  19168. this._cachedDefines = new StandardMaterialDefines();
  19169. this._cachedDefines.BonesPerMesh = -1;
  19170. this.getRenderTargetTextures = function () {
  19171. _this._renderTargets.reset();
  19172. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19173. _this._renderTargets.push(_this.reflectionTexture);
  19174. }
  19175. return _this._renderTargets;
  19176. };
  19177. }
  19178. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19179. get: function () {
  19180. return this._useLogarithmicDepth;
  19181. },
  19182. set: function (value) {
  19183. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19184. },
  19185. enumerable: true,
  19186. configurable: true
  19187. });
  19188. StandardMaterial.prototype.needAlphaBlending = function () {
  19189. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19190. };
  19191. StandardMaterial.prototype.needAlphaTesting = function () {
  19192. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19193. };
  19194. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19195. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19196. };
  19197. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19198. return this.diffuseTexture;
  19199. };
  19200. // Methods
  19201. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19202. if (!mesh) {
  19203. return true;
  19204. }
  19205. if (this._defines.INSTANCES !== useInstances) {
  19206. return false;
  19207. }
  19208. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19209. return true;
  19210. }
  19211. return false;
  19212. };
  19213. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19214. var lightIndex = 0;
  19215. var needNormals = false;
  19216. for (var index = 0; index < scene.lights.length; index++) {
  19217. var light = scene.lights[index];
  19218. if (!light.isEnabled()) {
  19219. continue;
  19220. }
  19221. // Excluded check
  19222. if (light._excludedMeshesIds.length > 0) {
  19223. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19224. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19225. if (excludedMesh) {
  19226. light.excludedMeshes.push(excludedMesh);
  19227. }
  19228. }
  19229. light._excludedMeshesIds = [];
  19230. }
  19231. // Included check
  19232. if (light._includedOnlyMeshesIds.length > 0) {
  19233. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19234. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19235. if (includedOnlyMesh) {
  19236. light.includedOnlyMeshes.push(includedOnlyMesh);
  19237. }
  19238. }
  19239. light._includedOnlyMeshesIds = [];
  19240. }
  19241. if (!light.canAffectMesh(mesh)) {
  19242. continue;
  19243. }
  19244. needNormals = true;
  19245. defines["LIGHT" + lightIndex] = true;
  19246. var type;
  19247. if (light instanceof BABYLON.SpotLight) {
  19248. type = "SPOTLIGHT" + lightIndex;
  19249. }
  19250. else if (light instanceof BABYLON.HemisphericLight) {
  19251. type = "HEMILIGHT" + lightIndex;
  19252. }
  19253. else if (light instanceof BABYLON.PointLight) {
  19254. type = "POINTLIGHT" + lightIndex;
  19255. }
  19256. else {
  19257. type = "DIRLIGHT" + lightIndex;
  19258. }
  19259. defines[type] = true;
  19260. // Specular
  19261. if (!light.specular.equalsFloats(0, 0, 0)) {
  19262. defines["SPECULARTERM"] = true;
  19263. }
  19264. // Shadows
  19265. if (scene.shadowsEnabled) {
  19266. var shadowGenerator = light.getShadowGenerator();
  19267. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19268. defines["SHADOW" + lightIndex] = true;
  19269. defines["SHADOWS"] = true;
  19270. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19271. defines["SHADOWVSM" + lightIndex] = true;
  19272. }
  19273. if (shadowGenerator.usePoissonSampling) {
  19274. defines["SHADOWPCF" + lightIndex] = true;
  19275. }
  19276. }
  19277. }
  19278. lightIndex++;
  19279. if (lightIndex === maxSimultaneousLights)
  19280. break;
  19281. }
  19282. return needNormals;
  19283. };
  19284. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19285. var lightIndex = 0;
  19286. var depthValuesAlreadySet = false;
  19287. for (var index = 0; index < scene.lights.length; index++) {
  19288. var light = scene.lights[index];
  19289. if (!light.isEnabled()) {
  19290. continue;
  19291. }
  19292. if (!light.canAffectMesh(mesh)) {
  19293. continue;
  19294. }
  19295. if (light instanceof BABYLON.PointLight) {
  19296. // Point Light
  19297. light.transferToEffect(effect, "vLightData" + lightIndex);
  19298. }
  19299. else if (light instanceof BABYLON.DirectionalLight) {
  19300. // Directional Light
  19301. light.transferToEffect(effect, "vLightData" + lightIndex);
  19302. }
  19303. else if (light instanceof BABYLON.SpotLight) {
  19304. // Spot Light
  19305. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19306. }
  19307. else if (light instanceof BABYLON.HemisphericLight) {
  19308. // Hemispheric Light
  19309. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19310. }
  19311. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19312. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19313. if (defines["SPECULARTERM"]) {
  19314. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19315. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19316. }
  19317. // Shadows
  19318. if (scene.shadowsEnabled) {
  19319. var shadowGenerator = light.getShadowGenerator();
  19320. if (mesh.receiveShadows && shadowGenerator) {
  19321. if (!light.needCube()) {
  19322. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19323. }
  19324. else {
  19325. if (!depthValuesAlreadySet) {
  19326. depthValuesAlreadySet = true;
  19327. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19328. }
  19329. }
  19330. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19331. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19332. }
  19333. }
  19334. lightIndex++;
  19335. if (lightIndex === maxSimultaneousLights)
  19336. break;
  19337. }
  19338. };
  19339. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19340. if (this.isFrozen) {
  19341. if (this._wasPreviouslyReady) {
  19342. return true;
  19343. }
  19344. }
  19345. var scene = this.getScene();
  19346. if (!this.checkReadyOnEveryCall) {
  19347. if (this._renderId === scene.getRenderId()) {
  19348. if (this._checkCache(scene, mesh, useInstances)) {
  19349. return true;
  19350. }
  19351. }
  19352. }
  19353. var engine = scene.getEngine();
  19354. var needNormals = false;
  19355. var needUVs = false;
  19356. this._defines.reset();
  19357. // Textures
  19358. if (scene.texturesEnabled) {
  19359. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19360. if (!this.diffuseTexture.isReady()) {
  19361. return false;
  19362. }
  19363. else {
  19364. needUVs = true;
  19365. this._defines.DIFFUSE = true;
  19366. }
  19367. }
  19368. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19369. if (!this.ambientTexture.isReady()) {
  19370. return false;
  19371. }
  19372. else {
  19373. needUVs = true;
  19374. this._defines.AMBIENT = true;
  19375. }
  19376. }
  19377. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19378. if (!this.opacityTexture.isReady()) {
  19379. return false;
  19380. }
  19381. else {
  19382. needUVs = true;
  19383. this._defines.OPACITY = true;
  19384. if (this.opacityTexture.getAlphaFromRGB) {
  19385. this._defines.OPACITYRGB = true;
  19386. }
  19387. }
  19388. }
  19389. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19390. if (!this.reflectionTexture.isReady()) {
  19391. return false;
  19392. }
  19393. else {
  19394. needNormals = true;
  19395. this._defines.REFLECTION = true;
  19396. if (this.roughness > 0) {
  19397. this._defines.ROUGHNESS = true;
  19398. }
  19399. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19400. this._defines.INVERTCUBICMAP = true;
  19401. }
  19402. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19403. switch (this.reflectionTexture.coordinatesMode) {
  19404. case BABYLON.Texture.CUBIC_MODE:
  19405. case BABYLON.Texture.INVCUBIC_MODE:
  19406. this._defines.REFLECTIONMAP_CUBIC = true;
  19407. break;
  19408. case BABYLON.Texture.EXPLICIT_MODE:
  19409. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19410. break;
  19411. case BABYLON.Texture.PLANAR_MODE:
  19412. this._defines.REFLECTIONMAP_PLANAR = true;
  19413. break;
  19414. case BABYLON.Texture.PROJECTION_MODE:
  19415. this._defines.REFLECTIONMAP_PROJECTION = true;
  19416. break;
  19417. case BABYLON.Texture.SKYBOX_MODE:
  19418. this._defines.REFLECTIONMAP_SKYBOX = true;
  19419. break;
  19420. case BABYLON.Texture.SPHERICAL_MODE:
  19421. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19422. break;
  19423. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19424. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19425. break;
  19426. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19427. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19428. break;
  19429. }
  19430. }
  19431. }
  19432. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19433. if (!this.emissiveTexture.isReady()) {
  19434. return false;
  19435. }
  19436. else {
  19437. needUVs = true;
  19438. this._defines.EMISSIVE = true;
  19439. }
  19440. }
  19441. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19442. if (!this.lightmapTexture.isReady()) {
  19443. return false;
  19444. }
  19445. else {
  19446. needUVs = true;
  19447. this._defines.LIGHTMAP = true;
  19448. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19449. }
  19450. }
  19451. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19452. if (!this.specularTexture.isReady()) {
  19453. return false;
  19454. }
  19455. else {
  19456. needUVs = true;
  19457. this._defines.SPECULAR = true;
  19458. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19459. }
  19460. }
  19461. }
  19462. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19463. if (!this.bumpTexture.isReady()) {
  19464. return false;
  19465. }
  19466. else {
  19467. needUVs = true;
  19468. this._defines.BUMP = true;
  19469. }
  19470. }
  19471. // Effect
  19472. if (scene.clipPlane) {
  19473. this._defines.CLIPPLANE = true;
  19474. }
  19475. if (engine.getAlphaTesting()) {
  19476. this._defines.ALPHATEST = true;
  19477. }
  19478. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19479. this._defines.ALPHAFROMDIFFUSE = true;
  19480. }
  19481. if (this.useEmissiveAsIllumination) {
  19482. this._defines.EMISSIVEASILLUMINATION = true;
  19483. }
  19484. if (this.linkEmissiveWithDiffuse) {
  19485. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19486. }
  19487. if (this.useReflectionFresnelFromSpecular) {
  19488. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19489. }
  19490. if (this.useLogarithmicDepth) {
  19491. this._defines.LOGARITHMICDEPTH = true;
  19492. }
  19493. // Point size
  19494. if (this.pointsCloud || scene.forcePointsCloud) {
  19495. this._defines.POINTSIZE = true;
  19496. }
  19497. // Fog
  19498. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19499. this._defines.FOG = true;
  19500. }
  19501. if (scene.lightsEnabled && !this.disableLighting) {
  19502. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19503. }
  19504. if (StandardMaterial.FresnelEnabled) {
  19505. // Fresnel
  19506. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19507. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19508. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19509. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19510. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19511. this._defines.DIFFUSEFRESNEL = true;
  19512. }
  19513. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19514. this._defines.OPACITYFRESNEL = true;
  19515. }
  19516. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19517. this._defines.REFLECTIONFRESNEL = true;
  19518. }
  19519. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19520. this._defines.EMISSIVEFRESNEL = true;
  19521. }
  19522. needNormals = true;
  19523. this._defines.FRESNEL = true;
  19524. }
  19525. }
  19526. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19527. this._defines.SPECULAROVERALPHA = true;
  19528. }
  19529. // Attribs
  19530. if (mesh) {
  19531. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19532. this._defines.NORMAL = true;
  19533. }
  19534. if (needUVs) {
  19535. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19536. this._defines.UV1 = true;
  19537. }
  19538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19539. this._defines.UV2 = true;
  19540. }
  19541. }
  19542. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19543. this._defines.VERTEXCOLOR = true;
  19544. if (mesh.hasVertexAlpha) {
  19545. this._defines.VERTEXALPHA = true;
  19546. }
  19547. }
  19548. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19549. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19550. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19551. }
  19552. // Instances
  19553. if (useInstances) {
  19554. this._defines.INSTANCES = true;
  19555. }
  19556. }
  19557. // Get correct effect
  19558. if (!this._defines.isEqual(this._cachedDefines)) {
  19559. this._defines.cloneTo(this._cachedDefines);
  19560. scene.resetCachedMaterial();
  19561. // Fallbacks
  19562. var fallbacks = new BABYLON.EffectFallbacks();
  19563. if (this._defines.REFLECTION) {
  19564. fallbacks.addFallback(0, "REFLECTION");
  19565. }
  19566. if (this._defines.SPECULAR) {
  19567. fallbacks.addFallback(0, "SPECULAR");
  19568. }
  19569. if (this._defines.BUMP) {
  19570. fallbacks.addFallback(0, "BUMP");
  19571. }
  19572. if (this._defines.SPECULAROVERALPHA) {
  19573. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19574. }
  19575. if (this._defines.FOG) {
  19576. fallbacks.addFallback(1, "FOG");
  19577. }
  19578. if (this._defines.POINTSIZE) {
  19579. fallbacks.addFallback(0, "POINTSIZE");
  19580. }
  19581. if (this._defines.LOGARITHMICDEPTH) {
  19582. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  19583. }
  19584. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19585. if (!this._defines["LIGHT" + lightIndex]) {
  19586. continue;
  19587. }
  19588. if (lightIndex > 0) {
  19589. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19590. }
  19591. if (this._defines["SHADOW" + lightIndex]) {
  19592. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19593. }
  19594. if (this._defines["SHADOWPCF" + lightIndex]) {
  19595. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19596. }
  19597. if (this._defines["SHADOWVSM" + lightIndex]) {
  19598. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19599. }
  19600. }
  19601. if (this._defines.SPECULARTERM) {
  19602. fallbacks.addFallback(0, "SPECULARTERM");
  19603. }
  19604. if (this._defines.DIFFUSEFRESNEL) {
  19605. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19606. }
  19607. if (this._defines.OPACITYFRESNEL) {
  19608. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19609. }
  19610. if (this._defines.REFLECTIONFRESNEL) {
  19611. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19612. }
  19613. if (this._defines.EMISSIVEFRESNEL) {
  19614. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19615. }
  19616. if (this._defines.FRESNEL) {
  19617. fallbacks.addFallback(4, "FRESNEL");
  19618. }
  19619. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19620. fallbacks.addCPUSkinningFallback(0, mesh);
  19621. }
  19622. //Attributes
  19623. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19624. if (this._defines.NORMAL) {
  19625. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19626. }
  19627. if (this._defines.UV1) {
  19628. attribs.push(BABYLON.VertexBuffer.UVKind);
  19629. }
  19630. if (this._defines.UV2) {
  19631. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19632. }
  19633. if (this._defines.VERTEXCOLOR) {
  19634. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19635. }
  19636. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  19637. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19638. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19639. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  19640. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19641. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19642. }
  19643. }
  19644. if (this._defines.INSTANCES) {
  19645. attribs.push("world0");
  19646. attribs.push("world1");
  19647. attribs.push("world2");
  19648. attribs.push("world3");
  19649. }
  19650. // Legacy browser patch
  19651. var shaderName = "default";
  19652. if (!scene.getEngine().getCaps().standardDerivatives) {
  19653. shaderName = "legacydefault";
  19654. }
  19655. var join = this._defines.toString();
  19656. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19657. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19658. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19659. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19660. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19661. "vFogInfos", "vFogColor", "pointSize",
  19662. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19663. "mBones",
  19664. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19665. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  19666. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19667. "logarithmicDepthConstant"
  19668. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19669. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19670. ], join, fallbacks, this.onCompiled, this.onError);
  19671. }
  19672. if (!this._effect.isReady()) {
  19673. return false;
  19674. }
  19675. this._renderId = scene.getRenderId();
  19676. this._wasPreviouslyReady = true;
  19677. if (mesh) {
  19678. if (!mesh._materialDefines) {
  19679. mesh._materialDefines = new StandardMaterialDefines();
  19680. }
  19681. this._defines.cloneTo(mesh._materialDefines);
  19682. }
  19683. return true;
  19684. };
  19685. StandardMaterial.prototype.unbind = function () {
  19686. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19687. this._effect.setTexture("reflection2DSampler", null);
  19688. }
  19689. _super.prototype.unbind.call(this);
  19690. };
  19691. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19692. this._effect.setMatrix("world", world);
  19693. };
  19694. StandardMaterial.prototype.bind = function (world, mesh) {
  19695. var scene = this.getScene();
  19696. // Matrices
  19697. this.bindOnlyWorldMatrix(world);
  19698. // Bones
  19699. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19700. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19701. }
  19702. if (scene.getCachedMaterial() !== this) {
  19703. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19704. if (StandardMaterial.FresnelEnabled) {
  19705. // Fresnel
  19706. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19707. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19708. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19709. }
  19710. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19711. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19712. }
  19713. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19714. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19715. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19716. }
  19717. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19718. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19719. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19720. }
  19721. }
  19722. // Textures
  19723. if (scene.texturesEnabled) {
  19724. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19725. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19726. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19727. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19728. }
  19729. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19730. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19731. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19732. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19733. }
  19734. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19735. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19736. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19737. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19738. }
  19739. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19740. if (this.reflectionTexture.isCube) {
  19741. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19742. }
  19743. else {
  19744. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19745. }
  19746. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19747. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19748. }
  19749. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19750. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19751. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19752. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19753. }
  19754. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19755. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19756. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19757. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19758. }
  19759. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19760. this._effect.setTexture("specularSampler", this.specularTexture);
  19761. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19762. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19763. }
  19764. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19765. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19766. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19767. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19768. }
  19769. }
  19770. // Clip plane
  19771. if (scene.clipPlane) {
  19772. var clipPlane = scene.clipPlane;
  19773. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19774. }
  19775. // Point size
  19776. if (this.pointsCloud) {
  19777. this._effect.setFloat("pointSize", this.pointSize);
  19778. }
  19779. // Colors
  19780. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19781. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19782. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19783. if (this._defines.SPECULARTERM) {
  19784. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19785. }
  19786. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19787. }
  19788. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  19789. // Diffuse
  19790. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19791. // Lights
  19792. if (scene.lightsEnabled && !this.disableLighting) {
  19793. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19794. }
  19795. // View
  19796. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19797. this._effect.setMatrix("view", scene.getViewMatrix());
  19798. }
  19799. // Fog
  19800. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19801. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19802. this._effect.setColor3("vFogColor", scene.fogColor);
  19803. }
  19804. // Log. depth
  19805. if (this._defines.LOGARITHMICDEPTH) {
  19806. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19807. }
  19808. }
  19809. _super.prototype.bind.call(this, world, mesh);
  19810. };
  19811. StandardMaterial.prototype.getAnimatables = function () {
  19812. var results = [];
  19813. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19814. results.push(this.diffuseTexture);
  19815. }
  19816. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19817. results.push(this.ambientTexture);
  19818. }
  19819. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19820. results.push(this.opacityTexture);
  19821. }
  19822. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19823. results.push(this.reflectionTexture);
  19824. }
  19825. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19826. results.push(this.emissiveTexture);
  19827. }
  19828. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19829. results.push(this.specularTexture);
  19830. }
  19831. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19832. results.push(this.bumpTexture);
  19833. }
  19834. return results;
  19835. };
  19836. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19837. if (this.diffuseTexture) {
  19838. this.diffuseTexture.dispose();
  19839. }
  19840. if (this.ambientTexture) {
  19841. this.ambientTexture.dispose();
  19842. }
  19843. if (this.opacityTexture) {
  19844. this.opacityTexture.dispose();
  19845. }
  19846. if (this.reflectionTexture) {
  19847. this.reflectionTexture.dispose();
  19848. }
  19849. if (this.emissiveTexture) {
  19850. this.emissiveTexture.dispose();
  19851. }
  19852. if (this.specularTexture) {
  19853. this.specularTexture.dispose();
  19854. }
  19855. if (this.bumpTexture) {
  19856. this.bumpTexture.dispose();
  19857. }
  19858. _super.prototype.dispose.call(this, forceDisposeEffect);
  19859. };
  19860. StandardMaterial.prototype.clone = function (name) {
  19861. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19862. // Base material
  19863. this.copyTo(newStandardMaterial);
  19864. // Standard material
  19865. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19866. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19867. }
  19868. if (this.ambientTexture && this.ambientTexture.clone) {
  19869. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19870. }
  19871. if (this.opacityTexture && this.opacityTexture.clone) {
  19872. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19873. }
  19874. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19875. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19876. }
  19877. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19878. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19879. }
  19880. if (this.specularTexture && this.specularTexture.clone) {
  19881. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19882. }
  19883. if (this.bumpTexture && this.bumpTexture.clone) {
  19884. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19885. }
  19886. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19887. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19888. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19889. }
  19890. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19891. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19892. newStandardMaterial.specularColor = this.specularColor.clone();
  19893. newStandardMaterial.specularPower = this.specularPower;
  19894. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19895. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19896. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19897. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19898. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19899. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19900. newStandardMaterial.roughness = this.roughness;
  19901. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19902. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19903. }
  19904. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19905. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19906. }
  19907. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19908. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19909. }
  19910. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19911. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19912. }
  19913. return newStandardMaterial;
  19914. };
  19915. StandardMaterial.prototype.serialize = function () {
  19916. var serializationObject = _super.prototype.serialize.call(this);
  19917. serializationObject.ambient = this.ambientColor.asArray();
  19918. serializationObject.diffuse = this.diffuseColor.asArray();
  19919. serializationObject.specular = this.specularColor.asArray();
  19920. serializationObject.specularPower = this.specularPower;
  19921. serializationObject.emissive = this.emissiveColor.asArray();
  19922. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  19923. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  19924. if (this.diffuseTexture) {
  19925. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  19926. }
  19927. if (this.diffuseFresnelParameters) {
  19928. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  19929. }
  19930. if (this.ambientTexture) {
  19931. serializationObject.ambientTexture = this.ambientTexture.serialize();
  19932. }
  19933. if (this.opacityTexture) {
  19934. serializationObject.opacityTexture = this.opacityTexture.serialize();
  19935. }
  19936. if (this.opacityFresnelParameters) {
  19937. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  19938. }
  19939. if (this.reflectionTexture) {
  19940. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  19941. }
  19942. if (this.reflectionFresnelParameters) {
  19943. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  19944. }
  19945. if (this.emissiveTexture) {
  19946. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  19947. }
  19948. if (this.lightmapTexture) {
  19949. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  19950. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19951. }
  19952. if (this.emissiveFresnelParameters) {
  19953. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  19954. }
  19955. if (this.specularTexture) {
  19956. serializationObject.specularTexture = this.specularTexture.serialize();
  19957. }
  19958. if (this.bumpTexture) {
  19959. serializationObject.bumpTexture = this.bumpTexture.serialize();
  19960. }
  19961. return serializationObject;
  19962. };
  19963. StandardMaterial.Parse = function (source, scene, rootUrl) {
  19964. var material = new StandardMaterial(source.name, scene);
  19965. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  19966. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  19967. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  19968. material.specularPower = source.specularPower;
  19969. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  19970. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  19971. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  19972. material.alpha = source.alpha;
  19973. material.id = source.id;
  19974. if (source.disableDepthWrite) {
  19975. material.disableDepthWrite = source.disableDepthWrite;
  19976. }
  19977. BABYLON.Tags.AddTagsTo(material, source.tags);
  19978. material.backFaceCulling = source.backFaceCulling;
  19979. material.wireframe = source.wireframe;
  19980. if (source.diffuseTexture) {
  19981. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  19982. }
  19983. if (source.diffuseFresnelParameters) {
  19984. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  19985. }
  19986. if (source.ambientTexture) {
  19987. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  19988. }
  19989. if (source.opacityTexture) {
  19990. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  19991. }
  19992. if (source.opacityFresnelParameters) {
  19993. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  19994. }
  19995. if (source.reflectionTexture) {
  19996. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  19997. }
  19998. if (source.reflectionFresnelParameters) {
  19999. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  20000. }
  20001. if (source.emissiveTexture) {
  20002. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  20003. }
  20004. if (source.lightmapTexture) {
  20005. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  20006. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  20007. }
  20008. if (source.emissiveFresnelParameters) {
  20009. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  20010. }
  20011. if (source.specularTexture) {
  20012. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  20013. }
  20014. if (source.bumpTexture) {
  20015. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  20016. }
  20017. if (source.checkReadyOnlyOnce) {
  20018. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  20019. }
  20020. return material;
  20021. };
  20022. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  20023. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  20024. // Statics
  20025. // Flags used to enable or disable a type of texture for all Standard Materials
  20026. StandardMaterial.DiffuseTextureEnabled = true;
  20027. StandardMaterial.AmbientTextureEnabled = true;
  20028. StandardMaterial.OpacityTextureEnabled = true;
  20029. StandardMaterial.ReflectionTextureEnabled = true;
  20030. StandardMaterial.EmissiveTextureEnabled = true;
  20031. StandardMaterial.SpecularTextureEnabled = true;
  20032. StandardMaterial.BumpTextureEnabled = true;
  20033. StandardMaterial.FresnelEnabled = true;
  20034. StandardMaterial.LightmapEnabled = true;
  20035. return StandardMaterial;
  20036. })(BABYLON.Material);
  20037. BABYLON.StandardMaterial = StandardMaterial;
  20038. })(BABYLON || (BABYLON = {}));
  20039. var BABYLON;
  20040. (function (BABYLON) {
  20041. var MultiMaterial = (function (_super) {
  20042. __extends(MultiMaterial, _super);
  20043. function MultiMaterial(name, scene) {
  20044. _super.call(this, name, scene, true);
  20045. this.subMaterials = new Array();
  20046. scene.multiMaterials.push(this);
  20047. }
  20048. // Properties
  20049. MultiMaterial.prototype.getSubMaterial = function (index) {
  20050. if (index < 0 || index >= this.subMaterials.length) {
  20051. return this.getScene().defaultMaterial;
  20052. }
  20053. return this.subMaterials[index];
  20054. };
  20055. // Methods
  20056. MultiMaterial.prototype.isReady = function (mesh) {
  20057. for (var index = 0; index < this.subMaterials.length; index++) {
  20058. var subMaterial = this.subMaterials[index];
  20059. if (subMaterial) {
  20060. if (!this.subMaterials[index].isReady(mesh)) {
  20061. return false;
  20062. }
  20063. }
  20064. }
  20065. return true;
  20066. };
  20067. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20068. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20069. for (var index = 0; index < this.subMaterials.length; index++) {
  20070. var subMaterial = null;
  20071. if (cloneChildren) {
  20072. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20073. }
  20074. else {
  20075. subMaterial = this.subMaterials[index];
  20076. }
  20077. newMultiMaterial.subMaterials.push(subMaterial);
  20078. }
  20079. return newMultiMaterial;
  20080. };
  20081. MultiMaterial.prototype.serialize = function () {
  20082. var serializationObject = {};
  20083. serializationObject.name = this.name;
  20084. serializationObject.id = this.id;
  20085. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20086. serializationObject.materials = [];
  20087. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20088. var subMat = this.subMaterials[matIndex];
  20089. if (subMat) {
  20090. serializationObject.materials.push(subMat.id);
  20091. }
  20092. else {
  20093. serializationObject.materials.push(null);
  20094. }
  20095. }
  20096. return serializationObject;
  20097. };
  20098. return MultiMaterial;
  20099. })(BABYLON.Material);
  20100. BABYLON.MultiMaterial = MultiMaterial;
  20101. })(BABYLON || (BABYLON = {}));
  20102. var BABYLON;
  20103. (function (BABYLON) {
  20104. var SceneLoader = (function () {
  20105. function SceneLoader() {
  20106. }
  20107. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20108. get: function () {
  20109. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20110. },
  20111. set: function (value) {
  20112. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20113. },
  20114. enumerable: true,
  20115. configurable: true
  20116. });
  20117. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20118. get: function () {
  20119. return SceneLoader._ShowLoadingScreen;
  20120. },
  20121. set: function (value) {
  20122. SceneLoader._ShowLoadingScreen = value;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20128. var dotPosition = sceneFilename.lastIndexOf(".");
  20129. var queryStringPosition = sceneFilename.indexOf("?");
  20130. if (queryStringPosition === -1) {
  20131. queryStringPosition = sceneFilename.length;
  20132. }
  20133. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20134. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20135. var plugin = this._registeredPlugins[index];
  20136. if (plugin.extensions.indexOf(extension) !== -1) {
  20137. return plugin;
  20138. }
  20139. }
  20140. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20141. };
  20142. // Public functions
  20143. SceneLoader.RegisterPlugin = function (plugin) {
  20144. plugin.extensions = plugin.extensions.toLowerCase();
  20145. SceneLoader._registeredPlugins.push(plugin);
  20146. };
  20147. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20148. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20149. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20150. return;
  20151. }
  20152. var loadingToken = {};
  20153. scene._addPendingData(loadingToken);
  20154. var manifestChecked = function (success) {
  20155. scene.database = database;
  20156. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20157. var importMeshFromData = function (data) {
  20158. var meshes = [];
  20159. var particleSystems = [];
  20160. var skeletons = [];
  20161. try {
  20162. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20163. if (onerror) {
  20164. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20165. }
  20166. scene._removePendingData(loadingToken);
  20167. return;
  20168. }
  20169. }
  20170. catch (e) {
  20171. if (onerror) {
  20172. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20173. }
  20174. scene._removePendingData(loadingToken);
  20175. return;
  20176. }
  20177. if (onsuccess) {
  20178. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20179. onsuccess(meshes, particleSystems, skeletons);
  20180. scene._removePendingData(loadingToken);
  20181. }
  20182. };
  20183. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20184. // Direct load
  20185. importMeshFromData(sceneFilename.substr(5));
  20186. return;
  20187. }
  20188. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20189. importMeshFromData(data);
  20190. }, progressCallBack, database);
  20191. };
  20192. if (scene.getEngine().enableOfflineSupport) {
  20193. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20194. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20195. }
  20196. else {
  20197. manifestChecked(true);
  20198. }
  20199. };
  20200. /**
  20201. * Load a scene
  20202. * @param rootUrl a string that defines the root url for scene and resources
  20203. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20204. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20205. */
  20206. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20207. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20208. };
  20209. /**
  20210. * Append a scene
  20211. * @param rootUrl a string that defines the root url for scene and resources
  20212. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20213. * @param scene is the instance of BABYLON.Scene to append to
  20214. */
  20215. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20216. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20217. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20218. return;
  20219. }
  20220. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20221. var database;
  20222. var loadingToken = {};
  20223. scene._addPendingData(loadingToken);
  20224. if (SceneLoader.ShowLoadingScreen) {
  20225. scene.getEngine().displayLoadingUI();
  20226. }
  20227. var loadSceneFromData = function (data) {
  20228. scene.database = database;
  20229. if (!plugin.load(scene, data, rootUrl)) {
  20230. if (onerror) {
  20231. onerror(scene);
  20232. }
  20233. scene._removePendingData(loadingToken);
  20234. scene.getEngine().hideLoadingUI();
  20235. return;
  20236. }
  20237. if (onsuccess) {
  20238. onsuccess(scene);
  20239. }
  20240. scene._removePendingData(loadingToken);
  20241. if (SceneLoader.ShowLoadingScreen) {
  20242. scene.executeWhenReady(function () {
  20243. scene.getEngine().hideLoadingUI();
  20244. });
  20245. }
  20246. };
  20247. var manifestChecked = function (success) {
  20248. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20249. };
  20250. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20251. // Direct load
  20252. loadSceneFromData(sceneFilename.substr(5));
  20253. return;
  20254. }
  20255. if (rootUrl.indexOf("file:") === -1) {
  20256. if (scene.getEngine().enableOfflineSupport) {
  20257. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20258. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20259. }
  20260. else {
  20261. manifestChecked(true);
  20262. }
  20263. }
  20264. else {
  20265. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20266. }
  20267. };
  20268. // Flags
  20269. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20270. SceneLoader._ShowLoadingScreen = true;
  20271. // Members
  20272. SceneLoader._registeredPlugins = new Array();
  20273. return SceneLoader;
  20274. })();
  20275. BABYLON.SceneLoader = SceneLoader;
  20276. ;
  20277. })(BABYLON || (BABYLON = {}));
  20278. var BABYLON;
  20279. (function (BABYLON) {
  20280. var Internals;
  20281. (function (Internals) {
  20282. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20283. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20284. var parsedMaterial = parsedData.materials[index];
  20285. if (parsedMaterial.id === id) {
  20286. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20287. }
  20288. }
  20289. return null;
  20290. };
  20291. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20292. names = (names instanceof Array) ? names : [names];
  20293. for (var i in names) {
  20294. if (mesh.name === names[i]) {
  20295. hierarchyIds.push(mesh.id);
  20296. return true;
  20297. }
  20298. }
  20299. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20300. hierarchyIds.push(mesh.id);
  20301. return true;
  20302. }
  20303. return false;
  20304. };
  20305. BABYLON.SceneLoader.RegisterPlugin({
  20306. extensions: ".babylon",
  20307. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20308. var parsedData = JSON.parse(data);
  20309. var loadedSkeletonsIds = [];
  20310. var loadedMaterialsIds = [];
  20311. var hierarchyIds = [];
  20312. var index;
  20313. var cache;
  20314. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20315. var parsedMesh = parsedData.meshes[index];
  20316. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20317. if (meshesNames instanceof Array) {
  20318. // Remove found mesh name from list.
  20319. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20320. }
  20321. //Geometry?
  20322. if (parsedMesh.geometryId) {
  20323. //does the file contain geometries?
  20324. if (parsedData.geometries) {
  20325. //find the correct geometry and add it to the scene
  20326. var found = false;
  20327. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20328. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20329. return;
  20330. }
  20331. else {
  20332. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20333. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20334. switch (geometryType) {
  20335. case "boxes":
  20336. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20337. break;
  20338. case "spheres":
  20339. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20340. break;
  20341. case "cylinders":
  20342. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20343. break;
  20344. case "toruses":
  20345. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20346. break;
  20347. case "grounds":
  20348. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20349. break;
  20350. case "planes":
  20351. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20352. break;
  20353. case "torusKnots":
  20354. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20355. break;
  20356. case "vertexData":
  20357. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20358. break;
  20359. }
  20360. found = true;
  20361. }
  20362. });
  20363. }
  20364. });
  20365. if (!found) {
  20366. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20367. }
  20368. }
  20369. }
  20370. // Material ?
  20371. if (parsedMesh.materialId) {
  20372. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20373. if (!materialFound && parsedData.multiMaterials) {
  20374. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20375. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20376. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20377. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20378. var subMatId = parsedMultiMaterial.materials[matIndex];
  20379. loadedMaterialsIds.push(subMatId);
  20380. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20381. }
  20382. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20383. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20384. materialFound = true;
  20385. break;
  20386. }
  20387. }
  20388. }
  20389. if (!materialFound) {
  20390. loadedMaterialsIds.push(parsedMesh.materialId);
  20391. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20392. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20393. }
  20394. }
  20395. }
  20396. // Skeleton ?
  20397. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20398. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20399. if (!skeletonAlreadyLoaded) {
  20400. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20401. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20402. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20403. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20404. loadedSkeletonsIds.push(parsedSkeleton.id);
  20405. }
  20406. }
  20407. }
  20408. }
  20409. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20410. meshes.push(mesh);
  20411. }
  20412. }
  20413. // Connecting parents
  20414. var currentMesh;
  20415. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20416. currentMesh = scene.meshes[index];
  20417. if (currentMesh._waitingParentId) {
  20418. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20419. currentMesh._waitingParentId = undefined;
  20420. }
  20421. }
  20422. // freeze and compute world matrix application
  20423. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20424. currentMesh = scene.meshes[index];
  20425. if (currentMesh._waitingFreezeWorldMatrix) {
  20426. currentMesh.freezeWorldMatrix();
  20427. currentMesh._waitingFreezeWorldMatrix = undefined;
  20428. }
  20429. else {
  20430. currentMesh.computeWorldMatrix(true);
  20431. }
  20432. }
  20433. // Particles
  20434. if (parsedData.particleSystems) {
  20435. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20436. var parsedParticleSystem = parsedData.particleSystems[index];
  20437. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20438. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20439. }
  20440. }
  20441. }
  20442. return true;
  20443. },
  20444. load: function (scene, data, rootUrl) {
  20445. var parsedData = JSON.parse(data);
  20446. // Scene
  20447. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20448. scene.autoClear = parsedData.autoClear;
  20449. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20450. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20451. if (parsedData.gravity) {
  20452. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20453. }
  20454. // Fog
  20455. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20456. scene.fogMode = parsedData.fogMode;
  20457. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20458. scene.fogStart = parsedData.fogStart;
  20459. scene.fogEnd = parsedData.fogEnd;
  20460. scene.fogDensity = parsedData.fogDensity;
  20461. }
  20462. //Physics
  20463. if (parsedData.physicsEnabled) {
  20464. var physicsPlugin;
  20465. if (parsedData.physicsEngine === "cannon") {
  20466. physicsPlugin = new BABYLON.CannonJSPlugin();
  20467. }
  20468. else if (parsedData.physicsEngine === "oimo") {
  20469. physicsPlugin = new BABYLON.OimoJSPlugin();
  20470. }
  20471. //else - default engine, which is currently oimo
  20472. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20473. scene.enablePhysics(physicsGravity, physicsPlugin);
  20474. }
  20475. //collisions, if defined. otherwise, default is true
  20476. if (parsedData.collisionsEnabled != undefined) {
  20477. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20478. }
  20479. scene.workerCollisions = !!parsedData.workerCollisions;
  20480. var index;
  20481. var cache;
  20482. // Lights
  20483. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20484. var parsedLight = parsedData.lights[index];
  20485. BABYLON.Light.Parse(parsedLight, scene);
  20486. }
  20487. // Materials
  20488. if (parsedData.materials) {
  20489. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20490. var parsedMaterial = parsedData.materials[index];
  20491. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20492. }
  20493. }
  20494. if (parsedData.multiMaterials) {
  20495. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20496. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20497. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20498. }
  20499. }
  20500. // Skeletons
  20501. if (parsedData.skeletons) {
  20502. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  20503. var parsedSkeleton = parsedData.skeletons[index];
  20504. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  20505. }
  20506. }
  20507. // Geometries
  20508. var geometries = parsedData.geometries;
  20509. if (geometries) {
  20510. // Boxes
  20511. var boxes = geometries.boxes;
  20512. if (boxes) {
  20513. for (index = 0, cache = boxes.length; index < cache; index++) {
  20514. var parsedBox = boxes[index];
  20515. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  20516. }
  20517. }
  20518. // Spheres
  20519. var spheres = geometries.spheres;
  20520. if (spheres) {
  20521. for (index = 0, cache = spheres.length; index < cache; index++) {
  20522. var parsedSphere = spheres[index];
  20523. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  20524. }
  20525. }
  20526. // Cylinders
  20527. var cylinders = geometries.cylinders;
  20528. if (cylinders) {
  20529. for (index = 0, cache = cylinders.length; index < cache; index++) {
  20530. var parsedCylinder = cylinders[index];
  20531. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  20532. }
  20533. }
  20534. // Toruses
  20535. var toruses = geometries.toruses;
  20536. if (toruses) {
  20537. for (index = 0, cache = toruses.length; index < cache; index++) {
  20538. var parsedTorus = toruses[index];
  20539. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  20540. }
  20541. }
  20542. // Grounds
  20543. var grounds = geometries.grounds;
  20544. if (grounds) {
  20545. for (index = 0, cache = grounds.length; index < cache; index++) {
  20546. var parsedGround = grounds[index];
  20547. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  20548. }
  20549. }
  20550. // Planes
  20551. var planes = geometries.planes;
  20552. if (planes) {
  20553. for (index = 0, cache = planes.length; index < cache; index++) {
  20554. var parsedPlane = planes[index];
  20555. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  20556. }
  20557. }
  20558. // TorusKnots
  20559. var torusKnots = geometries.torusKnots;
  20560. if (torusKnots) {
  20561. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  20562. var parsedTorusKnot = torusKnots[index];
  20563. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  20564. }
  20565. }
  20566. // VertexData
  20567. var vertexData = geometries.vertexData;
  20568. if (vertexData) {
  20569. for (index = 0, cache = vertexData.length; index < cache; index++) {
  20570. var parsedVertexData = vertexData[index];
  20571. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  20572. }
  20573. }
  20574. }
  20575. // Meshes
  20576. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20577. var parsedMesh = parsedData.meshes[index];
  20578. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20579. }
  20580. // Cameras
  20581. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  20582. var parsedCamera = parsedData.cameras[index];
  20583. BABYLON.Camera.Parse(parsedCamera, scene);
  20584. }
  20585. if (parsedData.activeCameraID) {
  20586. scene.setActiveCameraByID(parsedData.activeCameraID);
  20587. }
  20588. // Browsing all the graph to connect the dots
  20589. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  20590. var camera = scene.cameras[index];
  20591. if (camera._waitingParentId) {
  20592. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20593. camera._waitingParentId = undefined;
  20594. }
  20595. }
  20596. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  20597. var light = scene.lights[index];
  20598. if (light._waitingParentId) {
  20599. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20600. light._waitingParentId = undefined;
  20601. }
  20602. }
  20603. // Sounds
  20604. var loadedSounds = [];
  20605. var loadedSound;
  20606. if (BABYLON.AudioEngine && parsedData.sounds) {
  20607. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  20608. var parsedSound = parsedData.sounds[index];
  20609. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20610. if (!parsedSound.url)
  20611. parsedSound.url = parsedSound.name;
  20612. if (!loadedSounds[parsedSound.url]) {
  20613. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  20614. loadedSounds[parsedSound.url] = loadedSound;
  20615. }
  20616. else {
  20617. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  20618. }
  20619. }
  20620. else {
  20621. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20622. }
  20623. }
  20624. }
  20625. loadedSounds = [];
  20626. // Connect parents & children and parse actions
  20627. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20628. var mesh = scene.meshes[index];
  20629. if (mesh._waitingParentId) {
  20630. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20631. mesh._waitingParentId = undefined;
  20632. }
  20633. if (mesh._waitingActions) {
  20634. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  20635. mesh._waitingActions = undefined;
  20636. }
  20637. }
  20638. // freeze world matrix application
  20639. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20640. var currentMesh = scene.meshes[index];
  20641. if (currentMesh._waitingFreezeWorldMatrix) {
  20642. currentMesh.freezeWorldMatrix();
  20643. currentMesh._waitingFreezeWorldMatrix = undefined;
  20644. }
  20645. else {
  20646. currentMesh.computeWorldMatrix(true);
  20647. }
  20648. }
  20649. // Particles Systems
  20650. if (parsedData.particleSystems) {
  20651. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20652. var parsedParticleSystem = parsedData.particleSystems[index];
  20653. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  20654. }
  20655. }
  20656. // Lens flares
  20657. if (parsedData.lensFlareSystems) {
  20658. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  20659. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20660. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  20661. }
  20662. }
  20663. // Shadows
  20664. if (parsedData.shadowGenerators) {
  20665. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  20666. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20667. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  20668. }
  20669. }
  20670. // Actions (scene)
  20671. if (parsedData.actions) {
  20672. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  20673. }
  20674. // Finish
  20675. return true;
  20676. }
  20677. });
  20678. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20679. })(BABYLON || (BABYLON = {}));
  20680. var BABYLON;
  20681. (function (BABYLON) {
  20682. var SpriteManager = (function () {
  20683. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20684. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20685. this.name = name;
  20686. this.cellSize = cellSize;
  20687. this.sprites = new Array();
  20688. this.renderingGroupId = 0;
  20689. this.layerMask = 0x0FFFFFFF;
  20690. this.fogEnabled = true;
  20691. this.isPickable = false;
  20692. this._vertexDeclaration = [4, 4, 4, 4];
  20693. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20694. this._capacity = capacity;
  20695. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20696. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20697. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20698. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20699. this._scene = scene;
  20700. this._scene.spriteManagers.push(this);
  20701. // VBO
  20702. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20703. var indices = [];
  20704. var index = 0;
  20705. for (var count = 0; count < capacity; count++) {
  20706. indices.push(index);
  20707. indices.push(index + 1);
  20708. indices.push(index + 2);
  20709. indices.push(index);
  20710. indices.push(index + 2);
  20711. indices.push(index + 3);
  20712. index += 4;
  20713. }
  20714. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20715. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20716. // Effects
  20717. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20718. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20719. }
  20720. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20721. var arrayOffset = index * 16;
  20722. if (offsetX === 0)
  20723. offsetX = this._epsilon;
  20724. else if (offsetX === 1)
  20725. offsetX = 1 - this._epsilon;
  20726. if (offsetY === 0)
  20727. offsetY = this._epsilon;
  20728. else if (offsetY === 1)
  20729. offsetY = 1 - this._epsilon;
  20730. this._vertices[arrayOffset] = sprite.position.x;
  20731. this._vertices[arrayOffset + 1] = sprite.position.y;
  20732. this._vertices[arrayOffset + 2] = sprite.position.z;
  20733. this._vertices[arrayOffset + 3] = sprite.angle;
  20734. this._vertices[arrayOffset + 4] = sprite.width;
  20735. this._vertices[arrayOffset + 5] = sprite.height;
  20736. this._vertices[arrayOffset + 6] = offsetX;
  20737. this._vertices[arrayOffset + 7] = offsetY;
  20738. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20739. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20740. var offset = (sprite.cellIndex / rowSize) >> 0;
  20741. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20742. this._vertices[arrayOffset + 11] = offset;
  20743. // Color
  20744. this._vertices[arrayOffset + 12] = sprite.color.r;
  20745. this._vertices[arrayOffset + 13] = sprite.color.g;
  20746. this._vertices[arrayOffset + 14] = sprite.color.b;
  20747. this._vertices[arrayOffset + 15] = sprite.color.a;
  20748. };
  20749. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20750. var count = Math.min(this._capacity, this.sprites.length);
  20751. var min = BABYLON.Vector3.Zero();
  20752. var max = BABYLON.Vector3.Zero();
  20753. var distance = Number.MAX_VALUE;
  20754. var currentSprite;
  20755. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20756. var cameraView = camera.getViewMatrix();
  20757. for (var index = 0; index < count; index++) {
  20758. var sprite = this.sprites[index];
  20759. if (!sprite) {
  20760. continue;
  20761. }
  20762. if (predicate) {
  20763. if (!predicate(sprite)) {
  20764. continue;
  20765. }
  20766. }
  20767. else if (!sprite.isPickable) {
  20768. continue;
  20769. }
  20770. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20771. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20772. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20773. if (ray.intersectsBoxMinMax(min, max)) {
  20774. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20775. if (distance > currentDistance) {
  20776. distance = currentDistance;
  20777. currentSprite = sprite;
  20778. if (fastCheck) {
  20779. break;
  20780. }
  20781. }
  20782. }
  20783. }
  20784. if (currentSprite) {
  20785. var result = new BABYLON.PickingInfo();
  20786. result.hit = true;
  20787. result.pickedSprite = currentSprite;
  20788. result.distance = distance;
  20789. return result;
  20790. }
  20791. return null;
  20792. };
  20793. SpriteManager.prototype.render = function () {
  20794. // Check
  20795. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20796. return;
  20797. var engine = this._scene.getEngine();
  20798. var baseSize = this._spriteTexture.getBaseSize();
  20799. // Sprites
  20800. var deltaTime = engine.getDeltaTime();
  20801. var max = Math.min(this._capacity, this.sprites.length);
  20802. var rowSize = baseSize.width / this.cellSize;
  20803. var offset = 0;
  20804. for (var index = 0; index < max; index++) {
  20805. var sprite = this.sprites[index];
  20806. if (!sprite) {
  20807. continue;
  20808. }
  20809. sprite._animate(deltaTime);
  20810. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20811. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20812. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20813. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20814. }
  20815. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20816. // Render
  20817. var effect = this._effectBase;
  20818. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20819. effect = this._effectFog;
  20820. }
  20821. engine.enableEffect(effect);
  20822. var viewMatrix = this._scene.getViewMatrix();
  20823. effect.setTexture("diffuseSampler", this._spriteTexture);
  20824. effect.setMatrix("view", viewMatrix);
  20825. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20826. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20827. // Fog
  20828. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20829. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20830. effect.setColor3("vFogColor", this._scene.fogColor);
  20831. }
  20832. // VBOs
  20833. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20834. // Draw order
  20835. engine.setDepthFunctionToLessOrEqual();
  20836. effect.setBool("alphaTest", true);
  20837. engine.setColorWrite(false);
  20838. engine.draw(true, 0, max * 6);
  20839. engine.setColorWrite(true);
  20840. effect.setBool("alphaTest", false);
  20841. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20842. engine.draw(true, 0, max * 6);
  20843. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20844. };
  20845. SpriteManager.prototype.dispose = function () {
  20846. if (this._vertexBuffer) {
  20847. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20848. this._vertexBuffer = null;
  20849. }
  20850. if (this._indexBuffer) {
  20851. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20852. this._indexBuffer = null;
  20853. }
  20854. if (this._spriteTexture) {
  20855. this._spriteTexture.dispose();
  20856. this._spriteTexture = null;
  20857. }
  20858. // Remove from scene
  20859. var index = this._scene.spriteManagers.indexOf(this);
  20860. this._scene.spriteManagers.splice(index, 1);
  20861. // Callback
  20862. if (this.onDispose) {
  20863. this.onDispose();
  20864. }
  20865. };
  20866. return SpriteManager;
  20867. })();
  20868. BABYLON.SpriteManager = SpriteManager;
  20869. })(BABYLON || (BABYLON = {}));
  20870. var BABYLON;
  20871. (function (BABYLON) {
  20872. var Sprite = (function () {
  20873. function Sprite(name, manager) {
  20874. this.name = name;
  20875. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20876. this.width = 1.0;
  20877. this.height = 1.0;
  20878. this.angle = 0;
  20879. this.cellIndex = 0;
  20880. this.invertU = 0;
  20881. this.invertV = 0;
  20882. this.animations = new Array();
  20883. this.isPickable = false;
  20884. this._animationStarted = false;
  20885. this._loopAnimation = false;
  20886. this._fromIndex = 0;
  20887. this._toIndex = 0;
  20888. this._delay = 0;
  20889. this._direction = 1;
  20890. this._frameCount = 0;
  20891. this._time = 0;
  20892. this._manager = manager;
  20893. this._manager.sprites.push(this);
  20894. this.position = BABYLON.Vector3.Zero();
  20895. }
  20896. Object.defineProperty(Sprite.prototype, "size", {
  20897. get: function () {
  20898. return this.width;
  20899. },
  20900. set: function (value) {
  20901. this.width = value;
  20902. this.height = value;
  20903. },
  20904. enumerable: true,
  20905. configurable: true
  20906. });
  20907. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20908. this._fromIndex = from;
  20909. this._toIndex = to;
  20910. this._loopAnimation = loop;
  20911. this._delay = delay;
  20912. this._animationStarted = true;
  20913. this._direction = from < to ? 1 : -1;
  20914. this.cellIndex = from;
  20915. this._time = 0;
  20916. };
  20917. Sprite.prototype.stopAnimation = function () {
  20918. this._animationStarted = false;
  20919. };
  20920. Sprite.prototype._animate = function (deltaTime) {
  20921. if (!this._animationStarted)
  20922. return;
  20923. this._time += deltaTime;
  20924. if (this._time > this._delay) {
  20925. this._time = this._time % this._delay;
  20926. this.cellIndex += this._direction;
  20927. if (this.cellIndex == this._toIndex) {
  20928. if (this._loopAnimation) {
  20929. this.cellIndex = this._fromIndex;
  20930. }
  20931. else {
  20932. this._animationStarted = false;
  20933. if (this.disposeWhenFinishedAnimating) {
  20934. this.dispose();
  20935. }
  20936. }
  20937. }
  20938. }
  20939. };
  20940. Sprite.prototype.dispose = function () {
  20941. for (var i = 0; i < this._manager.sprites.length; i++) {
  20942. if (this._manager.sprites[i] == this) {
  20943. this._manager.sprites.splice(i, 1);
  20944. }
  20945. }
  20946. };
  20947. return Sprite;
  20948. })();
  20949. BABYLON.Sprite = Sprite;
  20950. })(BABYLON || (BABYLON = {}));
  20951. var BABYLON;
  20952. (function (BABYLON) {
  20953. var Layer = (function () {
  20954. function Layer(name, imgUrl, scene, isBackground, color) {
  20955. this.name = name;
  20956. this.scale = new BABYLON.Vector2(1, 1);
  20957. this.offset = new BABYLON.Vector2(0, 0);
  20958. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  20959. this._vertexDeclaration = [2];
  20960. this._vertexStrideSize = 2 * 4;
  20961. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20962. this.isBackground = isBackground === undefined ? true : isBackground;
  20963. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20964. this._scene = scene;
  20965. this._scene.layers.push(this);
  20966. // VBO
  20967. var vertices = [];
  20968. vertices.push(1, 1);
  20969. vertices.push(-1, 1);
  20970. vertices.push(-1, -1);
  20971. vertices.push(1, -1);
  20972. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20973. // Indices
  20974. var indices = [];
  20975. indices.push(0);
  20976. indices.push(1);
  20977. indices.push(2);
  20978. indices.push(0);
  20979. indices.push(2);
  20980. indices.push(3);
  20981. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20982. // Effects
  20983. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  20984. }
  20985. Layer.prototype.render = function () {
  20986. // Check
  20987. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20988. return;
  20989. var engine = this._scene.getEngine();
  20990. // Render
  20991. engine.enableEffect(this._effect);
  20992. engine.setState(false);
  20993. // Texture
  20994. this._effect.setTexture("textureSampler", this.texture);
  20995. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20996. // Color
  20997. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20998. // Scale / offset
  20999. this._effect.setVector2("offset", this.offset);
  21000. this._effect.setVector2("scale", this.scale);
  21001. // VBOs
  21002. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21003. // Draw order
  21004. engine.setAlphaMode(this.alphaBlendingMode);
  21005. engine.draw(true, 0, 6);
  21006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21007. };
  21008. Layer.prototype.dispose = function () {
  21009. if (this._vertexBuffer) {
  21010. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21011. this._vertexBuffer = null;
  21012. }
  21013. if (this._indexBuffer) {
  21014. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21015. this._indexBuffer = null;
  21016. }
  21017. if (this.texture) {
  21018. this.texture.dispose();
  21019. this.texture = null;
  21020. }
  21021. // Remove from scene
  21022. var index = this._scene.layers.indexOf(this);
  21023. this._scene.layers.splice(index, 1);
  21024. // Callback
  21025. if (this.onDispose) {
  21026. this.onDispose();
  21027. }
  21028. };
  21029. return Layer;
  21030. })();
  21031. BABYLON.Layer = Layer;
  21032. })(BABYLON || (BABYLON = {}));
  21033. var BABYLON;
  21034. (function (BABYLON) {
  21035. var Particle = (function () {
  21036. function Particle() {
  21037. this.position = BABYLON.Vector3.Zero();
  21038. this.direction = BABYLON.Vector3.Zero();
  21039. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21040. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21041. this.lifeTime = 1.0;
  21042. this.age = 0;
  21043. this.size = 0;
  21044. this.angle = 0;
  21045. this.angularSpeed = 0;
  21046. }
  21047. Particle.prototype.copyTo = function (other) {
  21048. other.position.copyFrom(this.position);
  21049. other.direction.copyFrom(this.direction);
  21050. other.color.copyFrom(this.color);
  21051. other.colorStep.copyFrom(this.colorStep);
  21052. other.lifeTime = this.lifeTime;
  21053. other.age = this.age;
  21054. other.size = this.size;
  21055. other.angle = this.angle;
  21056. other.angularSpeed = this.angularSpeed;
  21057. };
  21058. return Particle;
  21059. })();
  21060. BABYLON.Particle = Particle;
  21061. })(BABYLON || (BABYLON = {}));
  21062. var BABYLON;
  21063. (function (BABYLON) {
  21064. var randomNumber = function (min, max) {
  21065. if (min === max) {
  21066. return (min);
  21067. }
  21068. var random = Math.random();
  21069. return ((random * (max - min)) + min);
  21070. };
  21071. var ParticleSystem = (function () {
  21072. function ParticleSystem(name, capacity, scene, customEffect) {
  21073. var _this = this;
  21074. this.name = name;
  21075. this.renderingGroupId = 0;
  21076. this.emitter = null;
  21077. this.emitRate = 10;
  21078. this.manualEmitCount = -1;
  21079. this.updateSpeed = 0.01;
  21080. this.targetStopDuration = 0;
  21081. this.disposeOnStop = false;
  21082. this.minEmitPower = 1;
  21083. this.maxEmitPower = 1;
  21084. this.minLifeTime = 1;
  21085. this.maxLifeTime = 1;
  21086. this.minSize = 1;
  21087. this.maxSize = 1;
  21088. this.minAngularSpeed = 0;
  21089. this.maxAngularSpeed = 0;
  21090. this.layerMask = 0x0FFFFFFF;
  21091. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21092. this.forceDepthWrite = false;
  21093. this.gravity = BABYLON.Vector3.Zero();
  21094. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21095. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21096. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21097. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21098. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21099. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21100. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21101. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21102. this.particles = new Array();
  21103. this._vertexDeclaration = [3, 4, 4];
  21104. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21105. this._stockParticles = new Array();
  21106. this._newPartsExcess = 0;
  21107. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21108. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21109. this._scaledDirection = BABYLON.Vector3.Zero();
  21110. this._scaledGravity = BABYLON.Vector3.Zero();
  21111. this._currentRenderId = -1;
  21112. this._started = false;
  21113. this._stopped = false;
  21114. this._actualFrame = 0;
  21115. this.id = name;
  21116. this._capacity = capacity;
  21117. this._scene = scene;
  21118. this._customEffect = customEffect;
  21119. scene.particleSystems.push(this);
  21120. // VBO
  21121. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21122. var indices = [];
  21123. var index = 0;
  21124. for (var count = 0; count < capacity; count++) {
  21125. indices.push(index);
  21126. indices.push(index + 1);
  21127. indices.push(index + 2);
  21128. indices.push(index);
  21129. indices.push(index + 2);
  21130. indices.push(index + 3);
  21131. index += 4;
  21132. }
  21133. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21134. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21135. // Default behaviors
  21136. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21137. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21138. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21139. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21140. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21141. };
  21142. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21143. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21144. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21145. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21146. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21147. };
  21148. this.updateFunction = function (particles) {
  21149. for (var index = 0; index < particles.length; index++) {
  21150. var particle = particles[index];
  21151. particle.age += _this._scaledUpdateSpeed;
  21152. if (particle.age >= particle.lifeTime) {
  21153. _this.recycleParticle(particle);
  21154. index--;
  21155. continue;
  21156. }
  21157. else {
  21158. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21159. particle.color.addInPlace(_this._scaledColorStep);
  21160. if (particle.color.a < 0)
  21161. particle.color.a = 0;
  21162. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21163. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21164. particle.position.addInPlace(_this._scaledDirection);
  21165. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21166. particle.direction.addInPlace(_this._scaledGravity);
  21167. }
  21168. }
  21169. };
  21170. }
  21171. ParticleSystem.prototype.recycleParticle = function (particle) {
  21172. var lastParticle = this.particles.pop();
  21173. if (lastParticle !== particle) {
  21174. lastParticle.copyTo(particle);
  21175. this._stockParticles.push(lastParticle);
  21176. }
  21177. };
  21178. ParticleSystem.prototype.getCapacity = function () {
  21179. return this._capacity;
  21180. };
  21181. ParticleSystem.prototype.isAlive = function () {
  21182. return this._alive;
  21183. };
  21184. ParticleSystem.prototype.isStarted = function () {
  21185. return this._started;
  21186. };
  21187. ParticleSystem.prototype.start = function () {
  21188. this._started = true;
  21189. this._stopped = false;
  21190. this._actualFrame = 0;
  21191. };
  21192. ParticleSystem.prototype.stop = function () {
  21193. this._stopped = true;
  21194. };
  21195. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21196. var offset = index * 11;
  21197. this._vertices[offset] = particle.position.x;
  21198. this._vertices[offset + 1] = particle.position.y;
  21199. this._vertices[offset + 2] = particle.position.z;
  21200. this._vertices[offset + 3] = particle.color.r;
  21201. this._vertices[offset + 4] = particle.color.g;
  21202. this._vertices[offset + 5] = particle.color.b;
  21203. this._vertices[offset + 6] = particle.color.a;
  21204. this._vertices[offset + 7] = particle.angle;
  21205. this._vertices[offset + 8] = particle.size;
  21206. this._vertices[offset + 9] = offsetX;
  21207. this._vertices[offset + 10] = offsetY;
  21208. };
  21209. ParticleSystem.prototype._update = function (newParticles) {
  21210. // Update current
  21211. this._alive = this.particles.length > 0;
  21212. this.updateFunction(this.particles);
  21213. // Add new ones
  21214. var worldMatrix;
  21215. if (this.emitter.position) {
  21216. worldMatrix = this.emitter.getWorldMatrix();
  21217. }
  21218. else {
  21219. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21220. }
  21221. var particle;
  21222. for (var index = 0; index < newParticles; index++) {
  21223. if (this.particles.length === this._capacity) {
  21224. break;
  21225. }
  21226. if (this._stockParticles.length !== 0) {
  21227. particle = this._stockParticles.pop();
  21228. particle.age = 0;
  21229. }
  21230. else {
  21231. particle = new BABYLON.Particle();
  21232. }
  21233. this.particles.push(particle);
  21234. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21235. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21236. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21237. particle.size = randomNumber(this.minSize, this.maxSize);
  21238. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21239. this.startPositionFunction(worldMatrix, particle.position, particle);
  21240. var step = randomNumber(0, 1.0);
  21241. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21242. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21243. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21244. }
  21245. };
  21246. ParticleSystem.prototype._getEffect = function () {
  21247. if (this._customEffect) {
  21248. return this._customEffect;
  21249. }
  21250. ;
  21251. var defines = [];
  21252. if (this._scene.clipPlane) {
  21253. defines.push("#define CLIPPLANE");
  21254. }
  21255. // Effect
  21256. var join = defines.join("\n");
  21257. if (this._cachedDefines !== join) {
  21258. this._cachedDefines = join;
  21259. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21260. }
  21261. return this._effect;
  21262. };
  21263. ParticleSystem.prototype.animate = function () {
  21264. if (!this._started)
  21265. return;
  21266. var effect = this._getEffect();
  21267. // Check
  21268. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21269. return;
  21270. if (this._currentRenderId === this._scene.getRenderId()) {
  21271. return;
  21272. }
  21273. this._currentRenderId = this._scene.getRenderId();
  21274. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21275. // determine the number of particles we need to create
  21276. var newParticles;
  21277. if (this.manualEmitCount > -1) {
  21278. newParticles = this.manualEmitCount;
  21279. this._newPartsExcess = 0;
  21280. this.manualEmitCount = 0;
  21281. }
  21282. else {
  21283. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21284. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21285. }
  21286. if (this._newPartsExcess > 1.0) {
  21287. newParticles += this._newPartsExcess >> 0;
  21288. this._newPartsExcess -= this._newPartsExcess >> 0;
  21289. }
  21290. this._alive = false;
  21291. if (!this._stopped) {
  21292. this._actualFrame += this._scaledUpdateSpeed;
  21293. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21294. this.stop();
  21295. }
  21296. else {
  21297. newParticles = 0;
  21298. }
  21299. this._update(newParticles);
  21300. // Stopped?
  21301. if (this._stopped) {
  21302. if (!this._alive) {
  21303. this._started = false;
  21304. if (this.disposeOnStop) {
  21305. this._scene._toBeDisposed.push(this);
  21306. }
  21307. }
  21308. }
  21309. // Update VBO
  21310. var offset = 0;
  21311. for (var index = 0; index < this.particles.length; index++) {
  21312. var particle = this.particles[index];
  21313. this._appendParticleVertex(offset++, particle, 0, 0);
  21314. this._appendParticleVertex(offset++, particle, 1, 0);
  21315. this._appendParticleVertex(offset++, particle, 1, 1);
  21316. this._appendParticleVertex(offset++, particle, 0, 1);
  21317. }
  21318. var engine = this._scene.getEngine();
  21319. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21320. };
  21321. ParticleSystem.prototype.render = function () {
  21322. var effect = this._getEffect();
  21323. // Check
  21324. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21325. return 0;
  21326. var engine = this._scene.getEngine();
  21327. // Render
  21328. engine.enableEffect(effect);
  21329. engine.setState(false);
  21330. var viewMatrix = this._scene.getViewMatrix();
  21331. effect.setTexture("diffuseSampler", this.particleTexture);
  21332. effect.setMatrix("view", viewMatrix);
  21333. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21334. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21335. if (this._scene.clipPlane) {
  21336. var clipPlane = this._scene.clipPlane;
  21337. var invView = viewMatrix.clone();
  21338. invView.invert();
  21339. effect.setMatrix("invView", invView);
  21340. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21341. }
  21342. // VBOs
  21343. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21344. // Draw order
  21345. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21346. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21347. }
  21348. else {
  21349. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21350. }
  21351. if (this.forceDepthWrite) {
  21352. engine.setDepthWrite(true);
  21353. }
  21354. engine.draw(true, 0, this.particles.length * 6);
  21355. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21356. return this.particles.length;
  21357. };
  21358. ParticleSystem.prototype.dispose = function () {
  21359. if (this._vertexBuffer) {
  21360. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21361. this._vertexBuffer = null;
  21362. }
  21363. if (this._indexBuffer) {
  21364. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21365. this._indexBuffer = null;
  21366. }
  21367. if (this.particleTexture) {
  21368. this.particleTexture.dispose();
  21369. this.particleTexture = null;
  21370. }
  21371. // Remove from scene
  21372. var index = this._scene.particleSystems.indexOf(this);
  21373. this._scene.particleSystems.splice(index, 1);
  21374. // Callback
  21375. if (this.onDispose) {
  21376. this.onDispose();
  21377. }
  21378. };
  21379. // Clone
  21380. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21381. var result = new ParticleSystem(name, this._capacity, this._scene);
  21382. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21383. if (newEmitter === undefined) {
  21384. newEmitter = this.emitter;
  21385. }
  21386. result.emitter = newEmitter;
  21387. if (this.particleTexture) {
  21388. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21389. }
  21390. result.start();
  21391. return result;
  21392. };
  21393. ParticleSystem.prototype.serialize = function () {
  21394. var serializationObject = {};
  21395. serializationObject.name = this.name;
  21396. if (this.emitter.position) {
  21397. serializationObject.emitterId = this.emitter.id;
  21398. }
  21399. else {
  21400. serializationObject.emitter = this.emitter.asArray();
  21401. ;
  21402. }
  21403. serializationObject.capacity = this.getCapacity();
  21404. if (this.particleTexture) {
  21405. serializationObject.textureName = this.particleTexture.name;
  21406. }
  21407. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21408. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21409. serializationObject.minSize = this.minSize;
  21410. serializationObject.maxSize = this.maxSize;
  21411. serializationObject.minEmitPower = this.minEmitPower;
  21412. serializationObject.maxEmitPower = this.maxEmitPower;
  21413. serializationObject.minLifeTime = this.minLifeTime;
  21414. serializationObject.maxLifeTime = this.maxLifeTime;
  21415. serializationObject.emitRate = this.emitRate;
  21416. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21417. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21418. serializationObject.gravity = this.gravity.asArray();
  21419. serializationObject.direction1 = this.direction1.asArray();
  21420. serializationObject.direction2 = this.direction2.asArray();
  21421. serializationObject.color1 = this.color1.asArray();
  21422. serializationObject.color2 = this.color2.asArray();
  21423. serializationObject.colorDead = this.colorDead.asArray();
  21424. serializationObject.updateSpeed = this.updateSpeed;
  21425. serializationObject.targetStopDuration = this.targetStopDuration;
  21426. serializationObject.textureMask = this.textureMask.asArray();
  21427. serializationObject.blendMode = this.blendMode;
  21428. return serializationObject;
  21429. };
  21430. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21431. var name = parsedParticleSystem.name;
  21432. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21433. if (parsedParticleSystem.textureName) {
  21434. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21435. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21436. }
  21437. if (parsedParticleSystem.emitterId) {
  21438. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21439. }
  21440. else {
  21441. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21442. }
  21443. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21444. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21445. particleSystem.minSize = parsedParticleSystem.minSize;
  21446. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21447. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21448. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21449. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21450. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21451. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21452. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21453. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21454. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21455. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21456. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21457. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21458. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21459. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21460. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21461. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21462. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21463. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21464. particleSystem.start();
  21465. return particleSystem;
  21466. };
  21467. // Statics
  21468. ParticleSystem.BLENDMODE_ONEONE = 0;
  21469. ParticleSystem.BLENDMODE_STANDARD = 1;
  21470. return ParticleSystem;
  21471. })();
  21472. BABYLON.ParticleSystem = ParticleSystem;
  21473. })(BABYLON || (BABYLON = {}));
  21474. var BABYLON;
  21475. (function (BABYLON) {
  21476. var AnimationRange = (function () {
  21477. function AnimationRange(name, from, to) {
  21478. this.name = name;
  21479. this.from = from;
  21480. this.to = to;
  21481. }
  21482. return AnimationRange;
  21483. })();
  21484. BABYLON.AnimationRange = AnimationRange;
  21485. /**
  21486. * Composed of a frame, and an action function
  21487. */
  21488. var AnimationEvent = (function () {
  21489. function AnimationEvent(frame, action, onlyOnce) {
  21490. this.frame = frame;
  21491. this.action = action;
  21492. this.onlyOnce = onlyOnce;
  21493. this.isDone = false;
  21494. }
  21495. return AnimationEvent;
  21496. })();
  21497. BABYLON.AnimationEvent = AnimationEvent;
  21498. var Animation = (function () {
  21499. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21500. this.name = name;
  21501. this.targetProperty = targetProperty;
  21502. this.framePerSecond = framePerSecond;
  21503. this.dataType = dataType;
  21504. this.loopMode = loopMode;
  21505. this._offsetsCache = {};
  21506. this._highLimitsCache = {};
  21507. this._stopped = false;
  21508. // The set of event that will be linked to this animation
  21509. this._events = new Array();
  21510. this.allowMatricesInterpolation = false;
  21511. this._ranges = {};
  21512. this.targetPropertyPath = targetProperty.split(".");
  21513. this.dataType = dataType;
  21514. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21515. }
  21516. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21517. var dataType = undefined;
  21518. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21519. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21520. }
  21521. else if (from instanceof BABYLON.Quaternion) {
  21522. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21523. }
  21524. else if (from instanceof BABYLON.Vector3) {
  21525. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21526. }
  21527. else if (from instanceof BABYLON.Vector2) {
  21528. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21529. }
  21530. else if (from instanceof BABYLON.Color3) {
  21531. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21532. }
  21533. if (dataType == undefined) {
  21534. return null;
  21535. }
  21536. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21537. var keys = [];
  21538. keys.push({ frame: 0, value: from });
  21539. keys.push({ frame: totalFrame, value: to });
  21540. animation.setKeys(keys);
  21541. if (easingFunction !== undefined) {
  21542. animation.setEasingFunction(easingFunction);
  21543. }
  21544. return animation;
  21545. };
  21546. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21547. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21548. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21549. };
  21550. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21551. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21552. node.animations.push(animation);
  21553. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21554. };
  21555. // Methods
  21556. /**
  21557. * Add an event to this animation.
  21558. */
  21559. Animation.prototype.addEvent = function (event) {
  21560. this._events.push(event);
  21561. };
  21562. /**
  21563. * Remove all events found at the given frame
  21564. * @param frame
  21565. */
  21566. Animation.prototype.removeEvents = function (frame) {
  21567. for (var index = 0; index < this._events.length; index++) {
  21568. if (this._events[index].frame === frame) {
  21569. this._events.splice(index, 1);
  21570. index--;
  21571. }
  21572. }
  21573. };
  21574. Animation.prototype.createRange = function (name, from, to) {
  21575. // check name not already in use; could happen for bones after serialized
  21576. if (!this._ranges[name]) {
  21577. this._ranges[name] = new AnimationRange(name, from, to);
  21578. }
  21579. };
  21580. Animation.prototype.deleteRange = function (name, deleteFrames) {
  21581. if (deleteFrames === void 0) { deleteFrames = true; }
  21582. if (this._ranges[name]) {
  21583. if (deleteFrames) {
  21584. var from = this._ranges[name].from;
  21585. var to = this._ranges[name].to;
  21586. // this loop MUST go high to low for multiple splices to work
  21587. for (var key = this._keys.length - 1; key >= 0; key--) {
  21588. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  21589. this._keys.splice(key, 1);
  21590. }
  21591. }
  21592. }
  21593. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  21594. }
  21595. };
  21596. Animation.prototype.getRange = function (name) {
  21597. return this._ranges[name];
  21598. };
  21599. Animation.prototype.reset = function () {
  21600. this._offsetsCache = {};
  21601. this._highLimitsCache = {};
  21602. this.currentFrame = 0;
  21603. };
  21604. Animation.prototype.isStopped = function () {
  21605. return this._stopped;
  21606. };
  21607. Animation.prototype.getKeys = function () {
  21608. return this._keys;
  21609. };
  21610. Animation.prototype.getHighestFrame = function () {
  21611. var ret = 0;
  21612. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  21613. if (ret < this._keys[key].frame) {
  21614. ret = this._keys[key].frame;
  21615. }
  21616. }
  21617. return ret;
  21618. };
  21619. Animation.prototype.getEasingFunction = function () {
  21620. return this._easingFunction;
  21621. };
  21622. Animation.prototype.setEasingFunction = function (easingFunction) {
  21623. this._easingFunction = easingFunction;
  21624. };
  21625. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21626. return startValue + (endValue - startValue) * gradient;
  21627. };
  21628. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21629. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21630. };
  21631. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21632. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21633. };
  21634. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21635. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21636. };
  21637. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21638. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21639. };
  21640. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21641. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  21642. };
  21643. Animation.prototype.clone = function () {
  21644. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21645. if (this._keys) {
  21646. clone.setKeys(this._keys);
  21647. }
  21648. return clone;
  21649. };
  21650. Animation.prototype.setKeys = function (values) {
  21651. this._keys = values.slice(0);
  21652. this._offsetsCache = {};
  21653. this._highLimitsCache = {};
  21654. };
  21655. Animation.prototype._getKeyValue = function (value) {
  21656. if (typeof value === "function") {
  21657. return value();
  21658. }
  21659. return value;
  21660. };
  21661. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21662. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21663. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21664. }
  21665. this.currentFrame = currentFrame;
  21666. // Try to get a hash to find the right key
  21667. 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));
  21668. if (this._keys[startKey].frame >= currentFrame) {
  21669. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21670. startKey--;
  21671. }
  21672. }
  21673. for (var key = startKey; key < this._keys.length; key++) {
  21674. if (this._keys[key + 1].frame >= currentFrame) {
  21675. var startValue = this._getKeyValue(this._keys[key].value);
  21676. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21677. // gradient : percent of currentFrame between the frame inf and the frame sup
  21678. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21679. // check for easingFunction and correction of gradient
  21680. if (this._easingFunction != null) {
  21681. gradient = this._easingFunction.ease(gradient);
  21682. }
  21683. switch (this.dataType) {
  21684. // Float
  21685. case Animation.ANIMATIONTYPE_FLOAT:
  21686. switch (loopMode) {
  21687. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21688. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21689. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21690. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21691. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21692. }
  21693. break;
  21694. // Quaternion
  21695. case Animation.ANIMATIONTYPE_QUATERNION:
  21696. var quaternion = null;
  21697. switch (loopMode) {
  21698. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21699. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21700. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21701. break;
  21702. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21703. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21704. break;
  21705. }
  21706. return quaternion;
  21707. // Vector3
  21708. case Animation.ANIMATIONTYPE_VECTOR3:
  21709. switch (loopMode) {
  21710. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21711. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21712. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21713. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21714. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21715. }
  21716. // Vector2
  21717. case Animation.ANIMATIONTYPE_VECTOR2:
  21718. switch (loopMode) {
  21719. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21720. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21721. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21722. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21723. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21724. }
  21725. // Color3
  21726. case Animation.ANIMATIONTYPE_COLOR3:
  21727. switch (loopMode) {
  21728. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21729. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21730. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21731. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21732. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21733. }
  21734. // Matrix
  21735. case Animation.ANIMATIONTYPE_MATRIX:
  21736. switch (loopMode) {
  21737. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21738. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21739. if (this.allowMatricesInterpolation) {
  21740. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21741. }
  21742. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21743. return startValue;
  21744. }
  21745. default:
  21746. break;
  21747. }
  21748. break;
  21749. }
  21750. }
  21751. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21752. };
  21753. Animation.prototype.setValue = function (currentValue) {
  21754. // Set value
  21755. if (this.targetPropertyPath.length > 1) {
  21756. var property = this._target[this.targetPropertyPath[0]];
  21757. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21758. property = property[this.targetPropertyPath[index]];
  21759. }
  21760. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21761. }
  21762. else {
  21763. this._target[this.targetPropertyPath[0]] = currentValue;
  21764. }
  21765. if (this._target.markAsDirty) {
  21766. this._target.markAsDirty(this.targetProperty);
  21767. }
  21768. };
  21769. Animation.prototype.goToFrame = function (frame) {
  21770. if (frame < this._keys[0].frame) {
  21771. frame = this._keys[0].frame;
  21772. }
  21773. else if (frame > this._keys[this._keys.length - 1].frame) {
  21774. frame = this._keys[this._keys.length - 1].frame;
  21775. }
  21776. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21777. this.setValue(currentValue);
  21778. };
  21779. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21780. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21781. this._stopped = true;
  21782. return false;
  21783. }
  21784. var returnValue = true;
  21785. // Adding a start key at frame 0 if missing
  21786. if (this._keys[0].frame !== 0) {
  21787. var newKey = { frame: 0, value: this._keys[0].value };
  21788. this._keys.splice(0, 0, newKey);
  21789. }
  21790. // Check limits
  21791. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21792. from = this._keys[0].frame;
  21793. }
  21794. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21795. to = this._keys[this._keys.length - 1].frame;
  21796. }
  21797. // Compute ratio
  21798. var range = to - from;
  21799. var offsetValue;
  21800. // ratio represents the frame delta between from and to
  21801. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21802. var highLimitValue = 0;
  21803. if (ratio > range && !loop) {
  21804. returnValue = false;
  21805. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21806. }
  21807. else {
  21808. // Get max value if required
  21809. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21810. var keyOffset = to.toString() + from.toString();
  21811. if (!this._offsetsCache[keyOffset]) {
  21812. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21813. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21814. switch (this.dataType) {
  21815. // Float
  21816. case Animation.ANIMATIONTYPE_FLOAT:
  21817. this._offsetsCache[keyOffset] = toValue - fromValue;
  21818. break;
  21819. // Quaternion
  21820. case Animation.ANIMATIONTYPE_QUATERNION:
  21821. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21822. break;
  21823. // Vector3
  21824. case Animation.ANIMATIONTYPE_VECTOR3:
  21825. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21826. // Vector2
  21827. case Animation.ANIMATIONTYPE_VECTOR2:
  21828. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21829. // Color3
  21830. case Animation.ANIMATIONTYPE_COLOR3:
  21831. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21832. default:
  21833. break;
  21834. }
  21835. this._highLimitsCache[keyOffset] = toValue;
  21836. }
  21837. highLimitValue = this._highLimitsCache[keyOffset];
  21838. offsetValue = this._offsetsCache[keyOffset];
  21839. }
  21840. }
  21841. if (offsetValue === undefined) {
  21842. switch (this.dataType) {
  21843. // Float
  21844. case Animation.ANIMATIONTYPE_FLOAT:
  21845. offsetValue = 0;
  21846. break;
  21847. // Quaternion
  21848. case Animation.ANIMATIONTYPE_QUATERNION:
  21849. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21850. break;
  21851. // Vector3
  21852. case Animation.ANIMATIONTYPE_VECTOR3:
  21853. offsetValue = BABYLON.Vector3.Zero();
  21854. break;
  21855. // Vector2
  21856. case Animation.ANIMATIONTYPE_VECTOR2:
  21857. offsetValue = BABYLON.Vector2.Zero();
  21858. break;
  21859. // Color3
  21860. case Animation.ANIMATIONTYPE_COLOR3:
  21861. offsetValue = BABYLON.Color3.Black();
  21862. }
  21863. }
  21864. // Compute value
  21865. var repeatCount = (ratio / range) >> 0;
  21866. var currentFrame = returnValue ? from + ratio % range : to;
  21867. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21868. // Set value
  21869. this.setValue(currentValue);
  21870. // Check events
  21871. for (var index = 0; index < this._events.length; index++) {
  21872. if (currentFrame >= this._events[index].frame) {
  21873. var event = this._events[index];
  21874. if (!event.isDone) {
  21875. // If event should be done only once, remove it.
  21876. if (event.onlyOnce) {
  21877. this._events.splice(index, 1);
  21878. index--;
  21879. }
  21880. event.isDone = true;
  21881. event.action();
  21882. } // Don't do anything if the event has already be done.
  21883. }
  21884. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  21885. // reset event, the animation is looping
  21886. this._events[index].isDone = false;
  21887. }
  21888. }
  21889. if (!returnValue) {
  21890. this._stopped = true;
  21891. }
  21892. return returnValue;
  21893. };
  21894. Animation.prototype.serialize = function () {
  21895. var serializationObject = {};
  21896. serializationObject.name = this.name;
  21897. serializationObject.property = this.targetProperty;
  21898. serializationObject.framePerSecond = this.framePerSecond;
  21899. serializationObject.dataType = this.dataType;
  21900. serializationObject.loopBehavior = this.loopMode;
  21901. var dataType = this.dataType;
  21902. serializationObject.keys = [];
  21903. var keys = this.getKeys();
  21904. for (var index = 0; index < keys.length; index++) {
  21905. var animationKey = keys[index];
  21906. var key = {};
  21907. key.frame = animationKey.frame;
  21908. switch (dataType) {
  21909. case Animation.ANIMATIONTYPE_FLOAT:
  21910. key.values = [animationKey.value];
  21911. break;
  21912. case Animation.ANIMATIONTYPE_QUATERNION:
  21913. case Animation.ANIMATIONTYPE_MATRIX:
  21914. case Animation.ANIMATIONTYPE_VECTOR3:
  21915. case Animation.ANIMATIONTYPE_COLOR3:
  21916. key.values = animationKey.value.asArray();
  21917. break;
  21918. }
  21919. serializationObject.keys.push(key);
  21920. }
  21921. serializationObject.ranges = [];
  21922. for (var name in this._ranges) {
  21923. var range = {};
  21924. range.name = name;
  21925. range.from = this._ranges[name].from;
  21926. range.to = this._ranges[name].to;
  21927. serializationObject.ranges.push(range);
  21928. }
  21929. return serializationObject;
  21930. };
  21931. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21932. get: function () {
  21933. return Animation._ANIMATIONTYPE_FLOAT;
  21934. },
  21935. enumerable: true,
  21936. configurable: true
  21937. });
  21938. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21939. get: function () {
  21940. return Animation._ANIMATIONTYPE_VECTOR3;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21946. get: function () {
  21947. return Animation._ANIMATIONTYPE_VECTOR2;
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21953. get: function () {
  21954. return Animation._ANIMATIONTYPE_QUATERNION;
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21960. get: function () {
  21961. return Animation._ANIMATIONTYPE_MATRIX;
  21962. },
  21963. enumerable: true,
  21964. configurable: true
  21965. });
  21966. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21967. get: function () {
  21968. return Animation._ANIMATIONTYPE_COLOR3;
  21969. },
  21970. enumerable: true,
  21971. configurable: true
  21972. });
  21973. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21974. get: function () {
  21975. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21976. },
  21977. enumerable: true,
  21978. configurable: true
  21979. });
  21980. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21981. get: function () {
  21982. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21983. },
  21984. enumerable: true,
  21985. configurable: true
  21986. });
  21987. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21988. get: function () {
  21989. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21990. },
  21991. enumerable: true,
  21992. configurable: true
  21993. });
  21994. Animation.Parse = function (parsedAnimation) {
  21995. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  21996. var dataType = parsedAnimation.dataType;
  21997. var keys = [];
  21998. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  21999. var key = parsedAnimation.keys[index];
  22000. var data;
  22001. switch (dataType) {
  22002. case Animation.ANIMATIONTYPE_FLOAT:
  22003. data = key.values[0];
  22004. break;
  22005. case Animation.ANIMATIONTYPE_QUATERNION:
  22006. data = BABYLON.Quaternion.FromArray(key.values);
  22007. break;
  22008. case Animation.ANIMATIONTYPE_MATRIX:
  22009. data = BABYLON.Matrix.FromArray(key.values);
  22010. break;
  22011. case Animation.ANIMATIONTYPE_COLOR3:
  22012. data = BABYLON.Color3.FromArray(key.values);
  22013. break;
  22014. case Animation.ANIMATIONTYPE_VECTOR3:
  22015. default:
  22016. data = BABYLON.Vector3.FromArray(key.values);
  22017. break;
  22018. }
  22019. keys.push({
  22020. frame: key.frame,
  22021. value: data
  22022. });
  22023. }
  22024. animation.setKeys(keys);
  22025. if (parsedAnimation.ranges) {
  22026. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22027. data = parsedAnimation.ranges[index];
  22028. animation.createRange(data.name, data.from, data.to);
  22029. }
  22030. }
  22031. return animation;
  22032. };
  22033. Animation.AppendSerializedAnimations = function (source, destination) {
  22034. if (source.animations) {
  22035. destination.animations = [];
  22036. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22037. var animation = source.animations[animationIndex];
  22038. destination.animations.push(animation.serialize());
  22039. }
  22040. }
  22041. };
  22042. // Statics
  22043. Animation._ANIMATIONTYPE_FLOAT = 0;
  22044. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22045. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22046. Animation._ANIMATIONTYPE_MATRIX = 3;
  22047. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22048. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22049. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22050. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22051. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22052. return Animation;
  22053. })();
  22054. BABYLON.Animation = Animation;
  22055. })(BABYLON || (BABYLON = {}));
  22056. var BABYLON;
  22057. (function (BABYLON) {
  22058. var Animatable = (function () {
  22059. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22060. if (fromFrame === void 0) { fromFrame = 0; }
  22061. if (toFrame === void 0) { toFrame = 100; }
  22062. if (loopAnimation === void 0) { loopAnimation = false; }
  22063. if (speedRatio === void 0) { speedRatio = 1.0; }
  22064. this.target = target;
  22065. this.fromFrame = fromFrame;
  22066. this.toFrame = toFrame;
  22067. this.loopAnimation = loopAnimation;
  22068. this.speedRatio = speedRatio;
  22069. this.onAnimationEnd = onAnimationEnd;
  22070. this._animations = new Array();
  22071. this._paused = false;
  22072. this.animationStarted = false;
  22073. if (animations) {
  22074. this.appendAnimations(target, animations);
  22075. }
  22076. this._scene = scene;
  22077. scene._activeAnimatables.push(this);
  22078. }
  22079. // Methods
  22080. Animatable.prototype.getAnimations = function () {
  22081. return this._animations;
  22082. };
  22083. Animatable.prototype.appendAnimations = function (target, animations) {
  22084. for (var index = 0; index < animations.length; index++) {
  22085. var animation = animations[index];
  22086. animation._target = target;
  22087. this._animations.push(animation);
  22088. }
  22089. };
  22090. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22091. var animations = this._animations;
  22092. for (var index = 0; index < animations.length; index++) {
  22093. if (animations[index].targetProperty === property) {
  22094. return animations[index];
  22095. }
  22096. }
  22097. return null;
  22098. };
  22099. Animatable.prototype.reset = function () {
  22100. var animations = this._animations;
  22101. for (var index = 0; index < animations.length; index++) {
  22102. animations[index].reset();
  22103. }
  22104. this._localDelayOffset = null;
  22105. this._pausedDelay = null;
  22106. };
  22107. Animatable.prototype.goToFrame = function (frame) {
  22108. var animations = this._animations;
  22109. for (var index = 0; index < animations.length; index++) {
  22110. animations[index].goToFrame(frame);
  22111. }
  22112. };
  22113. Animatable.prototype.pause = function () {
  22114. if (this._paused) {
  22115. return;
  22116. }
  22117. this._paused = true;
  22118. };
  22119. Animatable.prototype.restart = function () {
  22120. this._paused = false;
  22121. };
  22122. Animatable.prototype.stop = function () {
  22123. var index = this._scene._activeAnimatables.indexOf(this);
  22124. if (index > -1) {
  22125. this._scene._activeAnimatables.splice(index, 1);
  22126. }
  22127. if (this.onAnimationEnd) {
  22128. this.onAnimationEnd();
  22129. }
  22130. };
  22131. Animatable.prototype._animate = function (delay) {
  22132. if (this._paused) {
  22133. this.animationStarted = false;
  22134. if (!this._pausedDelay) {
  22135. this._pausedDelay = delay;
  22136. }
  22137. return true;
  22138. }
  22139. if (!this._localDelayOffset) {
  22140. this._localDelayOffset = delay;
  22141. }
  22142. else if (this._pausedDelay) {
  22143. this._localDelayOffset += delay - this._pausedDelay;
  22144. this._pausedDelay = null;
  22145. }
  22146. // Animating
  22147. var running = false;
  22148. var animations = this._animations;
  22149. var index;
  22150. for (index = 0; index < animations.length; index++) {
  22151. var animation = animations[index];
  22152. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22153. running = running || isRunning;
  22154. }
  22155. this.animationStarted = running;
  22156. if (!running) {
  22157. // Remove from active animatables
  22158. index = this._scene._activeAnimatables.indexOf(this);
  22159. this._scene._activeAnimatables.splice(index, 1);
  22160. }
  22161. if (!running && this.onAnimationEnd) {
  22162. this.onAnimationEnd();
  22163. }
  22164. return running;
  22165. };
  22166. return Animatable;
  22167. })();
  22168. BABYLON.Animatable = Animatable;
  22169. })(BABYLON || (BABYLON = {}));
  22170. var BABYLON;
  22171. (function (BABYLON) {
  22172. var EasingFunction = (function () {
  22173. function EasingFunction() {
  22174. // Properties
  22175. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22176. }
  22177. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22178. get: function () {
  22179. return EasingFunction._EASINGMODE_EASEIN;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22185. get: function () {
  22186. return EasingFunction._EASINGMODE_EASEOUT;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22192. get: function () {
  22193. return EasingFunction._EASINGMODE_EASEINOUT;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22199. var n = Math.min(Math.max(easingMode, 0), 2);
  22200. this._easingMode = n;
  22201. };
  22202. EasingFunction.prototype.getEasingMode = function () {
  22203. return this._easingMode;
  22204. };
  22205. EasingFunction.prototype.easeInCore = function (gradient) {
  22206. throw new Error('You must implement this method');
  22207. };
  22208. EasingFunction.prototype.ease = function (gradient) {
  22209. switch (this._easingMode) {
  22210. case EasingFunction.EASINGMODE_EASEIN:
  22211. return this.easeInCore(gradient);
  22212. case EasingFunction.EASINGMODE_EASEOUT:
  22213. return (1 - this.easeInCore(1 - gradient));
  22214. }
  22215. if (gradient >= 0.5) {
  22216. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22217. }
  22218. return (this.easeInCore(gradient * 2) * 0.5);
  22219. };
  22220. //Statics
  22221. EasingFunction._EASINGMODE_EASEIN = 0;
  22222. EasingFunction._EASINGMODE_EASEOUT = 1;
  22223. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22224. return EasingFunction;
  22225. })();
  22226. BABYLON.EasingFunction = EasingFunction;
  22227. var CircleEase = (function (_super) {
  22228. __extends(CircleEase, _super);
  22229. function CircleEase() {
  22230. _super.apply(this, arguments);
  22231. }
  22232. CircleEase.prototype.easeInCore = function (gradient) {
  22233. gradient = Math.max(0, Math.min(1, gradient));
  22234. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22235. };
  22236. return CircleEase;
  22237. })(EasingFunction);
  22238. BABYLON.CircleEase = CircleEase;
  22239. var BackEase = (function (_super) {
  22240. __extends(BackEase, _super);
  22241. function BackEase(amplitude) {
  22242. if (amplitude === void 0) { amplitude = 1; }
  22243. _super.call(this);
  22244. this.amplitude = amplitude;
  22245. }
  22246. BackEase.prototype.easeInCore = function (gradient) {
  22247. var num = Math.max(0, this.amplitude);
  22248. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22249. };
  22250. return BackEase;
  22251. })(EasingFunction);
  22252. BABYLON.BackEase = BackEase;
  22253. var BounceEase = (function (_super) {
  22254. __extends(BounceEase, _super);
  22255. function BounceEase(bounces, bounciness) {
  22256. if (bounces === void 0) { bounces = 3; }
  22257. if (bounciness === void 0) { bounciness = 2; }
  22258. _super.call(this);
  22259. this.bounces = bounces;
  22260. this.bounciness = bounciness;
  22261. }
  22262. BounceEase.prototype.easeInCore = function (gradient) {
  22263. var y = Math.max(0.0, this.bounces);
  22264. var bounciness = this.bounciness;
  22265. if (bounciness <= 1.0) {
  22266. bounciness = 1.001;
  22267. }
  22268. var num9 = Math.pow(bounciness, y);
  22269. var num5 = 1.0 - bounciness;
  22270. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22271. var num15 = gradient * num4;
  22272. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22273. var num3 = Math.floor(num65);
  22274. var num13 = num3 + 1.0;
  22275. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22276. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22277. var num7 = (num8 + num12) * 0.5;
  22278. var num6 = gradient - num7;
  22279. var num2 = num7 - num8;
  22280. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22281. };
  22282. return BounceEase;
  22283. })(EasingFunction);
  22284. BABYLON.BounceEase = BounceEase;
  22285. var CubicEase = (function (_super) {
  22286. __extends(CubicEase, _super);
  22287. function CubicEase() {
  22288. _super.apply(this, arguments);
  22289. }
  22290. CubicEase.prototype.easeInCore = function (gradient) {
  22291. return (gradient * gradient * gradient);
  22292. };
  22293. return CubicEase;
  22294. })(EasingFunction);
  22295. BABYLON.CubicEase = CubicEase;
  22296. var ElasticEase = (function (_super) {
  22297. __extends(ElasticEase, _super);
  22298. function ElasticEase(oscillations, springiness) {
  22299. if (oscillations === void 0) { oscillations = 3; }
  22300. if (springiness === void 0) { springiness = 3; }
  22301. _super.call(this);
  22302. this.oscillations = oscillations;
  22303. this.springiness = springiness;
  22304. }
  22305. ElasticEase.prototype.easeInCore = function (gradient) {
  22306. var num2;
  22307. var num3 = Math.max(0.0, this.oscillations);
  22308. var num = Math.max(0.0, this.springiness);
  22309. if (num == 0) {
  22310. num2 = gradient;
  22311. }
  22312. else {
  22313. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22314. }
  22315. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22316. };
  22317. return ElasticEase;
  22318. })(EasingFunction);
  22319. BABYLON.ElasticEase = ElasticEase;
  22320. var ExponentialEase = (function (_super) {
  22321. __extends(ExponentialEase, _super);
  22322. function ExponentialEase(exponent) {
  22323. if (exponent === void 0) { exponent = 2; }
  22324. _super.call(this);
  22325. this.exponent = exponent;
  22326. }
  22327. ExponentialEase.prototype.easeInCore = function (gradient) {
  22328. if (this.exponent <= 0) {
  22329. return gradient;
  22330. }
  22331. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22332. };
  22333. return ExponentialEase;
  22334. })(EasingFunction);
  22335. BABYLON.ExponentialEase = ExponentialEase;
  22336. var PowerEase = (function (_super) {
  22337. __extends(PowerEase, _super);
  22338. function PowerEase(power) {
  22339. if (power === void 0) { power = 2; }
  22340. _super.call(this);
  22341. this.power = power;
  22342. }
  22343. PowerEase.prototype.easeInCore = function (gradient) {
  22344. var y = Math.max(0.0, this.power);
  22345. return Math.pow(gradient, y);
  22346. };
  22347. return PowerEase;
  22348. })(EasingFunction);
  22349. BABYLON.PowerEase = PowerEase;
  22350. var QuadraticEase = (function (_super) {
  22351. __extends(QuadraticEase, _super);
  22352. function QuadraticEase() {
  22353. _super.apply(this, arguments);
  22354. }
  22355. QuadraticEase.prototype.easeInCore = function (gradient) {
  22356. return (gradient * gradient);
  22357. };
  22358. return QuadraticEase;
  22359. })(EasingFunction);
  22360. BABYLON.QuadraticEase = QuadraticEase;
  22361. var QuarticEase = (function (_super) {
  22362. __extends(QuarticEase, _super);
  22363. function QuarticEase() {
  22364. _super.apply(this, arguments);
  22365. }
  22366. QuarticEase.prototype.easeInCore = function (gradient) {
  22367. return (gradient * gradient * gradient * gradient);
  22368. };
  22369. return QuarticEase;
  22370. })(EasingFunction);
  22371. BABYLON.QuarticEase = QuarticEase;
  22372. var QuinticEase = (function (_super) {
  22373. __extends(QuinticEase, _super);
  22374. function QuinticEase() {
  22375. _super.apply(this, arguments);
  22376. }
  22377. QuinticEase.prototype.easeInCore = function (gradient) {
  22378. return (gradient * gradient * gradient * gradient * gradient);
  22379. };
  22380. return QuinticEase;
  22381. })(EasingFunction);
  22382. BABYLON.QuinticEase = QuinticEase;
  22383. var SineEase = (function (_super) {
  22384. __extends(SineEase, _super);
  22385. function SineEase() {
  22386. _super.apply(this, arguments);
  22387. }
  22388. SineEase.prototype.easeInCore = function (gradient) {
  22389. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22390. };
  22391. return SineEase;
  22392. })(EasingFunction);
  22393. BABYLON.SineEase = SineEase;
  22394. var BezierCurveEase = (function (_super) {
  22395. __extends(BezierCurveEase, _super);
  22396. function BezierCurveEase(x1, y1, x2, y2) {
  22397. if (x1 === void 0) { x1 = 0; }
  22398. if (y1 === void 0) { y1 = 0; }
  22399. if (x2 === void 0) { x2 = 1; }
  22400. if (y2 === void 0) { y2 = 1; }
  22401. _super.call(this);
  22402. this.x1 = x1;
  22403. this.y1 = y1;
  22404. this.x2 = x2;
  22405. this.y2 = y2;
  22406. }
  22407. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22408. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22409. };
  22410. return BezierCurveEase;
  22411. })(EasingFunction);
  22412. BABYLON.BezierCurveEase = BezierCurveEase;
  22413. })(BABYLON || (BABYLON = {}));
  22414. var BABYLON;
  22415. (function (BABYLON) {
  22416. var Bone = (function (_super) {
  22417. __extends(Bone, _super);
  22418. function Bone(name, skeleton, parentBone, matrix, restPose) {
  22419. _super.call(this, name, skeleton.getScene());
  22420. this.name = name;
  22421. this.children = new Array();
  22422. this.animations = new Array();
  22423. this._worldTransform = new BABYLON.Matrix();
  22424. this._absoluteTransform = new BABYLON.Matrix();
  22425. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22426. this._skeleton = skeleton;
  22427. this._matrix = matrix;
  22428. this._baseMatrix = matrix;
  22429. this._restPose = restPose ? restPose : matrix.clone();
  22430. skeleton.bones.push(this);
  22431. if (parentBone) {
  22432. this._parent = parentBone;
  22433. parentBone.children.push(this);
  22434. }
  22435. else {
  22436. this._parent = null;
  22437. }
  22438. this._updateDifferenceMatrix();
  22439. }
  22440. // Members
  22441. Bone.prototype.getParent = function () {
  22442. return this._parent;
  22443. };
  22444. Bone.prototype.getLocalMatrix = function () {
  22445. return this._matrix;
  22446. };
  22447. Bone.prototype.getBaseMatrix = function () {
  22448. return this._baseMatrix;
  22449. };
  22450. Bone.prototype.getRestPose = function () {
  22451. return this._restPose;
  22452. };
  22453. Bone.prototype.returnToRest = function () {
  22454. this.updateMatrix(this._restPose.clone());
  22455. };
  22456. Bone.prototype.getWorldMatrix = function () {
  22457. return this._worldTransform;
  22458. };
  22459. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22460. return this._invertedAbsoluteTransform;
  22461. };
  22462. Bone.prototype.getAbsoluteTransform = function () {
  22463. return this._absoluteTransform;
  22464. };
  22465. // Methods
  22466. Bone.prototype.updateMatrix = function (matrix) {
  22467. this._baseMatrix = matrix.clone();
  22468. this._skeleton._markAsDirty();
  22469. this._updateDifferenceMatrix();
  22470. };
  22471. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  22472. if (!rootMatrix) {
  22473. rootMatrix = this._baseMatrix;
  22474. }
  22475. if (this._parent) {
  22476. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22477. }
  22478. else {
  22479. this._absoluteTransform.copyFrom(rootMatrix);
  22480. }
  22481. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22482. for (var index = 0; index < this.children.length; index++) {
  22483. this.children[index]._updateDifferenceMatrix();
  22484. }
  22485. };
  22486. Bone.prototype.markAsDirty = function () {
  22487. this._currentRenderId++;
  22488. this._skeleton._markAsDirty();
  22489. };
  22490. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  22491. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22492. // all animation may be coming from a library skeleton, so may need to create animation
  22493. if (this.animations.length === 0) {
  22494. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  22495. }
  22496. // get animation info / verify there is such a range from the source bone
  22497. var sourceRange = source.animations[0].getRange(rangeName);
  22498. if (!sourceRange) {
  22499. return false;
  22500. }
  22501. var from = sourceRange.from;
  22502. var to = sourceRange.to;
  22503. var sourceKeys = source.animations[0].getKeys();
  22504. // rescaling prep
  22505. var sourceBoneLength = source.length;
  22506. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  22507. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  22508. var destKeys = this.animations[0].getKeys();
  22509. // loop vars declaration / initialization
  22510. var orig;
  22511. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22512. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  22513. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  22514. var mat;
  22515. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  22516. orig = sourceKeys[key];
  22517. if (orig.frame >= from && orig.frame <= to) {
  22518. if (scalingReqd) {
  22519. orig.value.decompose(origScale, origRotation, origTranslation);
  22520. origTranslation.scaleInPlace(ratio);
  22521. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  22522. }
  22523. else {
  22524. mat = orig.value;
  22525. }
  22526. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  22527. }
  22528. }
  22529. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  22530. return true;
  22531. };
  22532. return Bone;
  22533. })(BABYLON.Node);
  22534. BABYLON.Bone = Bone;
  22535. })(BABYLON || (BABYLON = {}));
  22536. var BABYLON;
  22537. (function (BABYLON) {
  22538. var Skeleton = (function () {
  22539. function Skeleton(name, id, scene) {
  22540. this.name = name;
  22541. this.id = id;
  22542. this.bones = new Array();
  22543. this.needInitialSkinMatrix = false;
  22544. this._isDirty = true;
  22545. this._meshesWithPoseMatrix = new Array();
  22546. this._identity = BABYLON.Matrix.Identity();
  22547. this._ranges = {};
  22548. this.bones = [];
  22549. this._scene = scene;
  22550. scene.skeletons.push(this);
  22551. this.prepare();
  22552. //make sure it will recalculate the matrix next time prepare is called.
  22553. this._isDirty = true;
  22554. }
  22555. // Members
  22556. Skeleton.prototype.getTransformMatrices = function (mesh) {
  22557. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  22558. return mesh._bonesTransformMatrices;
  22559. }
  22560. return this._transformMatrices;
  22561. };
  22562. Skeleton.prototype.getScene = function () {
  22563. return this._scene;
  22564. };
  22565. // Methods
  22566. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22567. // check name not already in use
  22568. if (!this._ranges[name]) {
  22569. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  22570. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22571. if (this.bones[i].animations[0]) {
  22572. this.bones[i].animations[0].createRange(name, from, to);
  22573. }
  22574. }
  22575. }
  22576. };
  22577. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  22578. if (deleteFrames === void 0) { deleteFrames = true; }
  22579. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22580. if (this.bones[i].animations[0]) {
  22581. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  22582. }
  22583. }
  22584. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22585. };
  22586. Skeleton.prototype.getAnimationRange = function (name) {
  22587. return this._ranges[name];
  22588. };
  22589. /**
  22590. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  22591. */
  22592. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  22593. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  22594. if (this._ranges[name] || !source.getAnimationRange(name)) {
  22595. return false;
  22596. }
  22597. var ret = true;
  22598. var frameOffset = this._getHighestAnimationFrame() + 1;
  22599. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  22600. var boneDict = {};
  22601. var sourceBones = source.bones;
  22602. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  22603. boneDict[sourceBones[i].name] = sourceBones[i];
  22604. }
  22605. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22606. var boneName = this.bones[i].name;
  22607. var sourceBone = boneDict[boneName];
  22608. if (sourceBone) {
  22609. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  22610. }
  22611. else {
  22612. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  22613. ret = false;
  22614. }
  22615. }
  22616. // do not call createAnimationRange(), since it also is done to bones, which was already done
  22617. var range = source.getAnimationRange(name);
  22618. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  22619. return ret;
  22620. };
  22621. Skeleton.prototype.returnToRest = function () {
  22622. for (var index = 0; index < this.bones.length; index++) {
  22623. this.bones[index].returnToRest();
  22624. }
  22625. };
  22626. Skeleton.prototype._getHighestAnimationFrame = function () {
  22627. var ret = 0;
  22628. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  22629. if (this.bones[i].animations[0]) {
  22630. var highest = this.bones[i].animations[0].getHighestFrame();
  22631. if (ret < highest) {
  22632. ret = highest;
  22633. }
  22634. }
  22635. }
  22636. return ret;
  22637. };
  22638. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22639. var range = this.getAnimationRange(name);
  22640. if (!range) {
  22641. return null;
  22642. }
  22643. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22644. };
  22645. Skeleton.prototype._markAsDirty = function () {
  22646. this._isDirty = true;
  22647. };
  22648. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  22649. this._meshesWithPoseMatrix.push(mesh);
  22650. };
  22651. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  22652. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  22653. if (index > -1) {
  22654. this._meshesWithPoseMatrix.splice(index, 1);
  22655. }
  22656. };
  22657. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  22658. for (var index = 0; index < this.bones.length; index++) {
  22659. var bone = this.bones[index];
  22660. var parentBone = bone.getParent();
  22661. if (parentBone) {
  22662. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22663. }
  22664. else {
  22665. if (initialSkinMatrix) {
  22666. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  22667. }
  22668. else {
  22669. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22670. }
  22671. }
  22672. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  22673. }
  22674. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  22675. };
  22676. Skeleton.prototype.prepare = function () {
  22677. if (!this._isDirty) {
  22678. return;
  22679. }
  22680. if (this.needInitialSkinMatrix) {
  22681. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  22682. var mesh = this._meshesWithPoseMatrix[index];
  22683. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  22684. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22685. }
  22686. var poseMatrix = mesh.getPoseMatrix();
  22687. // Prepare bones
  22688. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  22689. var bone = this.bones[boneIndex];
  22690. if (!bone.getParent()) {
  22691. var matrix = bone.getBaseMatrix();
  22692. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  22693. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  22694. }
  22695. }
  22696. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  22697. }
  22698. }
  22699. else {
  22700. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22701. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22702. }
  22703. this._computeTransformMatrices(this._transformMatrices, null);
  22704. }
  22705. this._isDirty = false;
  22706. this._scene._activeBones += this.bones.length;
  22707. };
  22708. Skeleton.prototype.getAnimatables = function () {
  22709. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22710. this._animatables = [];
  22711. for (var index = 0; index < this.bones.length; index++) {
  22712. this._animatables.push(this.bones[index]);
  22713. }
  22714. }
  22715. return this._animatables;
  22716. };
  22717. Skeleton.prototype.clone = function (name, id) {
  22718. var result = new Skeleton(name, id || name, this._scene);
  22719. for (var index = 0; index < this.bones.length; index++) {
  22720. var source = this.bones[index];
  22721. var parentBone = null;
  22722. if (source.getParent()) {
  22723. var parentIndex = this.bones.indexOf(source.getParent());
  22724. parentBone = result.bones[parentIndex];
  22725. }
  22726. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  22727. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22728. }
  22729. return result;
  22730. };
  22731. Skeleton.prototype.dispose = function () {
  22732. this._meshesWithPoseMatrix = [];
  22733. // Animations
  22734. this.getScene().stopAnimation(this);
  22735. // Remove from scene
  22736. this.getScene().removeSkeleton(this);
  22737. };
  22738. Skeleton.prototype.serialize = function () {
  22739. var serializationObject = {};
  22740. serializationObject.name = this.name;
  22741. serializationObject.id = this.id;
  22742. serializationObject.bones = [];
  22743. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  22744. for (var index = 0; index < this.bones.length; index++) {
  22745. var bone = this.bones[index];
  22746. var serializedBone = {
  22747. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  22748. name: bone.name,
  22749. matrix: bone.getLocalMatrix().toArray(),
  22750. rest: bone.getRestPose().toArray()
  22751. };
  22752. serializationObject.bones.push(serializedBone);
  22753. if (bone.length) {
  22754. serializedBone.length = bone.length;
  22755. }
  22756. if (bone.animations && bone.animations.length > 0) {
  22757. serializedBone.animation = bone.animations[0].serialize();
  22758. }
  22759. serializationObject.ranges = [];
  22760. for (var name in this._ranges) {
  22761. var range = {};
  22762. range.name = name;
  22763. range.from = this._ranges[name].from;
  22764. range.to = this._ranges[name].to;
  22765. serializationObject.ranges.push(range);
  22766. }
  22767. }
  22768. return serializationObject;
  22769. };
  22770. Skeleton.Parse = function (parsedSkeleton, scene) {
  22771. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  22772. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  22773. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  22774. var parsedBone = parsedSkeleton.bones[index];
  22775. var parentBone = null;
  22776. if (parsedBone.parentBoneIndex > -1) {
  22777. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  22778. }
  22779. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  22780. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  22781. if (parsedBone.length) {
  22782. bone.length = parsedBone.length;
  22783. }
  22784. if (parsedBone.animation) {
  22785. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  22786. }
  22787. }
  22788. // placed after bones, so createAnimationRange can cascade down
  22789. if (parsedSkeleton.ranges) {
  22790. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  22791. var data = parsedSkeleton.ranges[index];
  22792. skeleton.createAnimationRange(data.name, data.from, data.to);
  22793. }
  22794. }
  22795. return skeleton;
  22796. };
  22797. return Skeleton;
  22798. })();
  22799. BABYLON.Skeleton = Skeleton;
  22800. })(BABYLON || (BABYLON = {}));
  22801. var BABYLON;
  22802. (function (BABYLON) {
  22803. var PostProcess = (function () {
  22804. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22805. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22806. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22807. this.name = name;
  22808. this.width = -1;
  22809. this.height = -1;
  22810. this._reusable = false;
  22811. this._textures = new BABYLON.SmartArray(2);
  22812. this._currentRenderTextureInd = 0;
  22813. if (camera != null) {
  22814. this._camera = camera;
  22815. this._scene = camera.getScene();
  22816. camera.attachPostProcess(this);
  22817. this._engine = this._scene.getEngine();
  22818. }
  22819. else {
  22820. this._engine = engine;
  22821. }
  22822. this._renderRatio = ratio;
  22823. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22824. this._reusable = reusable || false;
  22825. this._textureType = textureType;
  22826. this._samplers = samplers || [];
  22827. this._samplers.push("textureSampler");
  22828. this._fragmentUrl = fragmentUrl;
  22829. this._parameters = parameters || [];
  22830. this.updateEffect(defines);
  22831. }
  22832. PostProcess.prototype.updateEffect = function (defines) {
  22833. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22834. };
  22835. PostProcess.prototype.isReusable = function () {
  22836. return this._reusable;
  22837. };
  22838. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22839. camera = camera || this._camera;
  22840. var scene = camera.getScene();
  22841. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22842. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22843. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22844. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22845. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22846. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22847. if (this._textures.length > 0) {
  22848. for (var i = 0; i < this._textures.length; i++) {
  22849. this._engine._releaseTexture(this._textures.data[i]);
  22850. }
  22851. this._textures.reset();
  22852. }
  22853. this.width = desiredWidth;
  22854. this.height = desiredHeight;
  22855. 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 }));
  22856. if (this._reusable) {
  22857. 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 }));
  22858. }
  22859. if (this.onSizeChanged) {
  22860. this.onSizeChanged();
  22861. }
  22862. }
  22863. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22864. if (this.onActivate) {
  22865. this.onActivate(camera);
  22866. }
  22867. // Clear
  22868. if (this.clearColor) {
  22869. this._engine.clear(this.clearColor, true, true);
  22870. }
  22871. else {
  22872. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22873. }
  22874. if (this._reusable) {
  22875. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22876. }
  22877. };
  22878. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22879. get: function () {
  22880. return this._effect.isSupported;
  22881. },
  22882. enumerable: true,
  22883. configurable: true
  22884. });
  22885. PostProcess.prototype.apply = function () {
  22886. // Check
  22887. if (!this._effect.isReady())
  22888. return null;
  22889. // States
  22890. this._engine.enableEffect(this._effect);
  22891. this._engine.setState(false);
  22892. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22893. this._engine.setDepthBuffer(false);
  22894. this._engine.setDepthWrite(false);
  22895. // Texture
  22896. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22897. // Parameters
  22898. if (this.onApply) {
  22899. this.onApply(this._effect);
  22900. }
  22901. return this._effect;
  22902. };
  22903. PostProcess.prototype.dispose = function (camera) {
  22904. camera = camera || this._camera;
  22905. if (this._textures.length > 0) {
  22906. for (var i = 0; i < this._textures.length; i++) {
  22907. this._engine._releaseTexture(this._textures.data[i]);
  22908. }
  22909. this._textures.reset();
  22910. }
  22911. if (!camera) {
  22912. return;
  22913. }
  22914. camera.detachPostProcess(this);
  22915. var index = camera._postProcesses.indexOf(this);
  22916. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22917. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22918. }
  22919. };
  22920. return PostProcess;
  22921. })();
  22922. BABYLON.PostProcess = PostProcess;
  22923. })(BABYLON || (BABYLON = {}));
  22924. var BABYLON;
  22925. (function (BABYLON) {
  22926. var PostProcessManager = (function () {
  22927. function PostProcessManager(scene) {
  22928. this._vertexDeclaration = [2];
  22929. this._vertexStrideSize = 2 * 4;
  22930. this._scene = scene;
  22931. }
  22932. PostProcessManager.prototype._prepareBuffers = function () {
  22933. if (this._vertexBuffer) {
  22934. return;
  22935. }
  22936. // VBO
  22937. var vertices = [];
  22938. vertices.push(1, 1);
  22939. vertices.push(-1, 1);
  22940. vertices.push(-1, -1);
  22941. vertices.push(1, -1);
  22942. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22943. // Indices
  22944. var indices = [];
  22945. indices.push(0);
  22946. indices.push(1);
  22947. indices.push(2);
  22948. indices.push(0);
  22949. indices.push(2);
  22950. indices.push(3);
  22951. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22952. };
  22953. // Methods
  22954. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22955. var postProcesses = this._scene.activeCamera._postProcesses;
  22956. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22957. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22958. return false;
  22959. }
  22960. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22961. return true;
  22962. };
  22963. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22964. var engine = this._scene.getEngine();
  22965. for (var index = 0; index < postProcesses.length; index++) {
  22966. if (index < postProcesses.length - 1) {
  22967. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22968. }
  22969. else {
  22970. if (targetTexture) {
  22971. engine.bindFramebuffer(targetTexture);
  22972. }
  22973. else {
  22974. engine.restoreDefaultFramebuffer();
  22975. }
  22976. }
  22977. var pp = postProcesses[index];
  22978. var effect = pp.apply();
  22979. if (effect) {
  22980. if (pp.onBeforeRender) {
  22981. pp.onBeforeRender(effect);
  22982. }
  22983. // VBOs
  22984. this._prepareBuffers();
  22985. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22986. // Draw order
  22987. engine.draw(true, 0, 6);
  22988. if (pp.onAfterRender) {
  22989. pp.onAfterRender(effect);
  22990. }
  22991. }
  22992. }
  22993. // Restore depth buffer
  22994. engine.setDepthBuffer(true);
  22995. engine.setDepthWrite(true);
  22996. };
  22997. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22998. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22999. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23000. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23001. return;
  23002. }
  23003. var engine = this._scene.getEngine();
  23004. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23005. if (index < postProcessesTakenIndices.length - 1) {
  23006. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23007. }
  23008. else {
  23009. if (targetTexture) {
  23010. engine.bindFramebuffer(targetTexture, faceIndex);
  23011. }
  23012. else {
  23013. engine.restoreDefaultFramebuffer();
  23014. }
  23015. }
  23016. if (doNotPresent) {
  23017. break;
  23018. }
  23019. var pp = postProcesses[postProcessesTakenIndices[index]];
  23020. var effect = pp.apply();
  23021. if (effect) {
  23022. if (pp.onBeforeRender) {
  23023. pp.onBeforeRender(effect);
  23024. }
  23025. // VBOs
  23026. this._prepareBuffers();
  23027. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23028. // Draw order
  23029. engine.draw(true, 0, 6);
  23030. if (pp.onAfterRender) {
  23031. pp.onAfterRender(effect);
  23032. }
  23033. }
  23034. }
  23035. // Restore depth buffer
  23036. engine.setDepthBuffer(true);
  23037. engine.setDepthWrite(true);
  23038. };
  23039. PostProcessManager.prototype.dispose = function () {
  23040. if (this._vertexBuffer) {
  23041. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23042. this._vertexBuffer = null;
  23043. }
  23044. if (this._indexBuffer) {
  23045. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23046. this._indexBuffer = null;
  23047. }
  23048. };
  23049. return PostProcessManager;
  23050. })();
  23051. BABYLON.PostProcessManager = PostProcessManager;
  23052. })(BABYLON || (BABYLON = {}));
  23053. var BABYLON;
  23054. (function (BABYLON) {
  23055. var PassPostProcess = (function (_super) {
  23056. __extends(PassPostProcess, _super);
  23057. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23058. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23059. }
  23060. return PassPostProcess;
  23061. })(BABYLON.PostProcess);
  23062. BABYLON.PassPostProcess = PassPostProcess;
  23063. })(BABYLON || (BABYLON = {}));
  23064. var BABYLON;
  23065. (function (BABYLON) {
  23066. var PhysicsEngine = (function () {
  23067. function PhysicsEngine(plugin) {
  23068. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23069. }
  23070. PhysicsEngine.prototype._initialize = function (gravity) {
  23071. this._currentPlugin.initialize();
  23072. this._setGravity(gravity);
  23073. };
  23074. PhysicsEngine.prototype._runOneStep = function (delta) {
  23075. if (delta > 0.1) {
  23076. delta = 0.1;
  23077. }
  23078. else if (delta <= 0) {
  23079. delta = 1.0 / 60.0;
  23080. }
  23081. this._currentPlugin.runOneStep(delta);
  23082. };
  23083. PhysicsEngine.prototype._setGravity = function (gravity) {
  23084. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23085. this._currentPlugin.setGravity(this.gravity);
  23086. };
  23087. PhysicsEngine.prototype._getGravity = function () {
  23088. return this._currentPlugin.getGravity();
  23089. };
  23090. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23091. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23092. };
  23093. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23094. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23095. };
  23096. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23097. this._currentPlugin.unregisterMesh(mesh);
  23098. };
  23099. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23100. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23101. };
  23102. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23103. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23104. };
  23105. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23106. this._currentPlugin.updateBodyPosition(mesh);
  23107. };
  23108. PhysicsEngine.prototype.dispose = function () {
  23109. this._currentPlugin.dispose();
  23110. };
  23111. PhysicsEngine.prototype.isSupported = function () {
  23112. return this._currentPlugin.isSupported();
  23113. };
  23114. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23115. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23116. };
  23117. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23118. return this._currentPlugin.name;
  23119. };
  23120. // Statics
  23121. PhysicsEngine.NoImpostor = 0;
  23122. PhysicsEngine.SphereImpostor = 1;
  23123. PhysicsEngine.BoxImpostor = 2;
  23124. PhysicsEngine.PlaneImpostor = 3;
  23125. PhysicsEngine.MeshImpostor = 4;
  23126. PhysicsEngine.CapsuleImpostor = 5;
  23127. PhysicsEngine.ConeImpostor = 6;
  23128. PhysicsEngine.CylinderImpostor = 7;
  23129. PhysicsEngine.ConvexHullImpostor = 8;
  23130. PhysicsEngine.HeightmapImpostor = 9;
  23131. PhysicsEngine.Epsilon = 0.001;
  23132. return PhysicsEngine;
  23133. })();
  23134. BABYLON.PhysicsEngine = PhysicsEngine;
  23135. })(BABYLON || (BABYLON = {}));
  23136. var BABYLON;
  23137. (function (BABYLON) {
  23138. var VertexData = (function () {
  23139. function VertexData() {
  23140. }
  23141. VertexData.prototype.set = function (data, kind) {
  23142. switch (kind) {
  23143. case BABYLON.VertexBuffer.PositionKind:
  23144. this.positions = data;
  23145. break;
  23146. case BABYLON.VertexBuffer.NormalKind:
  23147. this.normals = data;
  23148. break;
  23149. case BABYLON.VertexBuffer.UVKind:
  23150. this.uvs = data;
  23151. break;
  23152. case BABYLON.VertexBuffer.UV2Kind:
  23153. this.uvs2 = data;
  23154. break;
  23155. case BABYLON.VertexBuffer.UV3Kind:
  23156. this.uvs3 = data;
  23157. break;
  23158. case BABYLON.VertexBuffer.UV4Kind:
  23159. this.uvs4 = data;
  23160. break;
  23161. case BABYLON.VertexBuffer.UV5Kind:
  23162. this.uvs5 = data;
  23163. break;
  23164. case BABYLON.VertexBuffer.UV6Kind:
  23165. this.uvs6 = data;
  23166. break;
  23167. case BABYLON.VertexBuffer.ColorKind:
  23168. this.colors = data;
  23169. break;
  23170. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23171. this.matricesIndices = data;
  23172. break;
  23173. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23174. this.matricesWeights = data;
  23175. break;
  23176. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23177. this.matricesIndicesExtra = data;
  23178. break;
  23179. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23180. this.matricesWeightsExtra = data;
  23181. break;
  23182. }
  23183. };
  23184. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23185. this._applyTo(mesh, updatable);
  23186. };
  23187. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23188. this._applyTo(geometry, updatable);
  23189. };
  23190. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23191. this._update(mesh);
  23192. };
  23193. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23194. this._update(geometry);
  23195. };
  23196. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23197. if (this.positions) {
  23198. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23199. }
  23200. if (this.normals) {
  23201. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23202. }
  23203. if (this.uvs) {
  23204. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23205. }
  23206. if (this.uvs2) {
  23207. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23208. }
  23209. if (this.uvs3) {
  23210. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23211. }
  23212. if (this.uvs4) {
  23213. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23214. }
  23215. if (this.uvs5) {
  23216. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23217. }
  23218. if (this.uvs6) {
  23219. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23220. }
  23221. if (this.colors) {
  23222. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23223. }
  23224. if (this.matricesIndices) {
  23225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23226. }
  23227. if (this.matricesWeights) {
  23228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23229. }
  23230. if (this.matricesIndicesExtra) {
  23231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23232. }
  23233. if (this.matricesWeightsExtra) {
  23234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23235. }
  23236. if (this.indices) {
  23237. meshOrGeometry.setIndices(this.indices);
  23238. }
  23239. };
  23240. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23241. if (this.positions) {
  23242. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23243. }
  23244. if (this.normals) {
  23245. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23246. }
  23247. if (this.uvs) {
  23248. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23249. }
  23250. if (this.uvs2) {
  23251. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23252. }
  23253. if (this.uvs3) {
  23254. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23255. }
  23256. if (this.uvs4) {
  23257. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23258. }
  23259. if (this.uvs5) {
  23260. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23261. }
  23262. if (this.uvs6) {
  23263. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23264. }
  23265. if (this.colors) {
  23266. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23267. }
  23268. if (this.matricesIndices) {
  23269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23270. }
  23271. if (this.matricesWeights) {
  23272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23273. }
  23274. if (this.matricesIndicesExtra) {
  23275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23276. }
  23277. if (this.matricesWeightsExtra) {
  23278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23279. }
  23280. if (this.indices) {
  23281. meshOrGeometry.setIndices(this.indices);
  23282. }
  23283. };
  23284. VertexData.prototype.transform = function (matrix) {
  23285. var transformed = BABYLON.Vector3.Zero();
  23286. var index;
  23287. if (this.positions) {
  23288. var position = BABYLON.Vector3.Zero();
  23289. for (index = 0; index < this.positions.length; index += 3) {
  23290. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23291. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23292. this.positions[index] = transformed.x;
  23293. this.positions[index + 1] = transformed.y;
  23294. this.positions[index + 2] = transformed.z;
  23295. }
  23296. }
  23297. if (this.normals) {
  23298. var normal = BABYLON.Vector3.Zero();
  23299. for (index = 0; index < this.normals.length; index += 3) {
  23300. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23301. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23302. this.normals[index] = transformed.x;
  23303. this.normals[index + 1] = transformed.y;
  23304. this.normals[index + 2] = transformed.z;
  23305. }
  23306. }
  23307. };
  23308. VertexData.prototype.merge = function (other) {
  23309. if (other.indices) {
  23310. if (!this.indices) {
  23311. this.indices = [];
  23312. }
  23313. var offset = this.positions ? this.positions.length / 3 : 0;
  23314. for (var index = 0; index < other.indices.length; index++) {
  23315. //TODO check type - if Int32Array!
  23316. this.indices.push(other.indices[index] + offset);
  23317. }
  23318. }
  23319. this.positions = this._mergeElement(this.positions, other.positions);
  23320. this.normals = this._mergeElement(this.normals, other.normals);
  23321. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23322. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23323. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23324. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23325. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23326. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23327. this.colors = this._mergeElement(this.colors, other.colors);
  23328. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23329. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23330. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23331. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23332. };
  23333. VertexData.prototype._mergeElement = function (source, other) {
  23334. if (!other)
  23335. return source;
  23336. if (!source)
  23337. return other;
  23338. var len = other.length + source.length;
  23339. var isSrcTypedArray = source instanceof Float32Array;
  23340. var isOthTypedArray = other instanceof Float32Array;
  23341. // use non-loop method when the source is Float32Array
  23342. if (isSrcTypedArray) {
  23343. var ret32 = new Float32Array(len);
  23344. ret32.set(source);
  23345. ret32.set(other, source.length);
  23346. return ret32;
  23347. }
  23348. else if (!isOthTypedArray) {
  23349. return source.concat(other);
  23350. }
  23351. else {
  23352. var ret = source.slice(0); // copy source to a separate array
  23353. for (var i = 0, len = other.length; i < len; i++) {
  23354. ret.push(other[i]);
  23355. }
  23356. return ret;
  23357. }
  23358. };
  23359. VertexData.prototype.serialize = function () {
  23360. var serializationObject = this.serialize();
  23361. if (this.positions) {
  23362. serializationObject.positions = this.positions;
  23363. }
  23364. if (this.normals) {
  23365. serializationObject.normals = this.normals;
  23366. }
  23367. if (this.uvs) {
  23368. serializationObject.uvs = this.uvs;
  23369. }
  23370. if (this.uvs2) {
  23371. serializationObject.uvs2 = this.uvs2;
  23372. }
  23373. if (this.uvs3) {
  23374. serializationObject.uvs3 = this.uvs3;
  23375. }
  23376. if (this.uvs4) {
  23377. serializationObject.uvs4 = this.uvs4;
  23378. }
  23379. if (this.uvs5) {
  23380. serializationObject.uvs5 = this.uvs5;
  23381. }
  23382. if (this.uvs6) {
  23383. serializationObject.uvs6 = this.uvs6;
  23384. }
  23385. if (this.colors) {
  23386. serializationObject.colors = this.colors;
  23387. }
  23388. if (this.matricesIndices) {
  23389. serializationObject.matricesIndices = this.matricesIndices;
  23390. serializationObject.matricesIndices._isExpanded = true;
  23391. }
  23392. if (this.matricesWeights) {
  23393. serializationObject.matricesWeights = this.matricesWeights;
  23394. }
  23395. if (this.matricesIndicesExtra) {
  23396. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23397. serializationObject.matricesIndicesExtra._isExpanded = true;
  23398. }
  23399. if (this.matricesWeightsExtra) {
  23400. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23401. }
  23402. serializationObject.indices = this.indices;
  23403. return serializationObject;
  23404. };
  23405. // Statics
  23406. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23407. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23408. };
  23409. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23410. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23411. };
  23412. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23413. var result = new VertexData();
  23414. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23415. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23416. }
  23417. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23418. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23419. }
  23420. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23421. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23422. }
  23423. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23424. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23425. }
  23426. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23427. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23428. }
  23429. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23430. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23431. }
  23432. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23433. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23434. }
  23435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23436. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23437. }
  23438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23439. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23440. }
  23441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23442. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23443. }
  23444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23445. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23446. }
  23447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23448. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23449. }
  23450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23451. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23452. }
  23453. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23454. return result;
  23455. };
  23456. VertexData.CreateRibbon = function (options) {
  23457. var pathArray = options.pathArray;
  23458. var closeArray = options.closeArray || false;
  23459. var closePath = options.closePath || false;
  23460. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23461. var offset = options.offset || defaultOffset;
  23462. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23463. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23464. var positions = [];
  23465. var indices = [];
  23466. var normals = [];
  23467. var uvs = [];
  23468. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23469. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23470. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23471. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23472. var minlg; // minimal length among all paths from pathArray
  23473. var lg = []; // array of path lengths : nb of vertex per path
  23474. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23475. var p; // path iterator
  23476. var i; // point iterator
  23477. var j; // point iterator
  23478. // if single path in pathArray
  23479. if (pathArray.length < 2) {
  23480. var ar1 = [];
  23481. var ar2 = [];
  23482. for (i = 0; i < pathArray[0].length - offset; i++) {
  23483. ar1.push(pathArray[0][i]);
  23484. ar2.push(pathArray[0][i + offset]);
  23485. }
  23486. pathArray = [ar1, ar2];
  23487. }
  23488. // positions and horizontal distances (u)
  23489. var idc = 0;
  23490. var closePathCorr = (closePath) ? 1 : 0;
  23491. var path;
  23492. var l;
  23493. minlg = pathArray[0].length;
  23494. var vectlg;
  23495. var dist;
  23496. for (p = 0; p < pathArray.length; p++) {
  23497. uTotalDistance[p] = 0;
  23498. us[p] = [0];
  23499. path = pathArray[p];
  23500. l = path.length;
  23501. minlg = (minlg < l) ? minlg : l;
  23502. j = 0;
  23503. while (j < l) {
  23504. positions.push(path[j].x, path[j].y, path[j].z);
  23505. if (j > 0) {
  23506. vectlg = path[j].subtract(path[j - 1]).length();
  23507. dist = vectlg + uTotalDistance[p];
  23508. us[p].push(dist);
  23509. uTotalDistance[p] = dist;
  23510. }
  23511. j++;
  23512. }
  23513. if (closePath) {
  23514. j--;
  23515. positions.push(path[0].x, path[0].y, path[0].z);
  23516. vectlg = path[j].subtract(path[0]).length();
  23517. dist = vectlg + uTotalDistance[p];
  23518. us[p].push(dist);
  23519. uTotalDistance[p] = dist;
  23520. }
  23521. lg[p] = l + closePathCorr;
  23522. idx[p] = idc;
  23523. idc += (l + closePathCorr);
  23524. }
  23525. // vertical distances (v)
  23526. var path1;
  23527. var path2;
  23528. var vertex1;
  23529. var vertex2;
  23530. for (i = 0; i < minlg + closePathCorr; i++) {
  23531. vTotalDistance[i] = 0;
  23532. vs[i] = [0];
  23533. for (p = 0; p < pathArray.length - 1; p++) {
  23534. path1 = pathArray[p];
  23535. path2 = pathArray[p + 1];
  23536. if (i === minlg) {
  23537. vertex1 = path1[0];
  23538. vertex2 = path2[0];
  23539. }
  23540. else {
  23541. vertex1 = path1[i];
  23542. vertex2 = path2[i];
  23543. }
  23544. vectlg = vertex2.subtract(vertex1).length();
  23545. dist = vectlg + vTotalDistance[i];
  23546. vs[i].push(dist);
  23547. vTotalDistance[i] = dist;
  23548. }
  23549. if (closeArray) {
  23550. path1 = pathArray[p];
  23551. path2 = pathArray[0];
  23552. if (i === minlg) {
  23553. vertex2 = path2[0];
  23554. }
  23555. vectlg = vertex2.subtract(vertex1).length();
  23556. dist = vectlg + vTotalDistance[i];
  23557. vTotalDistance[i] = dist;
  23558. }
  23559. }
  23560. // uvs
  23561. var u;
  23562. var v;
  23563. for (p = 0; p < pathArray.length; p++) {
  23564. for (i = 0; i < minlg + closePathCorr; i++) {
  23565. u = us[p][i] / uTotalDistance[p];
  23566. v = vs[i][p] / vTotalDistance[i];
  23567. uvs.push(u, v);
  23568. }
  23569. }
  23570. // indices
  23571. p = 0; // path index
  23572. var pi = 0; // positions array index
  23573. var l1 = lg[p] - 1; // path1 length
  23574. var l2 = lg[p + 1] - 1; // path2 length
  23575. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23576. var shft = idx[1] - idx[0]; // shift
  23577. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23578. while (pi <= min && p < path1nb) {
  23579. // 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
  23580. indices.push(pi, pi + shft, pi + 1);
  23581. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23582. pi += 1;
  23583. if (pi === min) {
  23584. p++;
  23585. if (p === lg.length - 1) {
  23586. shft = idx[0] - idx[p];
  23587. l1 = lg[p] - 1;
  23588. l2 = lg[0] - 1;
  23589. }
  23590. else {
  23591. shft = idx[p + 1] - idx[p];
  23592. l1 = lg[p] - 1;
  23593. l2 = lg[p + 1] - 1;
  23594. }
  23595. pi = idx[p];
  23596. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23597. }
  23598. }
  23599. // normals
  23600. VertexData.ComputeNormals(positions, indices, normals);
  23601. if (closePath) {
  23602. var indexFirst = 0;
  23603. var indexLast = 0;
  23604. for (p = 0; p < pathArray.length; p++) {
  23605. indexFirst = idx[p] * 3;
  23606. if (p + 1 < pathArray.length) {
  23607. indexLast = (idx[p + 1] - 1) * 3;
  23608. }
  23609. else {
  23610. indexLast = normals.length - 3;
  23611. }
  23612. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23613. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23614. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23615. normals[indexLast] = normals[indexFirst];
  23616. normals[indexLast + 1] = normals[indexFirst + 1];
  23617. normals[indexLast + 2] = normals[indexFirst + 2];
  23618. }
  23619. }
  23620. // sides
  23621. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23622. // Result
  23623. var vertexData = new VertexData();
  23624. vertexData.indices = indices;
  23625. vertexData.positions = positions;
  23626. vertexData.normals = normals;
  23627. vertexData.uvs = uvs;
  23628. if (closePath) {
  23629. vertexData._idx = idx;
  23630. }
  23631. return vertexData;
  23632. };
  23633. VertexData.CreateBox = function (options) {
  23634. var normalsSource = [
  23635. new BABYLON.Vector3(0, 0, 1),
  23636. new BABYLON.Vector3(0, 0, -1),
  23637. new BABYLON.Vector3(1, 0, 0),
  23638. new BABYLON.Vector3(-1, 0, 0),
  23639. new BABYLON.Vector3(0, 1, 0),
  23640. new BABYLON.Vector3(0, -1, 0)
  23641. ];
  23642. var indices = [];
  23643. var positions = [];
  23644. var normals = [];
  23645. var uvs = [];
  23646. var width = options.width || options.size || 1;
  23647. var height = options.height || options.size || 1;
  23648. var depth = options.depth || options.size || 1;
  23649. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23650. var faceUV = options.faceUV || new Array(6);
  23651. var faceColors = options.faceColors;
  23652. var colors = [];
  23653. // default face colors and UV if undefined
  23654. for (var f = 0; f < 6; f++) {
  23655. if (faceUV[f] === undefined) {
  23656. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23657. }
  23658. if (faceColors && faceColors[f] === undefined) {
  23659. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23660. }
  23661. }
  23662. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23663. // Create each face in turn.
  23664. for (var index = 0; index < normalsSource.length; index++) {
  23665. var normal = normalsSource[index];
  23666. // Get two vectors perpendicular to the face normal and to each other.
  23667. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23668. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23669. // Six indices (two triangles) per face.
  23670. var verticesLength = positions.length / 3;
  23671. indices.push(verticesLength);
  23672. indices.push(verticesLength + 1);
  23673. indices.push(verticesLength + 2);
  23674. indices.push(verticesLength);
  23675. indices.push(verticesLength + 2);
  23676. indices.push(verticesLength + 3);
  23677. // Four vertices per face.
  23678. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23679. positions.push(vertex.x, vertex.y, vertex.z);
  23680. normals.push(normal.x, normal.y, normal.z);
  23681. uvs.push(faceUV[index].z, faceUV[index].w);
  23682. if (faceColors) {
  23683. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23684. }
  23685. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23686. positions.push(vertex.x, vertex.y, vertex.z);
  23687. normals.push(normal.x, normal.y, normal.z);
  23688. uvs.push(faceUV[index].x, faceUV[index].w);
  23689. if (faceColors) {
  23690. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23691. }
  23692. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23693. positions.push(vertex.x, vertex.y, vertex.z);
  23694. normals.push(normal.x, normal.y, normal.z);
  23695. uvs.push(faceUV[index].x, faceUV[index].y);
  23696. if (faceColors) {
  23697. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23698. }
  23699. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23700. positions.push(vertex.x, vertex.y, vertex.z);
  23701. normals.push(normal.x, normal.y, normal.z);
  23702. uvs.push(faceUV[index].z, faceUV[index].y);
  23703. if (faceColors) {
  23704. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23705. }
  23706. }
  23707. // sides
  23708. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23709. // Result
  23710. var vertexData = new VertexData();
  23711. vertexData.indices = indices;
  23712. vertexData.positions = positions;
  23713. vertexData.normals = normals;
  23714. vertexData.uvs = uvs;
  23715. if (faceColors) {
  23716. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23717. vertexData.colors = totalColors;
  23718. }
  23719. return vertexData;
  23720. };
  23721. VertexData.CreateSphere = function (options) {
  23722. var segments = options.segments || 32;
  23723. var diameterX = options.diameterX || options.diameter || 1;
  23724. var diameterY = options.diameterY || options.diameter || 1;
  23725. var diameterZ = options.diameterZ || options.diameter || 1;
  23726. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23727. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23728. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23729. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23730. var totalZRotationSteps = 2 + segments;
  23731. var totalYRotationSteps = 2 * totalZRotationSteps;
  23732. var indices = [];
  23733. var positions = [];
  23734. var normals = [];
  23735. var uvs = [];
  23736. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23737. var normalizedZ = zRotationStep / totalZRotationSteps;
  23738. var angleZ = normalizedZ * Math.PI * slice;
  23739. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23740. var normalizedY = yRotationStep / totalYRotationSteps;
  23741. var angleY = normalizedY * Math.PI * 2 * arc;
  23742. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23743. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23744. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23745. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23746. var vertex = complete.multiply(radius);
  23747. var normal = complete.divide(radius).normalize();
  23748. positions.push(vertex.x, vertex.y, vertex.z);
  23749. normals.push(normal.x, normal.y, normal.z);
  23750. uvs.push(normalizedY, normalizedZ);
  23751. }
  23752. if (zRotationStep > 0) {
  23753. var verticesCount = positions.length / 3;
  23754. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23755. indices.push((firstIndex));
  23756. indices.push((firstIndex + 1));
  23757. indices.push(firstIndex + totalYRotationSteps + 1);
  23758. indices.push((firstIndex + totalYRotationSteps + 1));
  23759. indices.push((firstIndex + 1));
  23760. indices.push((firstIndex + totalYRotationSteps + 2));
  23761. }
  23762. }
  23763. }
  23764. // Sides
  23765. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23766. // Result
  23767. var vertexData = new VertexData();
  23768. vertexData.indices = indices;
  23769. vertexData.positions = positions;
  23770. vertexData.normals = normals;
  23771. vertexData.uvs = uvs;
  23772. return vertexData;
  23773. };
  23774. // Cylinder and cone
  23775. VertexData.CreateCylinder = function (options) {
  23776. var height = options.height || 2;
  23777. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23778. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23779. var tessellation = options.tessellation || 24;
  23780. var subdivisions = options.subdivisions || 1;
  23781. var hasRings = options.hasRings;
  23782. var enclose = options.enclose;
  23783. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23784. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23785. var faceUV = options.faceUV || new Array(3);
  23786. var faceColors = options.faceColors;
  23787. // default face colors and UV if undefined
  23788. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  23789. var ringNb = (hasRings) ? subdivisions : 1;
  23790. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  23791. var f;
  23792. for (f = 0; f < surfaceNb; f++) {
  23793. if (faceColors && faceColors[f] === undefined) {
  23794. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23795. }
  23796. }
  23797. for (f = 0; f < surfaceNb; f++) {
  23798. if (faceUV && faceUV[f] === undefined) {
  23799. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23800. }
  23801. }
  23802. var indices = [];
  23803. var positions = [];
  23804. var normals = [];
  23805. var uvs = [];
  23806. var colors = [];
  23807. var angle_step = Math.PI * 2 * arc / tessellation;
  23808. var angle;
  23809. var h;
  23810. var radius;
  23811. var tan = (diameterBottom - diameterTop) / 2 / height;
  23812. var ringVertex = BABYLON.Vector3.Zero();
  23813. var ringNormal = BABYLON.Vector3.Zero();
  23814. var ringFirstVertex = BABYLON.Vector3.Zero();
  23815. var ringFirstNormal = BABYLON.Vector3.Zero();
  23816. var quadNormal = BABYLON.Vector3.Zero();
  23817. var Y = BABYLON.Axis.Y;
  23818. // positions, normals, uvs
  23819. var i;
  23820. var j;
  23821. var r;
  23822. var ringIdx = 1;
  23823. var s = 1; // surface index
  23824. var cs = 0;
  23825. var v = 0;
  23826. for (i = 0; i <= subdivisions; i++) {
  23827. h = i / subdivisions;
  23828. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23829. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23830. for (r = 0; r < ringIdx; r++) {
  23831. if (hasRings) {
  23832. s += r;
  23833. }
  23834. if (enclose) {
  23835. s += 2 * r;
  23836. }
  23837. for (j = 0; j <= tessellation; j++) {
  23838. angle = j * angle_step;
  23839. // position
  23840. ringVertex.x = Math.cos(-angle) * radius;
  23841. ringVertex.y = -height / 2 + h * height;
  23842. ringVertex.z = Math.sin(-angle) * radius;
  23843. // normal
  23844. if (diameterTop === 0 && i === subdivisions) {
  23845. // if no top cap, reuse former normals
  23846. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23847. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23848. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23849. }
  23850. else {
  23851. ringNormal.x = ringVertex.x;
  23852. ringNormal.z = ringVertex.z;
  23853. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23854. ringNormal.normalize();
  23855. }
  23856. // keep first ring vertex values for enclose
  23857. if (j === 0) {
  23858. ringFirstVertex.copyFrom(ringVertex);
  23859. ringFirstNormal.copyFrom(ringNormal);
  23860. }
  23861. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23862. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23863. if (hasRings) {
  23864. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  23865. }
  23866. else {
  23867. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  23868. }
  23869. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  23870. if (faceColors) {
  23871. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  23872. }
  23873. }
  23874. // if enclose, add four vertices and their dedicated normals
  23875. if (arc !== 1 && enclose) {
  23876. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23877. positions.push(0, ringVertex.y, 0);
  23878. positions.push(0, ringVertex.y, 0);
  23879. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  23880. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  23881. quadNormal.normalize();
  23882. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23883. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  23884. quadNormal.normalize();
  23885. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  23886. if (hasRings) {
  23887. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  23888. }
  23889. else {
  23890. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  23891. }
  23892. uvs.push(faceUV[s + 1].x, v);
  23893. uvs.push(faceUV[s + 1].z, v);
  23894. if (hasRings) {
  23895. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  23896. }
  23897. else {
  23898. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  23899. }
  23900. uvs.push(faceUV[s + 2].x, v);
  23901. uvs.push(faceUV[s + 2].z, v);
  23902. if (faceColors) {
  23903. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23904. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  23905. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23906. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  23907. }
  23908. }
  23909. if (cs !== s) {
  23910. cs = s;
  23911. }
  23912. }
  23913. }
  23914. // indices
  23915. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  23916. var s;
  23917. i = 0;
  23918. for (s = 0; s < subdivisions; s++) {
  23919. for (j = 0; j < tessellation; j++) {
  23920. var i0 = i * (e + 1) + j;
  23921. var i1 = (i + 1) * (e + 1) + j;
  23922. var i2 = i * (e + 1) + (j + 1);
  23923. var i3 = (i + 1) * (e + 1) + (j + 1);
  23924. indices.push(i0, i1, i2);
  23925. indices.push(i3, i2, i1);
  23926. }
  23927. if (arc !== 1 && enclose) {
  23928. indices.push(i0 + 2, i1 + 2, i2 + 2);
  23929. indices.push(i3 + 2, i2 + 2, i1 + 2);
  23930. indices.push(i0 + 4, i1 + 4, i2 + 4);
  23931. indices.push(i3 + 4, i2 + 4, i1 + 4);
  23932. }
  23933. i = (hasRings) ? (i + 2) : (i + 1);
  23934. }
  23935. // Caps
  23936. var createCylinderCap = function (isTop) {
  23937. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23938. if (radius === 0) {
  23939. return;
  23940. }
  23941. // Cap positions, normals & uvs
  23942. var angle;
  23943. var circleVector;
  23944. var i;
  23945. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  23946. var c;
  23947. if (faceColors) {
  23948. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  23949. }
  23950. // cap center
  23951. var vbase = positions.length / 3;
  23952. var offset = isTop ? height / 2 : -height / 2;
  23953. var center = new BABYLON.Vector3(0, offset, 0);
  23954. positions.push(center.x, center.y, center.z);
  23955. normals.push(0, isTop ? 1 : -1, 0);
  23956. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23957. if (faceColors) {
  23958. colors.push(c.r, c.g, c.b, c.a);
  23959. }
  23960. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23961. for (i = 0; i <= tessellation; i++) {
  23962. angle = Math.PI * 2 * i * arc / tessellation;
  23963. var cos = Math.cos(-angle);
  23964. var sin = Math.sin(-angle);
  23965. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23966. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23967. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23968. normals.push(0, isTop ? 1 : -1, 0);
  23969. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23970. if (faceColors) {
  23971. colors.push(c.r, c.g, c.b, c.a);
  23972. }
  23973. }
  23974. // Cap indices
  23975. for (i = 0; i < tessellation; i++) {
  23976. if (!isTop) {
  23977. indices.push(vbase);
  23978. indices.push(vbase + (i + 1));
  23979. indices.push(vbase + (i + 2));
  23980. }
  23981. else {
  23982. indices.push(vbase);
  23983. indices.push(vbase + (i + 2));
  23984. indices.push(vbase + (i + 1));
  23985. }
  23986. }
  23987. };
  23988. // add caps to geometry
  23989. createCylinderCap(false);
  23990. createCylinderCap(true);
  23991. // Sides
  23992. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23993. var vertexData = new VertexData();
  23994. vertexData.indices = indices;
  23995. vertexData.positions = positions;
  23996. vertexData.normals = normals;
  23997. vertexData.uvs = uvs;
  23998. if (faceColors) {
  23999. vertexData.colors = colors;
  24000. }
  24001. return vertexData;
  24002. };
  24003. VertexData.CreateTorus = function (options) {
  24004. var indices = [];
  24005. var positions = [];
  24006. var normals = [];
  24007. var uvs = [];
  24008. var diameter = options.diameter || 1;
  24009. var thickness = options.thickness || 0.5;
  24010. var tessellation = options.tessellation || 16;
  24011. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24012. var stride = tessellation + 1;
  24013. for (var i = 0; i <= tessellation; i++) {
  24014. var u = i / tessellation;
  24015. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24016. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24017. for (var j = 0; j <= tessellation; j++) {
  24018. var v = 1 - j / tessellation;
  24019. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24020. var dx = Math.cos(innerAngle);
  24021. var dy = Math.sin(innerAngle);
  24022. // Create a vertex.
  24023. var normal = new BABYLON.Vector3(dx, dy, 0);
  24024. var position = normal.scale(thickness / 2);
  24025. var textureCoordinate = new BABYLON.Vector2(u, v);
  24026. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24027. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24028. positions.push(position.x, position.y, position.z);
  24029. normals.push(normal.x, normal.y, normal.z);
  24030. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24031. // And create indices for two triangles.
  24032. var nextI = (i + 1) % stride;
  24033. var nextJ = (j + 1) % stride;
  24034. indices.push(i * stride + j);
  24035. indices.push(i * stride + nextJ);
  24036. indices.push(nextI * stride + j);
  24037. indices.push(i * stride + nextJ);
  24038. indices.push(nextI * stride + nextJ);
  24039. indices.push(nextI * stride + j);
  24040. }
  24041. }
  24042. // Sides
  24043. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24044. // Result
  24045. var vertexData = new VertexData();
  24046. vertexData.indices = indices;
  24047. vertexData.positions = positions;
  24048. vertexData.normals = normals;
  24049. vertexData.uvs = uvs;
  24050. return vertexData;
  24051. };
  24052. VertexData.CreateLines = function (options) {
  24053. var indices = [];
  24054. var positions = [];
  24055. var points = options.points;
  24056. for (var index = 0; index < points.length; index++) {
  24057. positions.push(points[index].x, points[index].y, points[index].z);
  24058. if (index > 0) {
  24059. indices.push(index - 1);
  24060. indices.push(index);
  24061. }
  24062. }
  24063. // Result
  24064. var vertexData = new VertexData();
  24065. vertexData.indices = indices;
  24066. vertexData.positions = positions;
  24067. return vertexData;
  24068. };
  24069. VertexData.CreateDashedLines = function (options) {
  24070. var dashSize = options.dashSize || 3;
  24071. var gapSize = options.gapSize || 1;
  24072. var dashNb = options.dashNb || 200;
  24073. var points = options.points;
  24074. var positions = new Array();
  24075. var indices = new Array();
  24076. var curvect = BABYLON.Vector3.Zero();
  24077. var lg = 0;
  24078. var nb = 0;
  24079. var shft = 0;
  24080. var dashshft = 0;
  24081. var curshft = 0;
  24082. var idx = 0;
  24083. var i = 0;
  24084. for (i = 0; i < points.length - 1; i++) {
  24085. points[i + 1].subtractToRef(points[i], curvect);
  24086. lg += curvect.length();
  24087. }
  24088. shft = lg / dashNb;
  24089. dashshft = dashSize * shft / (dashSize + gapSize);
  24090. for (i = 0; i < points.length - 1; i++) {
  24091. points[i + 1].subtractToRef(points[i], curvect);
  24092. nb = Math.floor(curvect.length() / shft);
  24093. curvect.normalize();
  24094. for (var j = 0; j < nb; j++) {
  24095. curshft = shft * j;
  24096. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24097. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24098. indices.push(idx, idx + 1);
  24099. idx += 2;
  24100. }
  24101. }
  24102. // Result
  24103. var vertexData = new VertexData();
  24104. vertexData.positions = positions;
  24105. vertexData.indices = indices;
  24106. return vertexData;
  24107. };
  24108. VertexData.CreateGround = function (options) {
  24109. var indices = [];
  24110. var positions = [];
  24111. var normals = [];
  24112. var uvs = [];
  24113. var row, col;
  24114. var width = options.width || 1;
  24115. var height = options.height || 1;
  24116. var subdivisions = options.subdivisions || 1;
  24117. for (row = 0; row <= subdivisions; row++) {
  24118. for (col = 0; col <= subdivisions; col++) {
  24119. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24120. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24121. positions.push(position.x, position.y, position.z);
  24122. normals.push(normal.x, normal.y, normal.z);
  24123. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24124. }
  24125. }
  24126. for (row = 0; row < subdivisions; row++) {
  24127. for (col = 0; col < subdivisions; col++) {
  24128. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24129. indices.push(col + 1 + row * (subdivisions + 1));
  24130. indices.push(col + row * (subdivisions + 1));
  24131. indices.push(col + (row + 1) * (subdivisions + 1));
  24132. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24133. indices.push(col + row * (subdivisions + 1));
  24134. }
  24135. }
  24136. // Result
  24137. var vertexData = new VertexData();
  24138. vertexData.indices = indices;
  24139. vertexData.positions = positions;
  24140. vertexData.normals = normals;
  24141. vertexData.uvs = uvs;
  24142. return vertexData;
  24143. };
  24144. VertexData.CreateTiledGround = function (options) {
  24145. var xmin = options.xmin;
  24146. var zmin = options.zmin;
  24147. var xmax = options.xmax;
  24148. var zmax = options.zmax;
  24149. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24150. var precision = options.precision || { w: 1, h: 1 };
  24151. var indices = [];
  24152. var positions = [];
  24153. var normals = [];
  24154. var uvs = [];
  24155. var row, col, tileRow, tileCol;
  24156. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24157. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24158. precision.w = (precision.w < 1) ? 1 : precision.w;
  24159. precision.h = (precision.h < 1) ? 1 : precision.h;
  24160. var tileSize = {
  24161. 'w': (xmax - xmin) / subdivisions.w,
  24162. 'h': (zmax - zmin) / subdivisions.h
  24163. };
  24164. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24165. // Indices
  24166. var base = positions.length / 3;
  24167. var rowLength = precision.w + 1;
  24168. for (row = 0; row < precision.h; row++) {
  24169. for (col = 0; col < precision.w; col++) {
  24170. var square = [
  24171. base + col + row * rowLength,
  24172. base + (col + 1) + row * rowLength,
  24173. base + (col + 1) + (row + 1) * rowLength,
  24174. base + col + (row + 1) * rowLength
  24175. ];
  24176. indices.push(square[1]);
  24177. indices.push(square[2]);
  24178. indices.push(square[3]);
  24179. indices.push(square[0]);
  24180. indices.push(square[1]);
  24181. indices.push(square[3]);
  24182. }
  24183. }
  24184. // Position, normals and uvs
  24185. var position = BABYLON.Vector3.Zero();
  24186. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24187. for (row = 0; row <= precision.h; row++) {
  24188. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24189. for (col = 0; col <= precision.w; col++) {
  24190. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24191. position.y = 0;
  24192. positions.push(position.x, position.y, position.z);
  24193. normals.push(normal.x, normal.y, normal.z);
  24194. uvs.push(col / precision.w, row / precision.h);
  24195. }
  24196. }
  24197. }
  24198. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24199. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24200. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24201. }
  24202. }
  24203. // Result
  24204. var vertexData = new VertexData();
  24205. vertexData.indices = indices;
  24206. vertexData.positions = positions;
  24207. vertexData.normals = normals;
  24208. vertexData.uvs = uvs;
  24209. return vertexData;
  24210. };
  24211. VertexData.CreateGroundFromHeightMap = function (options) {
  24212. var indices = [];
  24213. var positions = [];
  24214. var normals = [];
  24215. var uvs = [];
  24216. var row, col;
  24217. // Vertices
  24218. for (row = 0; row <= options.subdivisions; row++) {
  24219. for (col = 0; col <= options.subdivisions; col++) {
  24220. 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));
  24221. // Compute height
  24222. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24223. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24224. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24225. var r = options.buffer[pos] / 255.0;
  24226. var g = options.buffer[pos + 1] / 255.0;
  24227. var b = options.buffer[pos + 2] / 255.0;
  24228. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24229. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24230. // Add vertex
  24231. positions.push(position.x, position.y, position.z);
  24232. normals.push(0, 0, 0);
  24233. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24234. }
  24235. }
  24236. // Indices
  24237. for (row = 0; row < options.subdivisions; row++) {
  24238. for (col = 0; col < options.subdivisions; col++) {
  24239. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24240. indices.push(col + 1 + row * (options.subdivisions + 1));
  24241. indices.push(col + row * (options.subdivisions + 1));
  24242. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24243. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24244. indices.push(col + row * (options.subdivisions + 1));
  24245. }
  24246. }
  24247. // Normals
  24248. VertexData.ComputeNormals(positions, indices, normals);
  24249. // Result
  24250. var vertexData = new VertexData();
  24251. vertexData.indices = indices;
  24252. vertexData.positions = positions;
  24253. vertexData.normals = normals;
  24254. vertexData.uvs = uvs;
  24255. return vertexData;
  24256. };
  24257. VertexData.CreatePlane = function (options) {
  24258. var indices = [];
  24259. var positions = [];
  24260. var normals = [];
  24261. var uvs = [];
  24262. var width = options.width || options.size || 1;
  24263. var height = options.height || options.size || 1;
  24264. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24265. // Vertices
  24266. var halfWidth = width / 2.0;
  24267. var halfHeight = height / 2.0;
  24268. positions.push(-halfWidth, -halfHeight, 0);
  24269. normals.push(0, 0, -1.0);
  24270. uvs.push(0.0, 0.0);
  24271. positions.push(halfWidth, -halfHeight, 0);
  24272. normals.push(0, 0, -1.0);
  24273. uvs.push(1.0, 0.0);
  24274. positions.push(halfWidth, halfHeight, 0);
  24275. normals.push(0, 0, -1.0);
  24276. uvs.push(1.0, 1.0);
  24277. positions.push(-halfWidth, halfHeight, 0);
  24278. normals.push(0, 0, -1.0);
  24279. uvs.push(0.0, 1.0);
  24280. // Indices
  24281. indices.push(0);
  24282. indices.push(1);
  24283. indices.push(2);
  24284. indices.push(0);
  24285. indices.push(2);
  24286. indices.push(3);
  24287. // Sides
  24288. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24289. // Result
  24290. var vertexData = new VertexData();
  24291. vertexData.indices = indices;
  24292. vertexData.positions = positions;
  24293. vertexData.normals = normals;
  24294. vertexData.uvs = uvs;
  24295. return vertexData;
  24296. };
  24297. VertexData.CreateDisc = function (options) {
  24298. var positions = [];
  24299. var indices = [];
  24300. var normals = [];
  24301. var uvs = [];
  24302. var radius = options.radius || 0.5;
  24303. var tessellation = options.tessellation || 64;
  24304. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24305. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24306. // positions and uvs
  24307. positions.push(0, 0, 0); // disc center first
  24308. uvs.push(0.5, 0.5);
  24309. var theta = Math.PI * 2 * arc;
  24310. var step = theta / tessellation;
  24311. for (var a = 0; a < theta; a += step) {
  24312. var x = Math.cos(a);
  24313. var y = Math.sin(a);
  24314. var u = (x + 1) / 2;
  24315. var v = (1 - y) / 2;
  24316. positions.push(radius * x, radius * y, 0);
  24317. uvs.push(u, v);
  24318. }
  24319. if (arc === 1) {
  24320. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24321. uvs.push(uvs[2], uvs[3]);
  24322. }
  24323. //indices
  24324. var vertexNb = positions.length / 3;
  24325. for (var i = 1; i < vertexNb - 1; i++) {
  24326. indices.push(i + 1, 0, i);
  24327. }
  24328. // result
  24329. VertexData.ComputeNormals(positions, indices, normals);
  24330. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24331. var vertexData = new VertexData();
  24332. vertexData.indices = indices;
  24333. vertexData.positions = positions;
  24334. vertexData.normals = normals;
  24335. vertexData.uvs = uvs;
  24336. return vertexData;
  24337. };
  24338. VertexData.CreateIcoSphere = function (options) {
  24339. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24340. var radius = options.radius || 1;
  24341. var flat = (options.flat === undefined) ? true : options.flat;
  24342. var subdivisions = options.subdivisions || 4;
  24343. var radiusX = options.radiusX || radius;
  24344. var radiusY = options.radiusY || radius;
  24345. var radiusZ = options.radiusZ || radius;
  24346. var t = (1 + Math.sqrt(5)) / 2;
  24347. // 12 vertex x,y,z
  24348. var ico_vertices = [
  24349. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24350. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24351. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24352. ];
  24353. // index of 3 vertex makes a face of icopshere
  24354. var ico_indices = [
  24355. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24356. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24357. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24358. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24359. ];
  24360. // vertex for uv have aliased position, not for UV
  24361. var vertices_unalias_id = [
  24362. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24363. // vertex alias
  24364. 0,
  24365. 2,
  24366. 3,
  24367. 3,
  24368. 3,
  24369. 4,
  24370. 7,
  24371. 8,
  24372. 9,
  24373. 9,
  24374. 10,
  24375. 11 // 23: B + 12
  24376. ];
  24377. // uv as integer step (not pixels !)
  24378. var ico_vertexuv = [
  24379. 5, 1, 3, 1, 6, 4, 0, 0,
  24380. 5, 3, 4, 2, 2, 2, 4, 0,
  24381. 2, 0, 1, 1, 6, 0, 6, 2,
  24382. // vertex alias (for same vertex on different faces)
  24383. 0, 4,
  24384. 3, 3,
  24385. 4, 4,
  24386. 3, 1,
  24387. 4, 2,
  24388. 4, 4,
  24389. 0, 2,
  24390. 1, 1,
  24391. 2, 2,
  24392. 3, 3,
  24393. 1, 3,
  24394. 2, 4 // 23: B + 12
  24395. ];
  24396. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24397. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24398. // First island of uv mapping
  24399. // v = 4h 3+ 2
  24400. // v = 3h 9+ 4
  24401. // v = 2h 9+ 5 B
  24402. // v = 1h 9 1 0
  24403. // v = 0h 3 8 7 A
  24404. // u = 0 1 2 3 4 5 6 *a
  24405. // Second island of uv mapping
  24406. // v = 4h 0+ B+ 4+
  24407. // v = 3h A+ 2+
  24408. // v = 2h 7+ 6 3+
  24409. // v = 1h 8+ 3+
  24410. // v = 0h
  24411. // u = 0 1 2 3 4 5 6 *a
  24412. // Face layout on texture UV mapping
  24413. // ============
  24414. // \ 4 /\ 16 / ======
  24415. // \ / \ / /\ 11 /
  24416. // \/ 7 \/ / \ /
  24417. // ======= / 10 \/
  24418. // /\ 17 /\ =======
  24419. // / \ / \ \ 15 /\
  24420. // / 8 \/ 12 \ \ / \
  24421. // ============ \/ 6 \
  24422. // \ 18 /\ ============
  24423. // \ / \ \ 5 /\ 0 /
  24424. // \/ 13 \ \ / \ /
  24425. // ======= \/ 1 \/
  24426. // =============
  24427. // /\ 19 /\ 2 /\
  24428. // / \ / \ / \
  24429. // / 14 \/ 9 \/ 3 \
  24430. // ===================
  24431. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24432. var ustep = 138 / 1024;
  24433. var vstep = 239 / 1024;
  24434. var uoffset = 60 / 1024;
  24435. var voffset = 26 / 1024;
  24436. // Second island should have margin, not to touch the first island
  24437. // avoid any borderline artefact in pixel rounding
  24438. var island_u_offset = -40 / 1024;
  24439. var island_v_offset = +20 / 1024;
  24440. // face is either island 0 or 1 :
  24441. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24442. var island = [
  24443. 0, 0, 0, 0, 1,
  24444. 0, 0, 1, 1, 0,
  24445. 0, 0, 1, 1, 0,
  24446. 0, 1, 1, 1, 0 // 15 - 19
  24447. ];
  24448. var indices = [];
  24449. var positions = [];
  24450. var normals = [];
  24451. var uvs = [];
  24452. var current_indice = 0;
  24453. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24454. var face_vertex_pos = new Array(3);
  24455. var face_vertex_uv = new Array(3);
  24456. var v012;
  24457. for (v012 = 0; v012 < 3; v012++) {
  24458. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24459. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24460. }
  24461. // create all with normals
  24462. for (var face = 0; face < 20; face++) {
  24463. // 3 vertex per face
  24464. for (v012 = 0; v012 < 3; v012++) {
  24465. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24466. var v_id = ico_indices[3 * face + v012];
  24467. // vertex have 3D position (x,y,z)
  24468. 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]);
  24469. // Normalize to get normal, then scale to radius
  24470. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24471. // uv Coordinates from vertex ID
  24472. 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);
  24473. }
  24474. // Subdivide the face (interpolate pos, norm, uv)
  24475. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24476. // - norm is linear interpolation of vertex corner normal
  24477. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24478. // - uv is linear interpolation
  24479. //
  24480. // Topology is as below for sub-divide by 2
  24481. // vertex shown as v0,v1,v2
  24482. // interp index is i1 to progress in range [v0,v1[
  24483. // interp index is i2 to progress in range [v0,v2[
  24484. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24485. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24486. //
  24487. //
  24488. // i2 v2
  24489. // ^ ^
  24490. // / / \
  24491. // / / \
  24492. // / / \
  24493. // / / (0,1) \
  24494. // / #---------\
  24495. // / / \ (0,0)'/ \
  24496. // / / \ / \
  24497. // / / \ / \
  24498. // / / (0,0) \ / (1,0) \
  24499. // / #---------#---------\
  24500. // v0 v1
  24501. //
  24502. // --------------------> i1
  24503. //
  24504. // interp of (i1,i2):
  24505. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24506. // along i1 : lerp(x0,x1, i1/(S-i2))
  24507. //
  24508. // centroid of triangle is needed to get help normal computation
  24509. // (c1,c2) are used for centroid location
  24510. var interp_vertex = function (i1, i2, c1, c2) {
  24511. // vertex is interpolated from
  24512. // - face_vertex_pos[0..2]
  24513. // - face_vertex_uv[0..2]
  24514. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24515. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24516. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24517. pos_interp.normalize();
  24518. var vertex_normal;
  24519. if (flat) {
  24520. // in flat mode, recalculate normal as face centroid normal
  24521. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24522. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24523. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24524. }
  24525. else {
  24526. // in smooth mode, recalculate normal from each single vertex position
  24527. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  24528. }
  24529. // Vertex normal need correction due to X,Y,Z radius scaling
  24530. vertex_normal.x /= radiusX;
  24531. vertex_normal.y /= radiusY;
  24532. vertex_normal.z /= radiusZ;
  24533. vertex_normal.normalize();
  24534. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24535. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24536. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24537. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  24538. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24539. uvs.push(uv_interp.x, uv_interp.y);
  24540. // push each vertex has member of a face
  24541. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24542. indices.push(current_indice);
  24543. current_indice++;
  24544. };
  24545. for (var i2 = 0; i2 < subdivisions; i2++) {
  24546. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24547. // face : (i1,i2) for /\ :
  24548. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24549. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24550. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24551. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24552. if (i1 + i2 + 1 < subdivisions) {
  24553. // face : (i1,i2)' for \/ :
  24554. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24555. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24556. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24557. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24558. }
  24559. }
  24560. }
  24561. }
  24562. // Sides
  24563. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24564. // Result
  24565. var vertexData = new VertexData();
  24566. vertexData.indices = indices;
  24567. vertexData.positions = positions;
  24568. vertexData.normals = normals;
  24569. vertexData.uvs = uvs;
  24570. return vertexData;
  24571. };
  24572. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24573. VertexData.CreatePolyhedron = function (options) {
  24574. // provided polyhedron types :
  24575. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24576. // 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)
  24577. var polyhedra = [];
  24578. 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]] };
  24579. 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]] };
  24580. polyhedra[2] = {
  24581. 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]],
  24582. 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]]
  24583. };
  24584. polyhedra[3] = {
  24585. 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]],
  24586. 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]]
  24587. };
  24588. polyhedra[4] = {
  24589. 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]],
  24590. 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]]
  24591. };
  24592. 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]] };
  24593. 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]] };
  24594. 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]] };
  24595. 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]] };
  24596. 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]] };
  24597. 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]] };
  24598. 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]] };
  24599. 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]] };
  24600. 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]] };
  24601. polyhedra[14] = {
  24602. 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]],
  24603. 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]]
  24604. };
  24605. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24606. var size = options.size;
  24607. var sizeX = options.sizeX || size || 1;
  24608. var sizeY = options.sizeY || size || 1;
  24609. var sizeZ = options.sizeZ || size || 1;
  24610. var data = options.custom || polyhedra[type];
  24611. var nbfaces = data.face.length;
  24612. var faceUV = options.faceUV || new Array(nbfaces);
  24613. var faceColors = options.faceColors;
  24614. var flat = (options.flat === undefined) ? true : options.flat;
  24615. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24616. var positions = [];
  24617. var indices = [];
  24618. var normals = [];
  24619. var uvs = [];
  24620. var colors = [];
  24621. var index = 0;
  24622. var faceIdx = 0; // face cursor in the array "indexes"
  24623. var indexes = [];
  24624. var i = 0;
  24625. var f = 0;
  24626. var u, v, ang, x, y, tmp;
  24627. // default face colors and UV if undefined
  24628. if (flat) {
  24629. for (f = 0; f < nbfaces; f++) {
  24630. if (faceColors && faceColors[f] === undefined) {
  24631. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24632. }
  24633. if (faceUV && faceUV[f] === undefined) {
  24634. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24635. }
  24636. }
  24637. }
  24638. if (!flat) {
  24639. for (i = 0; i < data.vertex.length; i++) {
  24640. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24641. uvs.push(0, 0);
  24642. }
  24643. for (f = 0; f < nbfaces; f++) {
  24644. for (i = 0; i < data.face[f].length - 2; i++) {
  24645. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24646. }
  24647. }
  24648. }
  24649. else {
  24650. for (f = 0; f < nbfaces; f++) {
  24651. var fl = data.face[f].length; // number of vertices of the current face
  24652. ang = 2 * Math.PI / fl;
  24653. x = 0.5 * Math.tan(ang / 2);
  24654. y = 0.5;
  24655. // positions, uvs, colors
  24656. for (i = 0; i < fl; i++) {
  24657. // positions
  24658. 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);
  24659. indexes.push(index);
  24660. index++;
  24661. // uvs
  24662. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24663. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24664. uvs.push(u, v);
  24665. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24666. y = x * Math.sin(ang) + y * Math.cos(ang);
  24667. x = tmp;
  24668. // colors
  24669. if (faceColors) {
  24670. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24671. }
  24672. }
  24673. // indices from indexes
  24674. for (i = 0; i < fl - 2; i++) {
  24675. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24676. }
  24677. faceIdx += fl;
  24678. }
  24679. }
  24680. VertexData.ComputeNormals(positions, indices, normals);
  24681. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24682. var vertexData = new VertexData();
  24683. vertexData.positions = positions;
  24684. vertexData.indices = indices;
  24685. vertexData.normals = normals;
  24686. vertexData.uvs = uvs;
  24687. if (faceColors && flat) {
  24688. vertexData.colors = colors;
  24689. }
  24690. return vertexData;
  24691. };
  24692. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24693. VertexData.CreateTorusKnot = function (options) {
  24694. var indices = [];
  24695. var positions = [];
  24696. var normals = [];
  24697. var uvs = [];
  24698. var radius = options.radius || 2;
  24699. var tube = options.tube || 0.5;
  24700. var radialSegments = options.radialSegments || 32;
  24701. var tubularSegments = options.tubularSegments || 32;
  24702. var p = options.p || 2;
  24703. var q = options.q || 3;
  24704. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24705. // Helper
  24706. var getPos = function (angle) {
  24707. var cu = Math.cos(angle);
  24708. var su = Math.sin(angle);
  24709. var quOverP = q / p * angle;
  24710. var cs = Math.cos(quOverP);
  24711. var tx = radius * (2 + cs) * 0.5 * cu;
  24712. var ty = radius * (2 + cs) * su * 0.5;
  24713. var tz = radius * Math.sin(quOverP) * 0.5;
  24714. return new BABYLON.Vector3(tx, ty, tz);
  24715. };
  24716. // Vertices
  24717. var i;
  24718. var j;
  24719. for (i = 0; i <= radialSegments; i++) {
  24720. var modI = i % radialSegments;
  24721. var u = modI / radialSegments * 2 * p * Math.PI;
  24722. var p1 = getPos(u);
  24723. var p2 = getPos(u + 0.01);
  24724. var tang = p2.subtract(p1);
  24725. var n = p2.add(p1);
  24726. var bitan = BABYLON.Vector3.Cross(tang, n);
  24727. n = BABYLON.Vector3.Cross(bitan, tang);
  24728. bitan.normalize();
  24729. n.normalize();
  24730. for (j = 0; j < tubularSegments; j++) {
  24731. var modJ = j % tubularSegments;
  24732. var v = modJ / tubularSegments * 2 * Math.PI;
  24733. var cx = -tube * Math.cos(v);
  24734. var cy = tube * Math.sin(v);
  24735. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24736. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24737. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24738. uvs.push(i / radialSegments);
  24739. uvs.push(j / tubularSegments);
  24740. }
  24741. }
  24742. for (i = 0; i < radialSegments; i++) {
  24743. for (j = 0; j < tubularSegments; j++) {
  24744. var jNext = (j + 1) % tubularSegments;
  24745. var a = i * tubularSegments + j;
  24746. var b = (i + 1) * tubularSegments + j;
  24747. var c = (i + 1) * tubularSegments + jNext;
  24748. var d = i * tubularSegments + jNext;
  24749. indices.push(d);
  24750. indices.push(b);
  24751. indices.push(a);
  24752. indices.push(d);
  24753. indices.push(c);
  24754. indices.push(b);
  24755. }
  24756. }
  24757. // Normals
  24758. VertexData.ComputeNormals(positions, indices, normals);
  24759. // Sides
  24760. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24761. // Result
  24762. var vertexData = new VertexData();
  24763. vertexData.indices = indices;
  24764. vertexData.positions = positions;
  24765. vertexData.normals = normals;
  24766. vertexData.uvs = uvs;
  24767. return vertexData;
  24768. };
  24769. // Tools
  24770. /**
  24771. * @param {any} - positions (number[] or Float32Array)
  24772. * @param {any} - indices (number[] or Uint16Array)
  24773. * @param {any} - normals (number[] or Float32Array)
  24774. */
  24775. VertexData.ComputeNormals = function (positions, indices, normals) {
  24776. var index = 0;
  24777. var p1p2x = 0.0;
  24778. var p1p2y = 0.0;
  24779. var p1p2z = 0.0;
  24780. var p3p2x = 0.0;
  24781. var p3p2y = 0.0;
  24782. var p3p2z = 0.0;
  24783. var faceNormalx = 0.0;
  24784. var faceNormaly = 0.0;
  24785. var faceNormalz = 0.0;
  24786. var length = 0.0;
  24787. var i1 = 0;
  24788. var i2 = 0;
  24789. var i3 = 0;
  24790. for (index = 0; index < positions.length; index++) {
  24791. normals[index] = 0.0;
  24792. }
  24793. // indice triplet = 1 face
  24794. var nbFaces = indices.length / 3;
  24795. for (index = 0; index < nbFaces; index++) {
  24796. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  24797. i2 = indices[index * 3 + 1];
  24798. i3 = indices[index * 3 + 2];
  24799. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  24800. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24801. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24802. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  24803. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24804. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24805. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  24806. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  24807. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  24808. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24809. length = (length === 0) ? 1.0 : length;
  24810. faceNormalx /= length; // normalize this normal
  24811. faceNormaly /= length;
  24812. faceNormalz /= length;
  24813. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  24814. normals[i1 * 3 + 1] += faceNormaly;
  24815. normals[i1 * 3 + 2] += faceNormalz;
  24816. normals[i2 * 3] += faceNormalx;
  24817. normals[i2 * 3 + 1] += faceNormaly;
  24818. normals[i2 * 3 + 2] += faceNormalz;
  24819. normals[i3 * 3] += faceNormalx;
  24820. normals[i3 * 3 + 1] += faceNormaly;
  24821. normals[i3 * 3 + 2] += faceNormalz;
  24822. }
  24823. // last normalization of each normal
  24824. for (index = 0; index < normals.length / 3; index++) {
  24825. faceNormalx = normals[index * 3];
  24826. faceNormaly = normals[index * 3 + 1];
  24827. faceNormalz = normals[index * 3 + 2];
  24828. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  24829. length = (length === 0) ? 1.0 : length;
  24830. faceNormalx /= length;
  24831. faceNormaly /= length;
  24832. faceNormalz /= length;
  24833. normals[index * 3] = faceNormalx;
  24834. normals[index * 3 + 1] = faceNormaly;
  24835. normals[index * 3 + 2] = faceNormalz;
  24836. }
  24837. };
  24838. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24839. var li = indices.length;
  24840. var ln = normals.length;
  24841. var i;
  24842. var n;
  24843. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24844. switch (sideOrientation) {
  24845. case BABYLON.Mesh.FRONTSIDE:
  24846. // nothing changed
  24847. break;
  24848. case BABYLON.Mesh.BACKSIDE:
  24849. var tmp;
  24850. // indices
  24851. for (i = 0; i < li; i += 3) {
  24852. tmp = indices[i];
  24853. indices[i] = indices[i + 2];
  24854. indices[i + 2] = tmp;
  24855. }
  24856. // normals
  24857. for (n = 0; n < ln; n++) {
  24858. normals[n] = -normals[n];
  24859. }
  24860. break;
  24861. case BABYLON.Mesh.DOUBLESIDE:
  24862. // positions
  24863. var lp = positions.length;
  24864. var l = lp / 3;
  24865. for (var p = 0; p < lp; p++) {
  24866. positions[lp + p] = positions[p];
  24867. }
  24868. // indices
  24869. for (i = 0; i < li; i += 3) {
  24870. indices[i + li] = indices[i + 2] + l;
  24871. indices[i + 1 + li] = indices[i + 1] + l;
  24872. indices[i + 2 + li] = indices[i] + l;
  24873. }
  24874. // normals
  24875. for (n = 0; n < ln; n++) {
  24876. normals[ln + n] = -normals[n];
  24877. }
  24878. // uvs
  24879. var lu = uvs.length;
  24880. for (var u = 0; u < lu; u++) {
  24881. uvs[u + lu] = uvs[u];
  24882. }
  24883. break;
  24884. }
  24885. };
  24886. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  24887. var vertexData = new VertexData();
  24888. // positions
  24889. var positions = parsedVertexData.positions;
  24890. if (positions) {
  24891. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  24892. }
  24893. // normals
  24894. var normals = parsedVertexData.normals;
  24895. if (normals) {
  24896. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  24897. }
  24898. // uvs
  24899. var uvs = parsedVertexData.uvs;
  24900. if (uvs) {
  24901. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  24902. }
  24903. // uv2s
  24904. var uv2s = parsedVertexData.uv2s;
  24905. if (uv2s) {
  24906. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  24907. }
  24908. // uv3s
  24909. var uv3s = parsedVertexData.uv3s;
  24910. if (uv3s) {
  24911. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  24912. }
  24913. // uv4s
  24914. var uv4s = parsedVertexData.uv4s;
  24915. if (uv4s) {
  24916. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  24917. }
  24918. // uv5s
  24919. var uv5s = parsedVertexData.uv5s;
  24920. if (uv5s) {
  24921. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  24922. }
  24923. // uv6s
  24924. var uv6s = parsedVertexData.uv6s;
  24925. if (uv6s) {
  24926. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  24927. }
  24928. // colors
  24929. var colors = parsedVertexData.colors;
  24930. if (colors) {
  24931. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  24932. }
  24933. // matricesIndices
  24934. var matricesIndices = parsedVertexData.matricesIndices;
  24935. if (matricesIndices) {
  24936. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  24937. }
  24938. // matricesWeights
  24939. var matricesWeights = parsedVertexData.matricesWeights;
  24940. if (matricesWeights) {
  24941. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  24942. }
  24943. // indices
  24944. var indices = parsedVertexData.indices;
  24945. if (indices) {
  24946. vertexData.indices = indices;
  24947. }
  24948. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  24949. };
  24950. return VertexData;
  24951. })();
  24952. BABYLON.VertexData = VertexData;
  24953. })(BABYLON || (BABYLON = {}));
  24954. var BABYLON;
  24955. (function (BABYLON) {
  24956. var Tags = (function () {
  24957. function Tags() {
  24958. }
  24959. Tags.EnableFor = function (obj) {
  24960. obj._tags = obj._tags || {};
  24961. obj.hasTags = function () {
  24962. return Tags.HasTags(obj);
  24963. };
  24964. obj.addTags = function (tagsString) {
  24965. return Tags.AddTagsTo(obj, tagsString);
  24966. };
  24967. obj.removeTags = function (tagsString) {
  24968. return Tags.RemoveTagsFrom(obj, tagsString);
  24969. };
  24970. obj.matchesTagsQuery = function (tagsQuery) {
  24971. return Tags.MatchesQuery(obj, tagsQuery);
  24972. };
  24973. };
  24974. Tags.DisableFor = function (obj) {
  24975. delete obj._tags;
  24976. delete obj.hasTags;
  24977. delete obj.addTags;
  24978. delete obj.removeTags;
  24979. delete obj.matchesTagsQuery;
  24980. };
  24981. Tags.HasTags = function (obj) {
  24982. if (!obj._tags) {
  24983. return false;
  24984. }
  24985. return !BABYLON.Tools.IsEmpty(obj._tags);
  24986. };
  24987. Tags.GetTags = function (obj) {
  24988. if (!obj._tags) {
  24989. return null;
  24990. }
  24991. return obj._tags;
  24992. };
  24993. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24994. // a tag cannot start with '||', '&&', and '!'
  24995. // it cannot contain whitespaces
  24996. Tags.AddTagsTo = function (obj, tagsString) {
  24997. if (!tagsString) {
  24998. return;
  24999. }
  25000. if (typeof tagsString !== "string") {
  25001. return;
  25002. }
  25003. var tags = tagsString.split(" ");
  25004. for (var t in tags) {
  25005. Tags._AddTagTo(obj, tags[t]);
  25006. }
  25007. };
  25008. Tags._AddTagTo = function (obj, tag) {
  25009. tag = tag.trim();
  25010. if (tag === "" || tag === "true" || tag === "false") {
  25011. return;
  25012. }
  25013. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25014. return;
  25015. }
  25016. Tags.EnableFor(obj);
  25017. obj._tags[tag] = true;
  25018. };
  25019. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25020. if (!Tags.HasTags(obj)) {
  25021. return;
  25022. }
  25023. var tags = tagsString.split(" ");
  25024. for (var t in tags) {
  25025. Tags._RemoveTagFrom(obj, tags[t]);
  25026. }
  25027. };
  25028. Tags._RemoveTagFrom = function (obj, tag) {
  25029. delete obj._tags[tag];
  25030. };
  25031. Tags.MatchesQuery = function (obj, tagsQuery) {
  25032. if (tagsQuery === undefined) {
  25033. return true;
  25034. }
  25035. if (tagsQuery === "") {
  25036. return Tags.HasTags(obj);
  25037. }
  25038. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25039. };
  25040. return Tags;
  25041. })();
  25042. BABYLON.Tags = Tags;
  25043. })(BABYLON || (BABYLON = {}));
  25044. var BABYLON;
  25045. (function (BABYLON) {
  25046. var Internals;
  25047. (function (Internals) {
  25048. var AndOrNotEvaluator = (function () {
  25049. function AndOrNotEvaluator() {
  25050. }
  25051. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25052. if (!query.match(/\([^\(\)]*\)/g)) {
  25053. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25054. }
  25055. else {
  25056. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25057. // remove parenthesis
  25058. r = r.slice(1, r.length - 1);
  25059. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25060. });
  25061. }
  25062. if (query === "true") {
  25063. return true;
  25064. }
  25065. if (query === "false") {
  25066. return false;
  25067. }
  25068. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25069. };
  25070. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25071. evaluateCallback = evaluateCallback || (function (r) {
  25072. return r === "true" ? true : false;
  25073. });
  25074. var result;
  25075. var or = parenthesisContent.split("||");
  25076. for (var i in or) {
  25077. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25078. var and = ori.split("&&");
  25079. if (and.length > 1) {
  25080. for (var j = 0; j < and.length; ++j) {
  25081. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25082. if (andj !== "true" && andj !== "false") {
  25083. if (andj[0] === "!") {
  25084. result = !evaluateCallback(andj.substring(1));
  25085. }
  25086. else {
  25087. result = evaluateCallback(andj);
  25088. }
  25089. }
  25090. else {
  25091. result = andj === "true" ? true : false;
  25092. }
  25093. if (!result) {
  25094. ori = "false";
  25095. break;
  25096. }
  25097. }
  25098. }
  25099. if (result || ori === "true") {
  25100. result = true;
  25101. break;
  25102. }
  25103. // result equals false (or undefined)
  25104. if (ori !== "true" && ori !== "false") {
  25105. if (ori[0] === "!") {
  25106. result = !evaluateCallback(ori.substring(1));
  25107. }
  25108. else {
  25109. result = evaluateCallback(ori);
  25110. }
  25111. }
  25112. else {
  25113. result = ori === "true" ? true : false;
  25114. }
  25115. }
  25116. // the whole parenthesis scope is replaced by 'true' or 'false'
  25117. return result ? "true" : "false";
  25118. };
  25119. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25120. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25121. // remove whitespaces
  25122. r = r.replace(/[\s]/g, function () { return ""; });
  25123. return r.length % 2 ? "!" : "";
  25124. });
  25125. booleanString = booleanString.trim();
  25126. if (booleanString === "!true") {
  25127. booleanString = "false";
  25128. }
  25129. else if (booleanString === "!false") {
  25130. booleanString = "true";
  25131. }
  25132. return booleanString;
  25133. };
  25134. return AndOrNotEvaluator;
  25135. })();
  25136. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25137. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25138. })(BABYLON || (BABYLON = {}));
  25139. var BABYLON;
  25140. (function (BABYLON) {
  25141. var PostProcessRenderPass = (function () {
  25142. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25143. this._enabled = true;
  25144. this._refCount = 0;
  25145. this._name = name;
  25146. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25147. this.setRenderList(renderList);
  25148. this._renderTexture.onBeforeRender = beforeRender;
  25149. this._renderTexture.onAfterRender = afterRender;
  25150. this._scene = scene;
  25151. this._renderList = renderList;
  25152. }
  25153. // private
  25154. PostProcessRenderPass.prototype._incRefCount = function () {
  25155. if (this._refCount === 0) {
  25156. this._scene.customRenderTargets.push(this._renderTexture);
  25157. }
  25158. return ++this._refCount;
  25159. };
  25160. PostProcessRenderPass.prototype._decRefCount = function () {
  25161. this._refCount--;
  25162. if (this._refCount <= 0) {
  25163. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25164. }
  25165. return this._refCount;
  25166. };
  25167. PostProcessRenderPass.prototype._update = function () {
  25168. this.setRenderList(this._renderList);
  25169. };
  25170. // public
  25171. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25172. this._renderTexture.renderList = renderList;
  25173. };
  25174. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25175. return this._renderTexture;
  25176. };
  25177. return PostProcessRenderPass;
  25178. })();
  25179. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25180. })(BABYLON || (BABYLON = {}));
  25181. var BABYLON;
  25182. (function (BABYLON) {
  25183. var PostProcessRenderEffect = (function () {
  25184. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25185. this._engine = engine;
  25186. this._name = name;
  25187. this._singleInstance = singleInstance || true;
  25188. this._getPostProcess = getPostProcess;
  25189. this._cameras = [];
  25190. this._indicesForCamera = [];
  25191. this._postProcesses = {};
  25192. this._renderPasses = {};
  25193. this._renderEffectAsPasses = {};
  25194. }
  25195. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25196. get: function () {
  25197. for (var index in this._postProcesses) {
  25198. if (!this._postProcesses[index].isSupported) {
  25199. return false;
  25200. }
  25201. }
  25202. return true;
  25203. },
  25204. enumerable: true,
  25205. configurable: true
  25206. });
  25207. PostProcessRenderEffect.prototype._update = function () {
  25208. for (var renderPassName in this._renderPasses) {
  25209. this._renderPasses[renderPassName]._update();
  25210. }
  25211. };
  25212. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25213. this._renderPasses[renderPass._name] = renderPass;
  25214. this._linkParameters();
  25215. };
  25216. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25217. delete this._renderPasses[renderPass._name];
  25218. this._linkParameters();
  25219. };
  25220. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25221. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25222. this._linkParameters();
  25223. };
  25224. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25225. for (var renderPassName in this._renderPasses) {
  25226. if (renderPassName === passName) {
  25227. return this._renderPasses[passName];
  25228. }
  25229. }
  25230. };
  25231. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25232. this._renderPasses = {};
  25233. this._linkParameters();
  25234. };
  25235. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25236. var cameraKey;
  25237. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25238. for (var i = 0; i < _cam.length; i++) {
  25239. var camera = _cam[i];
  25240. var cameraName = camera.name;
  25241. if (this._singleInstance) {
  25242. cameraKey = 0;
  25243. }
  25244. else {
  25245. cameraKey = cameraName;
  25246. }
  25247. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25248. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25249. if (!this._indicesForCamera[cameraName]) {
  25250. this._indicesForCamera[cameraName] = [];
  25251. }
  25252. this._indicesForCamera[cameraName].push(index);
  25253. if (this._cameras.indexOf(camera) === -1) {
  25254. this._cameras[cameraName] = camera;
  25255. }
  25256. for (var passName in this._renderPasses) {
  25257. this._renderPasses[passName]._incRefCount();
  25258. }
  25259. }
  25260. this._linkParameters();
  25261. };
  25262. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25263. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25264. for (var i = 0; i < _cam.length; i++) {
  25265. var camera = _cam[i];
  25266. var cameraName = camera.name;
  25267. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25268. var index = this._cameras.indexOf(cameraName);
  25269. this._indicesForCamera.splice(index, 1);
  25270. this._cameras.splice(index, 1);
  25271. for (var passName in this._renderPasses) {
  25272. this._renderPasses[passName]._decRefCount();
  25273. }
  25274. }
  25275. };
  25276. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25277. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25278. for (var i = 0; i < _cam.length; i++) {
  25279. var camera = _cam[i];
  25280. var cameraName = camera.name;
  25281. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25282. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25283. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25284. }
  25285. }
  25286. for (var passName in this._renderPasses) {
  25287. this._renderPasses[passName]._incRefCount();
  25288. }
  25289. }
  25290. };
  25291. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25292. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25293. for (var i = 0; i < _cam.length; i++) {
  25294. var camera = _cam[i];
  25295. var cameraName = camera.Name;
  25296. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25297. for (var passName in this._renderPasses) {
  25298. this._renderPasses[passName]._decRefCount();
  25299. }
  25300. }
  25301. };
  25302. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25303. if (this._singleInstance) {
  25304. return this._postProcesses[0];
  25305. }
  25306. else {
  25307. return this._postProcesses[camera.name];
  25308. }
  25309. };
  25310. PostProcessRenderEffect.prototype._linkParameters = function () {
  25311. var _this = this;
  25312. for (var index in this._postProcesses) {
  25313. if (this.applyParameters) {
  25314. this.applyParameters(this._postProcesses[index]);
  25315. }
  25316. this._postProcesses[index].onBeforeRender = function (effect) {
  25317. _this._linkTextures(effect);
  25318. };
  25319. }
  25320. };
  25321. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25322. for (var renderPassName in this._renderPasses) {
  25323. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25324. }
  25325. for (var renderEffectName in this._renderEffectAsPasses) {
  25326. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25327. }
  25328. };
  25329. return PostProcessRenderEffect;
  25330. })();
  25331. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25332. })(BABYLON || (BABYLON = {}));
  25333. var BABYLON;
  25334. (function (BABYLON) {
  25335. var PostProcessRenderPipeline = (function () {
  25336. function PostProcessRenderPipeline(engine, name) {
  25337. this._engine = engine;
  25338. this._name = name;
  25339. this._renderEffects = {};
  25340. this._renderEffectsForIsolatedPass = {};
  25341. this._cameras = [];
  25342. }
  25343. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25344. get: function () {
  25345. for (var renderEffectName in this._renderEffects) {
  25346. if (!this._renderEffects[renderEffectName].isSupported) {
  25347. return false;
  25348. }
  25349. }
  25350. return true;
  25351. },
  25352. enumerable: true,
  25353. configurable: true
  25354. });
  25355. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25356. this._renderEffects[renderEffect._name] = renderEffect;
  25357. };
  25358. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25359. var renderEffects = this._renderEffects[renderEffectName];
  25360. if (!renderEffects) {
  25361. return;
  25362. }
  25363. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25364. };
  25365. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25366. var renderEffects = this._renderEffects[renderEffectName];
  25367. if (!renderEffects) {
  25368. return;
  25369. }
  25370. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25371. };
  25372. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25373. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25374. var indicesToDelete = [];
  25375. var i;
  25376. for (i = 0; i < _cam.length; i++) {
  25377. var camera = _cam[i];
  25378. var cameraName = camera.name;
  25379. if (this._cameras.indexOf(camera) === -1) {
  25380. this._cameras[cameraName] = camera;
  25381. }
  25382. else if (unique) {
  25383. indicesToDelete.push(i);
  25384. }
  25385. }
  25386. for (i = 0; i < indicesToDelete.length; i++) {
  25387. cameras.splice(indicesToDelete[i], 1);
  25388. }
  25389. for (var renderEffectName in this._renderEffects) {
  25390. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25391. }
  25392. };
  25393. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25394. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25395. for (var renderEffectName in this._renderEffects) {
  25396. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25397. }
  25398. for (var i = 0; i < _cam.length; i++) {
  25399. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25400. }
  25401. };
  25402. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25403. var _this = this;
  25404. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25405. var pass = null;
  25406. var renderEffectName;
  25407. for (renderEffectName in this._renderEffects) {
  25408. pass = this._renderEffects[renderEffectName].getPass(passName);
  25409. if (pass != null) {
  25410. break;
  25411. }
  25412. }
  25413. if (pass === null) {
  25414. return;
  25415. }
  25416. for (renderEffectName in this._renderEffects) {
  25417. this._renderEffects[renderEffectName]._disable(_cam);
  25418. }
  25419. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25420. for (var i = 0; i < _cam.length; i++) {
  25421. var camera = _cam[i];
  25422. var cameraName = camera.name;
  25423. 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); });
  25424. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25425. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25426. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25427. }
  25428. };
  25429. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25430. var _this = this;
  25431. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25432. for (var i = 0; i < _cam.length; i++) {
  25433. var camera = _cam[i];
  25434. var cameraName = camera.name;
  25435. 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); });
  25436. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25437. }
  25438. for (var renderEffectName in this._renderEffects) {
  25439. this._renderEffects[renderEffectName]._enable(_cam);
  25440. }
  25441. };
  25442. PostProcessRenderPipeline.prototype._update = function () {
  25443. for (var renderEffectName in this._renderEffects) {
  25444. this._renderEffects[renderEffectName]._update();
  25445. }
  25446. for (var i = 0; i < this._cameras.length; i++) {
  25447. var cameraName = this._cameras[i].name;
  25448. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25449. this._renderEffectsForIsolatedPass[cameraName]._update();
  25450. }
  25451. }
  25452. };
  25453. PostProcessRenderPipeline.prototype.dispose = function () {
  25454. // Must be implemented by children
  25455. };
  25456. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25457. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25458. return PostProcessRenderPipeline;
  25459. })();
  25460. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25461. })(BABYLON || (BABYLON = {}));
  25462. var BABYLON;
  25463. (function (BABYLON) {
  25464. var PostProcessRenderPipelineManager = (function () {
  25465. function PostProcessRenderPipelineManager() {
  25466. this._renderPipelines = {};
  25467. }
  25468. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25469. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25470. };
  25471. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25472. var renderPipeline = this._renderPipelines[renderPipelineName];
  25473. if (!renderPipeline) {
  25474. return;
  25475. }
  25476. renderPipeline._attachCameras(cameras, unique);
  25477. };
  25478. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25479. var renderPipeline = this._renderPipelines[renderPipelineName];
  25480. if (!renderPipeline) {
  25481. return;
  25482. }
  25483. renderPipeline._detachCameras(cameras);
  25484. };
  25485. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25486. var renderPipeline = this._renderPipelines[renderPipelineName];
  25487. if (!renderPipeline) {
  25488. return;
  25489. }
  25490. renderPipeline._enableEffect(renderEffectName, cameras);
  25491. };
  25492. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25493. var renderPipeline = this._renderPipelines[renderPipelineName];
  25494. if (!renderPipeline) {
  25495. return;
  25496. }
  25497. renderPipeline._disableEffect(renderEffectName, cameras);
  25498. };
  25499. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25500. var renderPipeline = this._renderPipelines[renderPipelineName];
  25501. if (!renderPipeline) {
  25502. return;
  25503. }
  25504. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25505. };
  25506. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25507. var renderPipeline = this._renderPipelines[renderPipelineName];
  25508. if (!renderPipeline) {
  25509. return;
  25510. }
  25511. renderPipeline._disableDisplayOnlyPass(cameras);
  25512. };
  25513. PostProcessRenderPipelineManager.prototype.update = function () {
  25514. for (var renderPipelineName in this._renderPipelines) {
  25515. var pipeline = this._renderPipelines[renderPipelineName];
  25516. if (!pipeline.isSupported) {
  25517. pipeline.dispose();
  25518. delete this._renderPipelines[renderPipelineName];
  25519. }
  25520. else {
  25521. pipeline._update();
  25522. }
  25523. }
  25524. };
  25525. return PostProcessRenderPipelineManager;
  25526. })();
  25527. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25528. })(BABYLON || (BABYLON = {}));
  25529. var BABYLON;
  25530. (function (BABYLON) {
  25531. var BoundingBoxRenderer = (function () {
  25532. function BoundingBoxRenderer(scene) {
  25533. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25534. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25535. this.showBackLines = true;
  25536. this.renderList = new BABYLON.SmartArray(32);
  25537. this._scene = scene;
  25538. }
  25539. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25540. if (this._colorShader) {
  25541. return;
  25542. }
  25543. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25544. attributes: ["position"],
  25545. uniforms: ["worldViewProjection", "color"]
  25546. });
  25547. var engine = this._scene.getEngine();
  25548. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25549. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25550. 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]);
  25551. };
  25552. BoundingBoxRenderer.prototype.reset = function () {
  25553. this.renderList.reset();
  25554. };
  25555. BoundingBoxRenderer.prototype.render = function () {
  25556. if (this.renderList.length === 0) {
  25557. return;
  25558. }
  25559. this._prepareRessources();
  25560. if (!this._colorShader.isReady()) {
  25561. return;
  25562. }
  25563. var engine = this._scene.getEngine();
  25564. engine.setDepthWrite(false);
  25565. this._colorShader._preBind();
  25566. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25567. var boundingBox = this.renderList.data[boundingBoxIndex];
  25568. var min = boundingBox.minimum;
  25569. var max = boundingBox.maximum;
  25570. var diff = max.subtract(min);
  25571. var median = min.add(diff.scale(0.5));
  25572. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25573. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25574. .multiply(boundingBox.getWorldMatrix());
  25575. // VBOs
  25576. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25577. if (this.showBackLines) {
  25578. // Back
  25579. engine.setDepthFunctionToGreaterOrEqual();
  25580. this._scene.resetCachedMaterial();
  25581. this._colorShader.setColor4("color", this.backColor.toColor4());
  25582. this._colorShader.bind(worldMatrix);
  25583. // Draw order
  25584. engine.draw(false, 0, 24);
  25585. }
  25586. // Front
  25587. engine.setDepthFunctionToLess();
  25588. this._scene.resetCachedMaterial();
  25589. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25590. this._colorShader.bind(worldMatrix);
  25591. // Draw order
  25592. engine.draw(false, 0, 24);
  25593. }
  25594. this._colorShader.unbind();
  25595. engine.setDepthFunctionToLessOrEqual();
  25596. engine.setDepthWrite(true);
  25597. };
  25598. BoundingBoxRenderer.prototype.dispose = function () {
  25599. if (!this._colorShader) {
  25600. return;
  25601. }
  25602. this._colorShader.dispose();
  25603. this._vb.dispose();
  25604. this._scene.getEngine()._releaseBuffer(this._ib);
  25605. };
  25606. return BoundingBoxRenderer;
  25607. })();
  25608. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25609. })(BABYLON || (BABYLON = {}));
  25610. var BABYLON;
  25611. (function (BABYLON) {
  25612. var Condition = (function () {
  25613. function Condition(actionManager) {
  25614. this._actionManager = actionManager;
  25615. }
  25616. Condition.prototype.isValid = function () {
  25617. return true;
  25618. };
  25619. Condition.prototype._getProperty = function (propertyPath) {
  25620. return this._actionManager._getProperty(propertyPath);
  25621. };
  25622. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25623. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25624. };
  25625. return Condition;
  25626. })();
  25627. BABYLON.Condition = Condition;
  25628. var ValueCondition = (function (_super) {
  25629. __extends(ValueCondition, _super);
  25630. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25631. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25632. _super.call(this, actionManager);
  25633. this.propertyPath = propertyPath;
  25634. this.value = value;
  25635. this.operator = operator;
  25636. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25637. this._property = this._getProperty(this.propertyPath);
  25638. }
  25639. Object.defineProperty(ValueCondition, "IsEqual", {
  25640. get: function () {
  25641. return ValueCondition._IsEqual;
  25642. },
  25643. enumerable: true,
  25644. configurable: true
  25645. });
  25646. Object.defineProperty(ValueCondition, "IsDifferent", {
  25647. get: function () {
  25648. return ValueCondition._IsDifferent;
  25649. },
  25650. enumerable: true,
  25651. configurable: true
  25652. });
  25653. Object.defineProperty(ValueCondition, "IsGreater", {
  25654. get: function () {
  25655. return ValueCondition._IsGreater;
  25656. },
  25657. enumerable: true,
  25658. configurable: true
  25659. });
  25660. Object.defineProperty(ValueCondition, "IsLesser", {
  25661. get: function () {
  25662. return ValueCondition._IsLesser;
  25663. },
  25664. enumerable: true,
  25665. configurable: true
  25666. });
  25667. // Methods
  25668. ValueCondition.prototype.isValid = function () {
  25669. switch (this.operator) {
  25670. case ValueCondition.IsGreater:
  25671. return this._target[this._property] > this.value;
  25672. case ValueCondition.IsLesser:
  25673. return this._target[this._property] < this.value;
  25674. case ValueCondition.IsEqual:
  25675. case ValueCondition.IsDifferent:
  25676. var check;
  25677. if (this.value.equals) {
  25678. check = this.value.equals(this._target[this._property]);
  25679. }
  25680. else {
  25681. check = this.value === this._target[this._property];
  25682. }
  25683. return this.operator === ValueCondition.IsEqual ? check : !check;
  25684. }
  25685. return false;
  25686. };
  25687. // Statics
  25688. ValueCondition._IsEqual = 0;
  25689. ValueCondition._IsDifferent = 1;
  25690. ValueCondition._IsGreater = 2;
  25691. ValueCondition._IsLesser = 3;
  25692. return ValueCondition;
  25693. })(Condition);
  25694. BABYLON.ValueCondition = ValueCondition;
  25695. var PredicateCondition = (function (_super) {
  25696. __extends(PredicateCondition, _super);
  25697. function PredicateCondition(actionManager, predicate) {
  25698. _super.call(this, actionManager);
  25699. this.predicate = predicate;
  25700. }
  25701. PredicateCondition.prototype.isValid = function () {
  25702. return this.predicate();
  25703. };
  25704. return PredicateCondition;
  25705. })(Condition);
  25706. BABYLON.PredicateCondition = PredicateCondition;
  25707. var StateCondition = (function (_super) {
  25708. __extends(StateCondition, _super);
  25709. function StateCondition(actionManager, target, value) {
  25710. _super.call(this, actionManager);
  25711. this.value = value;
  25712. this._target = target;
  25713. }
  25714. // Methods
  25715. StateCondition.prototype.isValid = function () {
  25716. return this._target.state === this.value;
  25717. };
  25718. return StateCondition;
  25719. })(Condition);
  25720. BABYLON.StateCondition = StateCondition;
  25721. })(BABYLON || (BABYLON = {}));
  25722. var BABYLON;
  25723. (function (BABYLON) {
  25724. var Action = (function () {
  25725. function Action(triggerOptions, condition) {
  25726. this.triggerOptions = triggerOptions;
  25727. if (triggerOptions.parameter) {
  25728. this.trigger = triggerOptions.trigger;
  25729. this._triggerParameter = triggerOptions.parameter;
  25730. }
  25731. else {
  25732. this.trigger = triggerOptions;
  25733. }
  25734. this._nextActiveAction = this;
  25735. this._condition = condition;
  25736. }
  25737. // Methods
  25738. Action.prototype._prepare = function () {
  25739. };
  25740. Action.prototype.getTriggerParameter = function () {
  25741. return this._triggerParameter;
  25742. };
  25743. Action.prototype._executeCurrent = function (evt) {
  25744. if (this._nextActiveAction._condition) {
  25745. var condition = this._nextActiveAction._condition;
  25746. var currentRenderId = this._actionManager.getScene().getRenderId();
  25747. // We cache the current evaluation for the current frame
  25748. if (condition._evaluationId === currentRenderId) {
  25749. if (!condition._currentResult) {
  25750. return;
  25751. }
  25752. }
  25753. else {
  25754. condition._evaluationId = currentRenderId;
  25755. if (!condition.isValid()) {
  25756. condition._currentResult = false;
  25757. return;
  25758. }
  25759. condition._currentResult = true;
  25760. }
  25761. }
  25762. this._nextActiveAction.execute(evt);
  25763. this.skipToNextActiveAction();
  25764. };
  25765. Action.prototype.execute = function (evt) {
  25766. };
  25767. Action.prototype.skipToNextActiveAction = function () {
  25768. if (this._nextActiveAction._child) {
  25769. if (!this._nextActiveAction._child._actionManager) {
  25770. this._nextActiveAction._child._actionManager = this._actionManager;
  25771. }
  25772. this._nextActiveAction = this._nextActiveAction._child;
  25773. }
  25774. else {
  25775. this._nextActiveAction = this;
  25776. }
  25777. };
  25778. Action.prototype.then = function (action) {
  25779. this._child = action;
  25780. action._actionManager = this._actionManager;
  25781. action._prepare();
  25782. return action;
  25783. };
  25784. Action.prototype._getProperty = function (propertyPath) {
  25785. return this._actionManager._getProperty(propertyPath);
  25786. };
  25787. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25788. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25789. };
  25790. return Action;
  25791. })();
  25792. BABYLON.Action = Action;
  25793. })(BABYLON || (BABYLON = {}));
  25794. var BABYLON;
  25795. (function (BABYLON) {
  25796. /**
  25797. * ActionEvent is the event beint sent when an action is triggered.
  25798. */
  25799. var ActionEvent = (function () {
  25800. /**
  25801. * @constructor
  25802. * @param source The mesh or sprite that triggered the action.
  25803. * @param pointerX The X mouse cursor position at the time of the event
  25804. * @param pointerY The Y mouse cursor position at the time of the event
  25805. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25806. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25807. */
  25808. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25809. this.source = source;
  25810. this.pointerX = pointerX;
  25811. this.pointerY = pointerY;
  25812. this.meshUnderPointer = meshUnderPointer;
  25813. this.sourceEvent = sourceEvent;
  25814. this.additionalData = additionalData;
  25815. }
  25816. /**
  25817. * Helper function to auto-create an ActionEvent from a source mesh.
  25818. * @param source The source mesh that triggered the event
  25819. * @param evt {Event} The original (browser) event
  25820. */
  25821. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25822. var scene = source.getScene();
  25823. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25824. };
  25825. /**
  25826. * Helper function to auto-create an ActionEvent from a source mesh.
  25827. * @param source The source sprite that triggered the event
  25828. * @param scene Scene associated with the sprite
  25829. * @param evt {Event} The original (browser) event
  25830. */
  25831. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25832. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25833. };
  25834. /**
  25835. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25836. * @param scene the scene where the event occurred
  25837. * @param evt {Event} The original (browser) event
  25838. */
  25839. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25840. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25841. };
  25842. return ActionEvent;
  25843. })();
  25844. BABYLON.ActionEvent = ActionEvent;
  25845. /**
  25846. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25847. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25848. */
  25849. var ActionManager = (function () {
  25850. function ActionManager(scene) {
  25851. // Members
  25852. this.actions = new Array();
  25853. this._scene = scene;
  25854. scene._actionManagers.push(this);
  25855. }
  25856. Object.defineProperty(ActionManager, "NothingTrigger", {
  25857. get: function () {
  25858. return ActionManager._NothingTrigger;
  25859. },
  25860. enumerable: true,
  25861. configurable: true
  25862. });
  25863. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25864. get: function () {
  25865. return ActionManager._OnPickTrigger;
  25866. },
  25867. enumerable: true,
  25868. configurable: true
  25869. });
  25870. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25871. get: function () {
  25872. return ActionManager._OnLeftPickTrigger;
  25873. },
  25874. enumerable: true,
  25875. configurable: true
  25876. });
  25877. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25878. get: function () {
  25879. return ActionManager._OnRightPickTrigger;
  25880. },
  25881. enumerable: true,
  25882. configurable: true
  25883. });
  25884. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25885. get: function () {
  25886. return ActionManager._OnCenterPickTrigger;
  25887. },
  25888. enumerable: true,
  25889. configurable: true
  25890. });
  25891. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  25892. get: function () {
  25893. return ActionManager._OnPickDownTrigger;
  25894. },
  25895. enumerable: true,
  25896. configurable: true
  25897. });
  25898. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25899. get: function () {
  25900. return ActionManager._OnPickUpTrigger;
  25901. },
  25902. enumerable: true,
  25903. configurable: true
  25904. });
  25905. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  25906. get: function () {
  25907. return ActionManager._OnLongPressTrigger;
  25908. },
  25909. enumerable: true,
  25910. configurable: true
  25911. });
  25912. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25913. get: function () {
  25914. return ActionManager._OnPointerOverTrigger;
  25915. },
  25916. enumerable: true,
  25917. configurable: true
  25918. });
  25919. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25920. get: function () {
  25921. return ActionManager._OnPointerOutTrigger;
  25922. },
  25923. enumerable: true,
  25924. configurable: true
  25925. });
  25926. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25927. get: function () {
  25928. return ActionManager._OnEveryFrameTrigger;
  25929. },
  25930. enumerable: true,
  25931. configurable: true
  25932. });
  25933. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25934. get: function () {
  25935. return ActionManager._OnIntersectionEnterTrigger;
  25936. },
  25937. enumerable: true,
  25938. configurable: true
  25939. });
  25940. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25941. get: function () {
  25942. return ActionManager._OnIntersectionExitTrigger;
  25943. },
  25944. enumerable: true,
  25945. configurable: true
  25946. });
  25947. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25948. get: function () {
  25949. return ActionManager._OnKeyDownTrigger;
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25955. get: function () {
  25956. return ActionManager._OnKeyUpTrigger;
  25957. },
  25958. enumerable: true,
  25959. configurable: true
  25960. });
  25961. // Methods
  25962. ActionManager.prototype.dispose = function () {
  25963. var index = this._scene._actionManagers.indexOf(this);
  25964. if (index > -1) {
  25965. this._scene._actionManagers.splice(index, 1);
  25966. }
  25967. };
  25968. ActionManager.prototype.getScene = function () {
  25969. return this._scene;
  25970. };
  25971. /**
  25972. * Does this action manager handles actions of any of the given triggers
  25973. * @param {number[]} triggers - the triggers to be tested
  25974. * @return {boolean} whether one (or more) of the triggers is handeled
  25975. */
  25976. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25977. for (var index = 0; index < this.actions.length; index++) {
  25978. var action = this.actions[index];
  25979. if (triggers.indexOf(action.trigger) > -1) {
  25980. return true;
  25981. }
  25982. }
  25983. return false;
  25984. };
  25985. /**
  25986. * Does this action manager handles actions of a given trigger
  25987. * @param {number} trigger - the trigger to be tested
  25988. * @return {boolean} whether the trigger is handeled
  25989. */
  25990. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25991. for (var index = 0; index < this.actions.length; index++) {
  25992. var action = this.actions[index];
  25993. if (action.trigger === trigger) {
  25994. return true;
  25995. }
  25996. }
  25997. return false;
  25998. };
  25999. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26000. /**
  26001. * Does this action manager has pointer triggers
  26002. * @return {boolean} whether or not it has pointer triggers
  26003. */
  26004. get: function () {
  26005. for (var index = 0; index < this.actions.length; index++) {
  26006. var action = this.actions[index];
  26007. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26008. return true;
  26009. }
  26010. }
  26011. return false;
  26012. },
  26013. enumerable: true,
  26014. configurable: true
  26015. });
  26016. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26017. /**
  26018. * Does this action manager has pick triggers
  26019. * @return {boolean} whether or not it has pick triggers
  26020. */
  26021. get: function () {
  26022. for (var index = 0; index < this.actions.length; index++) {
  26023. var action = this.actions[index];
  26024. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26025. return true;
  26026. }
  26027. }
  26028. return false;
  26029. },
  26030. enumerable: true,
  26031. configurable: true
  26032. });
  26033. /**
  26034. * Registers an action to this action manager
  26035. * @param {BABYLON.Action} action - the action to be registered
  26036. * @return {BABYLON.Action} the action amended (prepared) after registration
  26037. */
  26038. ActionManager.prototype.registerAction = function (action) {
  26039. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26040. if (this.getScene().actionManager !== this) {
  26041. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26042. return null;
  26043. }
  26044. }
  26045. this.actions.push(action);
  26046. action._actionManager = this;
  26047. action._prepare();
  26048. return action;
  26049. };
  26050. /**
  26051. * Process a specific trigger
  26052. * @param {number} trigger - the trigger to process
  26053. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26054. */
  26055. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26056. for (var index = 0; index < this.actions.length; index++) {
  26057. var action = this.actions[index];
  26058. if (action.trigger === trigger) {
  26059. if (trigger === ActionManager.OnKeyUpTrigger
  26060. || trigger === ActionManager.OnKeyDownTrigger) {
  26061. var parameter = action.getTriggerParameter();
  26062. if (parameter) {
  26063. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26064. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26065. if (actualkey !== parameter.toLowerCase()) {
  26066. continue;
  26067. }
  26068. }
  26069. }
  26070. action._executeCurrent(evt);
  26071. }
  26072. }
  26073. };
  26074. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26075. var properties = propertyPath.split(".");
  26076. for (var index = 0; index < properties.length - 1; index++) {
  26077. target = target[properties[index]];
  26078. }
  26079. return target;
  26080. };
  26081. ActionManager.prototype._getProperty = function (propertyPath) {
  26082. var properties = propertyPath.split(".");
  26083. return properties[properties.length - 1];
  26084. };
  26085. ActionManager.Parse = function (parsedActions, object, scene) {
  26086. var actionManager = new BABYLON.ActionManager(scene);
  26087. if (object === null)
  26088. scene.actionManager = actionManager;
  26089. else
  26090. object.actionManager = actionManager;
  26091. // instanciate a new object
  26092. var instanciate = function (name, params) {
  26093. var newInstance = Object.create(BABYLON[name].prototype);
  26094. newInstance.constructor.apply(newInstance, params);
  26095. return newInstance;
  26096. };
  26097. var parseParameter = function (name, value, target, propertyPath) {
  26098. if (propertyPath === null) {
  26099. // String, boolean or float
  26100. var floatValue = parseFloat(value);
  26101. if (value === "true" || value === "false")
  26102. return value === "true";
  26103. else
  26104. return isNaN(floatValue) ? value : floatValue;
  26105. }
  26106. var effectiveTarget = propertyPath.split(".");
  26107. var values = value.split(",");
  26108. // Get effective Target
  26109. for (var i = 0; i < effectiveTarget.length; i++) {
  26110. target = target[effectiveTarget[i]];
  26111. }
  26112. // Return appropriate value with its type
  26113. if (typeof (target) === "boolean")
  26114. return values[0] === "true";
  26115. if (typeof (target) === "string")
  26116. return values[0];
  26117. // Parameters with multiple values such as Vector3 etc.
  26118. var split = new Array();
  26119. for (var i = 0; i < values.length; i++)
  26120. split.push(parseFloat(values[i]));
  26121. if (target instanceof BABYLON.Vector3)
  26122. return BABYLON.Vector3.FromArray(split);
  26123. if (target instanceof BABYLON.Vector4)
  26124. return BABYLON.Vector4.FromArray(split);
  26125. if (target instanceof BABYLON.Color3)
  26126. return BABYLON.Color3.FromArray(split);
  26127. if (target instanceof BABYLON.Color4)
  26128. return BABYLON.Color4.FromArray(split);
  26129. return parseFloat(values[0]);
  26130. };
  26131. // traverse graph per trigger
  26132. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26133. if (combineArray === void 0) { combineArray = null; }
  26134. if (parsedAction.detached)
  26135. return;
  26136. var parameters = new Array();
  26137. var target = null;
  26138. var propertyPath = null;
  26139. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26140. // Parameters
  26141. if (parsedAction.type === 2)
  26142. parameters.push(actionManager);
  26143. else
  26144. parameters.push(trigger);
  26145. if (combine) {
  26146. var actions = new Array();
  26147. for (var j = 0; j < parsedAction.combine.length; j++) {
  26148. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26149. }
  26150. parameters.push(actions);
  26151. }
  26152. else {
  26153. for (var i = 0; i < parsedAction.properties.length; i++) {
  26154. var value = parsedAction.properties[i].value;
  26155. var name = parsedAction.properties[i].name;
  26156. var targetType = parsedAction.properties[i].targetType;
  26157. if (name === "target")
  26158. if (targetType !== null && targetType === "SceneProperties")
  26159. value = target = scene;
  26160. else
  26161. value = target = scene.getNodeByName(value);
  26162. else if (name === "parent")
  26163. value = scene.getNodeByName(value);
  26164. else if (name === "sound")
  26165. value = scene.getSoundByName(value);
  26166. else if (name !== "propertyPath") {
  26167. if (parsedAction.type === 2 && name === "operator")
  26168. value = BABYLON.ValueCondition[value];
  26169. else
  26170. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26171. }
  26172. else {
  26173. propertyPath = value;
  26174. }
  26175. parameters.push(value);
  26176. }
  26177. }
  26178. if (combineArray === null) {
  26179. parameters.push(condition);
  26180. }
  26181. else {
  26182. parameters.push(null);
  26183. }
  26184. // If interpolate value action
  26185. if (parsedAction.name === "InterpolateValueAction") {
  26186. var param = parameters[parameters.length - 2];
  26187. parameters[parameters.length - 1] = param;
  26188. parameters[parameters.length - 2] = condition;
  26189. }
  26190. // Action or condition(s) and not CombineAction
  26191. var newAction = instanciate(parsedAction.name, parameters);
  26192. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26193. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26194. if (action)
  26195. action.then(nothing);
  26196. else
  26197. actionManager.registerAction(nothing);
  26198. action = nothing;
  26199. }
  26200. if (combineArray === null) {
  26201. if (newAction instanceof BABYLON.Condition) {
  26202. condition = newAction;
  26203. newAction = action;
  26204. }
  26205. else {
  26206. condition = null;
  26207. if (action)
  26208. action.then(newAction);
  26209. else
  26210. actionManager.registerAction(newAction);
  26211. }
  26212. }
  26213. else {
  26214. combineArray.push(newAction);
  26215. }
  26216. for (var i = 0; i < parsedAction.children.length; i++)
  26217. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26218. };
  26219. // triggers
  26220. for (var i = 0; i < parsedActions.children.length; i++) {
  26221. var triggerParams;
  26222. var trigger = parsedActions.children[i];
  26223. if (trigger.properties.length > 0) {
  26224. var param = trigger.properties[0].value;
  26225. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26226. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26227. }
  26228. else
  26229. triggerParams = BABYLON.ActionManager[trigger.name];
  26230. for (var j = 0; j < trigger.children.length; j++) {
  26231. if (!trigger.detached)
  26232. traverse(trigger.children[j], triggerParams, null, null);
  26233. }
  26234. }
  26235. };
  26236. // Statics
  26237. ActionManager._NothingTrigger = 0;
  26238. ActionManager._OnPickTrigger = 1;
  26239. ActionManager._OnLeftPickTrigger = 2;
  26240. ActionManager._OnRightPickTrigger = 3;
  26241. ActionManager._OnCenterPickTrigger = 4;
  26242. ActionManager._OnPickDownTrigger = 5;
  26243. ActionManager._OnPickUpTrigger = 6;
  26244. ActionManager._OnLongPressTrigger = 7;
  26245. ActionManager._OnPointerOverTrigger = 8;
  26246. ActionManager._OnPointerOutTrigger = 9;
  26247. ActionManager._OnEveryFrameTrigger = 10;
  26248. ActionManager._OnIntersectionEnterTrigger = 11;
  26249. ActionManager._OnIntersectionExitTrigger = 12;
  26250. ActionManager._OnKeyDownTrigger = 13;
  26251. ActionManager._OnKeyUpTrigger = 14;
  26252. ActionManager.DragMovementThreshold = 10; // in pixels
  26253. ActionManager.LongPressDelay = 500; // in milliseconds
  26254. return ActionManager;
  26255. })();
  26256. BABYLON.ActionManager = ActionManager;
  26257. })(BABYLON || (BABYLON = {}));
  26258. var BABYLON;
  26259. (function (BABYLON) {
  26260. var InterpolateValueAction = (function (_super) {
  26261. __extends(InterpolateValueAction, _super);
  26262. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26263. if (duration === void 0) { duration = 1000; }
  26264. _super.call(this, triggerOptions, condition);
  26265. this.propertyPath = propertyPath;
  26266. this.value = value;
  26267. this.duration = duration;
  26268. this.stopOtherAnimations = stopOtherAnimations;
  26269. this.onInterpolationDone = onInterpolationDone;
  26270. this._target = target;
  26271. }
  26272. InterpolateValueAction.prototype._prepare = function () {
  26273. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26274. this._property = this._getProperty(this.propertyPath);
  26275. };
  26276. InterpolateValueAction.prototype.execute = function () {
  26277. var scene = this._actionManager.getScene();
  26278. var keys = [
  26279. {
  26280. frame: 0,
  26281. value: this._target[this._property]
  26282. }, {
  26283. frame: 100,
  26284. value: this.value
  26285. }
  26286. ];
  26287. var dataType;
  26288. if (typeof this.value === "number") {
  26289. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26290. }
  26291. else if (this.value instanceof BABYLON.Color3) {
  26292. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26293. }
  26294. else if (this.value instanceof BABYLON.Vector3) {
  26295. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26296. }
  26297. else if (this.value instanceof BABYLON.Matrix) {
  26298. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26299. }
  26300. else if (this.value instanceof BABYLON.Quaternion) {
  26301. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26302. }
  26303. else {
  26304. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26305. return;
  26306. }
  26307. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26308. animation.setKeys(keys);
  26309. if (this.stopOtherAnimations) {
  26310. scene.stopAnimation(this._target);
  26311. }
  26312. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26313. };
  26314. return InterpolateValueAction;
  26315. })(BABYLON.Action);
  26316. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26317. })(BABYLON || (BABYLON = {}));
  26318. var BABYLON;
  26319. (function (BABYLON) {
  26320. var SwitchBooleanAction = (function (_super) {
  26321. __extends(SwitchBooleanAction, _super);
  26322. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26323. _super.call(this, triggerOptions, condition);
  26324. this.propertyPath = propertyPath;
  26325. this._target = target;
  26326. }
  26327. SwitchBooleanAction.prototype._prepare = function () {
  26328. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26329. this._property = this._getProperty(this.propertyPath);
  26330. };
  26331. SwitchBooleanAction.prototype.execute = function () {
  26332. this._target[this._property] = !this._target[this._property];
  26333. };
  26334. return SwitchBooleanAction;
  26335. })(BABYLON.Action);
  26336. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26337. var SetStateAction = (function (_super) {
  26338. __extends(SetStateAction, _super);
  26339. function SetStateAction(triggerOptions, target, value, condition) {
  26340. _super.call(this, triggerOptions, condition);
  26341. this.value = value;
  26342. this._target = target;
  26343. }
  26344. SetStateAction.prototype.execute = function () {
  26345. this._target.state = this.value;
  26346. };
  26347. return SetStateAction;
  26348. })(BABYLON.Action);
  26349. BABYLON.SetStateAction = SetStateAction;
  26350. var SetValueAction = (function (_super) {
  26351. __extends(SetValueAction, _super);
  26352. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26353. _super.call(this, triggerOptions, condition);
  26354. this.propertyPath = propertyPath;
  26355. this.value = value;
  26356. this._target = target;
  26357. }
  26358. SetValueAction.prototype._prepare = function () {
  26359. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26360. this._property = this._getProperty(this.propertyPath);
  26361. };
  26362. SetValueAction.prototype.execute = function () {
  26363. this._target[this._property] = this.value;
  26364. };
  26365. return SetValueAction;
  26366. })(BABYLON.Action);
  26367. BABYLON.SetValueAction = SetValueAction;
  26368. var IncrementValueAction = (function (_super) {
  26369. __extends(IncrementValueAction, _super);
  26370. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26371. _super.call(this, triggerOptions, condition);
  26372. this.propertyPath = propertyPath;
  26373. this.value = value;
  26374. this._target = target;
  26375. }
  26376. IncrementValueAction.prototype._prepare = function () {
  26377. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26378. this._property = this._getProperty(this.propertyPath);
  26379. if (typeof this._target[this._property] !== "number") {
  26380. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26381. }
  26382. };
  26383. IncrementValueAction.prototype.execute = function () {
  26384. this._target[this._property] += this.value;
  26385. };
  26386. return IncrementValueAction;
  26387. })(BABYLON.Action);
  26388. BABYLON.IncrementValueAction = IncrementValueAction;
  26389. var PlayAnimationAction = (function (_super) {
  26390. __extends(PlayAnimationAction, _super);
  26391. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26392. _super.call(this, triggerOptions, condition);
  26393. this.from = from;
  26394. this.to = to;
  26395. this.loop = loop;
  26396. this._target = target;
  26397. }
  26398. PlayAnimationAction.prototype._prepare = function () {
  26399. };
  26400. PlayAnimationAction.prototype.execute = function () {
  26401. var scene = this._actionManager.getScene();
  26402. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26403. };
  26404. return PlayAnimationAction;
  26405. })(BABYLON.Action);
  26406. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26407. var StopAnimationAction = (function (_super) {
  26408. __extends(StopAnimationAction, _super);
  26409. function StopAnimationAction(triggerOptions, target, condition) {
  26410. _super.call(this, triggerOptions, condition);
  26411. this._target = target;
  26412. }
  26413. StopAnimationAction.prototype._prepare = function () {
  26414. };
  26415. StopAnimationAction.prototype.execute = function () {
  26416. var scene = this._actionManager.getScene();
  26417. scene.stopAnimation(this._target);
  26418. };
  26419. return StopAnimationAction;
  26420. })(BABYLON.Action);
  26421. BABYLON.StopAnimationAction = StopAnimationAction;
  26422. var DoNothingAction = (function (_super) {
  26423. __extends(DoNothingAction, _super);
  26424. function DoNothingAction(triggerOptions, condition) {
  26425. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26426. _super.call(this, triggerOptions, condition);
  26427. }
  26428. DoNothingAction.prototype.execute = function () {
  26429. };
  26430. return DoNothingAction;
  26431. })(BABYLON.Action);
  26432. BABYLON.DoNothingAction = DoNothingAction;
  26433. var CombineAction = (function (_super) {
  26434. __extends(CombineAction, _super);
  26435. function CombineAction(triggerOptions, children, condition) {
  26436. _super.call(this, triggerOptions, condition);
  26437. this.children = children;
  26438. }
  26439. CombineAction.prototype._prepare = function () {
  26440. for (var index = 0; index < this.children.length; index++) {
  26441. this.children[index]._actionManager = this._actionManager;
  26442. this.children[index]._prepare();
  26443. }
  26444. };
  26445. CombineAction.prototype.execute = function (evt) {
  26446. for (var index = 0; index < this.children.length; index++) {
  26447. this.children[index].execute(evt);
  26448. }
  26449. };
  26450. return CombineAction;
  26451. })(BABYLON.Action);
  26452. BABYLON.CombineAction = CombineAction;
  26453. var ExecuteCodeAction = (function (_super) {
  26454. __extends(ExecuteCodeAction, _super);
  26455. function ExecuteCodeAction(triggerOptions, func, condition) {
  26456. _super.call(this, triggerOptions, condition);
  26457. this.func = func;
  26458. }
  26459. ExecuteCodeAction.prototype.execute = function (evt) {
  26460. this.func(evt);
  26461. };
  26462. return ExecuteCodeAction;
  26463. })(BABYLON.Action);
  26464. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26465. var SetParentAction = (function (_super) {
  26466. __extends(SetParentAction, _super);
  26467. function SetParentAction(triggerOptions, target, parent, condition) {
  26468. _super.call(this, triggerOptions, condition);
  26469. this._target = target;
  26470. this._parent = parent;
  26471. }
  26472. SetParentAction.prototype._prepare = function () {
  26473. };
  26474. SetParentAction.prototype.execute = function () {
  26475. if (this._target.parent === this._parent) {
  26476. return;
  26477. }
  26478. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26479. invertParentWorldMatrix.invert();
  26480. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26481. this._target.parent = this._parent;
  26482. };
  26483. return SetParentAction;
  26484. })(BABYLON.Action);
  26485. BABYLON.SetParentAction = SetParentAction;
  26486. var PlaySoundAction = (function (_super) {
  26487. __extends(PlaySoundAction, _super);
  26488. function PlaySoundAction(triggerOptions, sound, condition) {
  26489. _super.call(this, triggerOptions, condition);
  26490. this._sound = sound;
  26491. }
  26492. PlaySoundAction.prototype._prepare = function () {
  26493. };
  26494. PlaySoundAction.prototype.execute = function () {
  26495. if (this._sound !== undefined)
  26496. this._sound.play();
  26497. };
  26498. return PlaySoundAction;
  26499. })(BABYLON.Action);
  26500. BABYLON.PlaySoundAction = PlaySoundAction;
  26501. var StopSoundAction = (function (_super) {
  26502. __extends(StopSoundAction, _super);
  26503. function StopSoundAction(triggerOptions, sound, condition) {
  26504. _super.call(this, triggerOptions, condition);
  26505. this._sound = sound;
  26506. }
  26507. StopSoundAction.prototype._prepare = function () {
  26508. };
  26509. StopSoundAction.prototype.execute = function () {
  26510. if (this._sound !== undefined)
  26511. this._sound.stop();
  26512. };
  26513. return StopSoundAction;
  26514. })(BABYLON.Action);
  26515. BABYLON.StopSoundAction = StopSoundAction;
  26516. })(BABYLON || (BABYLON = {}));
  26517. var BABYLON;
  26518. (function (BABYLON) {
  26519. var Geometry = (function () {
  26520. function Geometry(id, scene, vertexData, updatable, mesh) {
  26521. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26522. this._totalVertices = 0;
  26523. this._isDisposed = false;
  26524. this.id = id;
  26525. this._engine = scene.getEngine();
  26526. this._meshes = [];
  26527. this._scene = scene;
  26528. //Init vertex buffer cache
  26529. this._vertexBuffers = {};
  26530. this._indices = [];
  26531. // vertexData
  26532. if (vertexData) {
  26533. this.setAllVerticesData(vertexData, updatable);
  26534. }
  26535. else {
  26536. this._totalVertices = 0;
  26537. this._indices = [];
  26538. }
  26539. // applyToMesh
  26540. if (mesh) {
  26541. this.applyToMesh(mesh);
  26542. mesh.computeWorldMatrix(true);
  26543. }
  26544. }
  26545. Object.defineProperty(Geometry.prototype, "extend", {
  26546. get: function () {
  26547. return this._extend;
  26548. },
  26549. enumerable: true,
  26550. configurable: true
  26551. });
  26552. Geometry.prototype.getScene = function () {
  26553. return this._scene;
  26554. };
  26555. Geometry.prototype.getEngine = function () {
  26556. return this._engine;
  26557. };
  26558. Geometry.prototype.isReady = function () {
  26559. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26560. };
  26561. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26562. vertexData.applyToGeometry(this, updatable);
  26563. this.notifyUpdate();
  26564. };
  26565. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26566. if (this._vertexBuffers[kind]) {
  26567. this._vertexBuffers[kind].dispose();
  26568. }
  26569. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26570. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26571. stride = this._vertexBuffers[kind].getStrideSize();
  26572. this._totalVertices = data.length / stride;
  26573. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26574. var meshes = this._meshes;
  26575. var numOfMeshes = meshes.length;
  26576. for (var index = 0; index < numOfMeshes; index++) {
  26577. var mesh = meshes[index];
  26578. mesh._resetPointsArrayCache();
  26579. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26580. mesh._createGlobalSubMesh();
  26581. mesh.computeWorldMatrix(true);
  26582. }
  26583. }
  26584. this.notifyUpdate(kind);
  26585. };
  26586. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26587. var vertexBuffer = this.getVertexBuffer(kind);
  26588. if (!vertexBuffer) {
  26589. return;
  26590. }
  26591. vertexBuffer.updateDirectly(data, offset);
  26592. this.notifyUpdate(kind);
  26593. };
  26594. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26595. var vertexBuffer = this.getVertexBuffer(kind);
  26596. if (!vertexBuffer) {
  26597. return;
  26598. }
  26599. vertexBuffer.update(data);
  26600. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26601. var stride = vertexBuffer.getStrideSize();
  26602. this._totalVertices = data.length / stride;
  26603. if (updateExtends) {
  26604. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26605. }
  26606. var meshes = this._meshes;
  26607. var numOfMeshes = meshes.length;
  26608. for (var index = 0; index < numOfMeshes; index++) {
  26609. var mesh = meshes[index];
  26610. mesh._resetPointsArrayCache();
  26611. if (updateExtends) {
  26612. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26613. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26614. var subMesh = mesh.subMeshes[subIndex];
  26615. subMesh.refreshBoundingInfo();
  26616. }
  26617. }
  26618. }
  26619. }
  26620. this.notifyUpdate(kind);
  26621. };
  26622. Geometry.prototype.getTotalVertices = function () {
  26623. if (!this.isReady()) {
  26624. return 0;
  26625. }
  26626. return this._totalVertices;
  26627. };
  26628. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26629. var vertexBuffer = this.getVertexBuffer(kind);
  26630. if (!vertexBuffer) {
  26631. return null;
  26632. }
  26633. var orig = vertexBuffer.getData();
  26634. if (!copyWhenShared || this._meshes.length === 1) {
  26635. return orig;
  26636. }
  26637. else {
  26638. var len = orig.length;
  26639. var copy = [];
  26640. for (var i = 0; i < len; i++) {
  26641. copy.push(orig[i]);
  26642. }
  26643. return copy;
  26644. }
  26645. };
  26646. Geometry.prototype.getVertexBuffer = function (kind) {
  26647. if (!this.isReady()) {
  26648. return null;
  26649. }
  26650. return this._vertexBuffers[kind];
  26651. };
  26652. Geometry.prototype.getVertexBuffers = function () {
  26653. if (!this.isReady()) {
  26654. return null;
  26655. }
  26656. return this._vertexBuffers;
  26657. };
  26658. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26659. if (!this._vertexBuffers) {
  26660. if (this._delayInfo) {
  26661. return this._delayInfo.indexOf(kind) !== -1;
  26662. }
  26663. return false;
  26664. }
  26665. return this._vertexBuffers[kind] !== undefined;
  26666. };
  26667. Geometry.prototype.getVerticesDataKinds = function () {
  26668. var result = [];
  26669. var kind;
  26670. if (!this._vertexBuffers && this._delayInfo) {
  26671. for (kind in this._delayInfo) {
  26672. result.push(kind);
  26673. }
  26674. }
  26675. else {
  26676. for (kind in this._vertexBuffers) {
  26677. result.push(kind);
  26678. }
  26679. }
  26680. return result;
  26681. };
  26682. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26683. if (this._indexBuffer) {
  26684. this._engine._releaseBuffer(this._indexBuffer);
  26685. }
  26686. this._indices = indices;
  26687. if (this._meshes.length !== 0 && this._indices) {
  26688. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26689. }
  26690. if (totalVertices !== undefined) {
  26691. this._totalVertices = totalVertices;
  26692. }
  26693. var meshes = this._meshes;
  26694. var numOfMeshes = meshes.length;
  26695. for (var index = 0; index < numOfMeshes; index++) {
  26696. meshes[index]._createGlobalSubMesh();
  26697. }
  26698. this.notifyUpdate();
  26699. };
  26700. Geometry.prototype.getTotalIndices = function () {
  26701. if (!this.isReady()) {
  26702. return 0;
  26703. }
  26704. return this._indices.length;
  26705. };
  26706. Geometry.prototype.getIndices = function (copyWhenShared) {
  26707. if (!this.isReady()) {
  26708. return null;
  26709. }
  26710. var orig = this._indices;
  26711. if (!copyWhenShared || this._meshes.length === 1) {
  26712. return orig;
  26713. }
  26714. else {
  26715. var len = orig.length;
  26716. var copy = [];
  26717. for (var i = 0; i < len; i++) {
  26718. copy.push(orig[i]);
  26719. }
  26720. return copy;
  26721. }
  26722. };
  26723. Geometry.prototype.getIndexBuffer = function () {
  26724. if (!this.isReady()) {
  26725. return null;
  26726. }
  26727. return this._indexBuffer;
  26728. };
  26729. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26730. var meshes = this._meshes;
  26731. var index = meshes.indexOf(mesh);
  26732. if (index === -1) {
  26733. return;
  26734. }
  26735. for (var kind in this._vertexBuffers) {
  26736. this._vertexBuffers[kind].dispose();
  26737. }
  26738. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26739. this._indexBuffer = null;
  26740. }
  26741. meshes.splice(index, 1);
  26742. mesh._geometry = null;
  26743. if (meshes.length === 0 && shouldDispose) {
  26744. this.dispose();
  26745. }
  26746. };
  26747. Geometry.prototype.applyToMesh = function (mesh) {
  26748. if (mesh._geometry === this) {
  26749. return;
  26750. }
  26751. var previousGeometry = mesh._geometry;
  26752. if (previousGeometry) {
  26753. previousGeometry.releaseForMesh(mesh);
  26754. }
  26755. var meshes = this._meshes;
  26756. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26757. mesh._geometry = this;
  26758. this._scene.pushGeometry(this);
  26759. meshes.push(mesh);
  26760. if (this.isReady()) {
  26761. this._applyToMesh(mesh);
  26762. }
  26763. else {
  26764. mesh._boundingInfo = this._boundingInfo;
  26765. }
  26766. };
  26767. Geometry.prototype._applyToMesh = function (mesh) {
  26768. var numOfMeshes = this._meshes.length;
  26769. // vertexBuffers
  26770. for (var kind in this._vertexBuffers) {
  26771. if (numOfMeshes === 1) {
  26772. this._vertexBuffers[kind].create();
  26773. }
  26774. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26775. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26776. mesh._resetPointsArrayCache();
  26777. if (!this._extend) {
  26778. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26779. }
  26780. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26781. mesh._createGlobalSubMesh();
  26782. //bounding info was just created again, world matrix should be applied again.
  26783. mesh._updateBoundingInfo();
  26784. }
  26785. }
  26786. // indexBuffer
  26787. if (numOfMeshes === 1 && this._indices) {
  26788. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26789. }
  26790. if (this._indexBuffer) {
  26791. this._indexBuffer.references = numOfMeshes;
  26792. }
  26793. };
  26794. Geometry.prototype.notifyUpdate = function (kind) {
  26795. if (this.onGeometryUpdated) {
  26796. this.onGeometryUpdated(this, kind);
  26797. }
  26798. };
  26799. Geometry.prototype.load = function (scene, onLoaded) {
  26800. var _this = this;
  26801. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26802. return;
  26803. }
  26804. if (this.isReady()) {
  26805. if (onLoaded) {
  26806. onLoaded();
  26807. }
  26808. return;
  26809. }
  26810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26811. scene._addPendingData(this);
  26812. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26813. _this._delayLoadingFunction(JSON.parse(data), _this);
  26814. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26815. _this._delayInfo = [];
  26816. scene._removePendingData(_this);
  26817. var meshes = _this._meshes;
  26818. var numOfMeshes = meshes.length;
  26819. for (var index = 0; index < numOfMeshes; index++) {
  26820. _this._applyToMesh(meshes[index]);
  26821. }
  26822. if (onLoaded) {
  26823. onLoaded();
  26824. }
  26825. }, function () { }, scene.database);
  26826. };
  26827. Geometry.prototype.isDisposed = function () {
  26828. return this._isDisposed;
  26829. };
  26830. Geometry.prototype.dispose = function () {
  26831. var meshes = this._meshes;
  26832. var numOfMeshes = meshes.length;
  26833. var index;
  26834. for (index = 0; index < numOfMeshes; index++) {
  26835. this.releaseForMesh(meshes[index]);
  26836. }
  26837. this._meshes = [];
  26838. for (var kind in this._vertexBuffers) {
  26839. this._vertexBuffers[kind].dispose();
  26840. }
  26841. this._vertexBuffers = [];
  26842. this._totalVertices = 0;
  26843. if (this._indexBuffer) {
  26844. this._engine._releaseBuffer(this._indexBuffer);
  26845. }
  26846. this._indexBuffer = null;
  26847. this._indices = [];
  26848. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26849. this.delayLoadingFile = null;
  26850. this._delayLoadingFunction = null;
  26851. this._delayInfo = [];
  26852. this._boundingInfo = null;
  26853. this._scene.removeGeometry(this);
  26854. this._isDisposed = true;
  26855. };
  26856. Geometry.prototype.copy = function (id) {
  26857. var vertexData = new BABYLON.VertexData();
  26858. vertexData.indices = [];
  26859. var indices = this.getIndices();
  26860. for (var index = 0; index < indices.length; index++) {
  26861. vertexData.indices.push(indices[index]);
  26862. }
  26863. var updatable = false;
  26864. var stopChecking = false;
  26865. var kind;
  26866. for (kind in this._vertexBuffers) {
  26867. // using slice() to make a copy of the array and not just reference it
  26868. var data = this.getVerticesData(kind);
  26869. if (data instanceof Float32Array) {
  26870. vertexData.set(new Float32Array(data), kind);
  26871. }
  26872. else {
  26873. vertexData.set(data.slice(0), kind);
  26874. }
  26875. if (!stopChecking) {
  26876. updatable = this.getVertexBuffer(kind).isUpdatable();
  26877. stopChecking = !updatable;
  26878. }
  26879. }
  26880. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26881. geometry.delayLoadState = this.delayLoadState;
  26882. geometry.delayLoadingFile = this.delayLoadingFile;
  26883. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26884. for (kind in this._delayInfo) {
  26885. geometry._delayInfo = geometry._delayInfo || [];
  26886. geometry._delayInfo.push(kind);
  26887. }
  26888. // Bounding info
  26889. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26890. return geometry;
  26891. };
  26892. Geometry.prototype.serialize = function () {
  26893. var serializationObject = {};
  26894. serializationObject.id = this.id;
  26895. if (BABYLON.Tags.HasTags(this)) {
  26896. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26897. }
  26898. return serializationObject;
  26899. };
  26900. Geometry.prototype.serializeVerticeData = function () {
  26901. var serializationObject = this.serialize();
  26902. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26903. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26904. }
  26905. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26906. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26907. }
  26908. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26909. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26910. }
  26911. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26912. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26913. }
  26914. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26915. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26916. }
  26917. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26918. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26919. }
  26920. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26921. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26922. }
  26923. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26924. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26925. }
  26926. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26927. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26928. }
  26929. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26930. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26931. serializationObject.matricesIndices._isExpanded = true;
  26932. }
  26933. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26934. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26935. }
  26936. serializationObject.indices = this.getIndices();
  26937. return serializationObject;
  26938. };
  26939. // Statics
  26940. Geometry.ExtractFromMesh = function (mesh, id) {
  26941. var geometry = mesh._geometry;
  26942. if (!geometry) {
  26943. return null;
  26944. }
  26945. return geometry.copy(id);
  26946. };
  26947. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26948. // be aware Math.random() could cause collisions
  26949. Geometry.RandomId = function () {
  26950. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26951. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26952. return v.toString(16);
  26953. });
  26954. };
  26955. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26956. var scene = mesh.getScene();
  26957. // Geometry
  26958. var geometryId = parsedGeometry.geometryId;
  26959. if (geometryId) {
  26960. var geometry = scene.getGeometryByID(geometryId);
  26961. if (geometry) {
  26962. geometry.applyToMesh(mesh);
  26963. }
  26964. }
  26965. else if (parsedGeometry instanceof ArrayBuffer) {
  26966. var binaryInfo = mesh._binaryInfo;
  26967. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26968. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26969. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26970. }
  26971. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26972. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26973. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26974. }
  26975. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26976. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26977. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26978. }
  26979. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26980. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26981. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26982. }
  26983. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26984. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26985. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26986. }
  26987. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26988. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26989. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26990. }
  26991. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26992. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26993. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26994. }
  26995. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26996. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26997. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26998. }
  26999. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27000. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27001. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27002. }
  27003. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27004. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27005. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27006. }
  27007. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27008. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27010. }
  27011. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27012. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27013. mesh.setIndices(indicesData);
  27014. }
  27015. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27016. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27017. mesh.subMeshes = [];
  27018. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27019. var materialIndex = subMeshesData[(i * 5) + 0];
  27020. var verticesStart = subMeshesData[(i * 5) + 1];
  27021. var verticesCount = subMeshesData[(i * 5) + 2];
  27022. var indexStart = subMeshesData[(i * 5) + 3];
  27023. var indexCount = subMeshesData[(i * 5) + 4];
  27024. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27025. }
  27026. }
  27027. }
  27028. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27029. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27030. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27031. if (parsedGeometry.uvs) {
  27032. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27033. }
  27034. if (parsedGeometry.uvs2) {
  27035. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27036. }
  27037. if (parsedGeometry.uvs3) {
  27038. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27039. }
  27040. if (parsedGeometry.uvs4) {
  27041. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27042. }
  27043. if (parsedGeometry.uvs5) {
  27044. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27045. }
  27046. if (parsedGeometry.uvs6) {
  27047. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27048. }
  27049. if (parsedGeometry.colors) {
  27050. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27051. }
  27052. if (parsedGeometry.matricesIndices) {
  27053. if (!parsedGeometry.matricesIndices._isExpanded) {
  27054. var floatIndices = [];
  27055. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27056. var matricesIndex = parsedGeometry.matricesIndices[i];
  27057. floatIndices.push(matricesIndex & 0x000000FF);
  27058. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27059. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27060. floatIndices.push(matricesIndex >> 24);
  27061. }
  27062. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27063. }
  27064. else {
  27065. delete parsedGeometry.matricesIndices._isExpanded;
  27066. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27067. }
  27068. }
  27069. if (parsedGeometry.matricesIndicesExtra) {
  27070. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27071. var floatIndices = [];
  27072. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27073. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27074. floatIndices.push(matricesIndex & 0x000000FF);
  27075. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27076. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27077. floatIndices.push(matricesIndex >> 24);
  27078. }
  27079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27080. }
  27081. else {
  27082. delete parsedGeometry.matricesIndices._isExpanded;
  27083. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27084. }
  27085. }
  27086. if (parsedGeometry.matricesWeights) {
  27087. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27088. }
  27089. if (parsedGeometry.matricesWeightsExtra) {
  27090. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27091. }
  27092. mesh.setIndices(parsedGeometry.indices);
  27093. }
  27094. // SubMeshes
  27095. if (parsedGeometry.subMeshes) {
  27096. mesh.subMeshes = [];
  27097. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27098. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27099. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27100. }
  27101. }
  27102. // Flat shading
  27103. if (mesh._shouldGenerateFlatShading) {
  27104. mesh.convertToFlatShadedMesh();
  27105. delete mesh._shouldGenerateFlatShading;
  27106. }
  27107. // Update
  27108. mesh.computeWorldMatrix(true);
  27109. // Octree
  27110. if (scene['_selectionOctree']) {
  27111. scene['_selectionOctree'].addMesh(mesh);
  27112. }
  27113. };
  27114. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27115. if (scene.getGeometryByID(parsedVertexData.id)) {
  27116. return null; // null since geometry could be something else than a box...
  27117. }
  27118. var geometry = new Geometry(parsedVertexData.id, scene);
  27119. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27120. if (parsedVertexData.delayLoadingFile) {
  27121. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27122. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27123. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27124. geometry._delayInfo = [];
  27125. if (parsedVertexData.hasUVs) {
  27126. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27127. }
  27128. if (parsedVertexData.hasUVs2) {
  27129. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27130. }
  27131. if (parsedVertexData.hasUVs3) {
  27132. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27133. }
  27134. if (parsedVertexData.hasUVs4) {
  27135. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27136. }
  27137. if (parsedVertexData.hasUVs5) {
  27138. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27139. }
  27140. if (parsedVertexData.hasUVs6) {
  27141. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27142. }
  27143. if (parsedVertexData.hasColors) {
  27144. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27145. }
  27146. if (parsedVertexData.hasMatricesIndices) {
  27147. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27148. }
  27149. if (parsedVertexData.hasMatricesWeights) {
  27150. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27151. }
  27152. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27153. }
  27154. else {
  27155. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27156. }
  27157. scene.pushGeometry(geometry, true);
  27158. return geometry;
  27159. };
  27160. return Geometry;
  27161. })();
  27162. BABYLON.Geometry = Geometry;
  27163. /////// Primitives //////////////////////////////////////////////
  27164. var Geometry;
  27165. (function (Geometry) {
  27166. var Primitives;
  27167. (function (Primitives) {
  27168. /// Abstract class
  27169. var _Primitive = (function (_super) {
  27170. __extends(_Primitive, _super);
  27171. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27172. this._beingRegenerated = true;
  27173. this._canBeRegenerated = canBeRegenerated;
  27174. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27175. this._beingRegenerated = false;
  27176. }
  27177. _Primitive.prototype.canBeRegenerated = function () {
  27178. return this._canBeRegenerated;
  27179. };
  27180. _Primitive.prototype.regenerate = function () {
  27181. if (!this._canBeRegenerated) {
  27182. return;
  27183. }
  27184. this._beingRegenerated = true;
  27185. this.setAllVerticesData(this._regenerateVertexData(), false);
  27186. this._beingRegenerated = false;
  27187. };
  27188. _Primitive.prototype.asNewGeometry = function (id) {
  27189. return _super.prototype.copy.call(this, id);
  27190. };
  27191. // overrides
  27192. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27193. if (!this._beingRegenerated) {
  27194. return;
  27195. }
  27196. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27197. };
  27198. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27199. if (!this._beingRegenerated) {
  27200. return;
  27201. }
  27202. _super.prototype.setVerticesData.call(this, kind, data, false);
  27203. };
  27204. // to override
  27205. // protected
  27206. _Primitive.prototype._regenerateVertexData = function () {
  27207. throw new Error("Abstract method");
  27208. };
  27209. _Primitive.prototype.copy = function (id) {
  27210. throw new Error("Must be overriden in sub-classes.");
  27211. };
  27212. _Primitive.prototype.serialize = function () {
  27213. var serializationObject = _super.prototype.serialize.call(this);
  27214. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27215. return serializationObject;
  27216. };
  27217. return _Primitive;
  27218. })(Geometry);
  27219. Primitives._Primitive = _Primitive;
  27220. var Ribbon = (function (_super) {
  27221. __extends(Ribbon, _super);
  27222. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27223. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27224. this.pathArray = pathArray;
  27225. this.closeArray = closeArray;
  27226. this.closePath = closePath;
  27227. this.offset = offset;
  27228. this.side = side;
  27229. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27230. }
  27231. Ribbon.prototype._regenerateVertexData = function () {
  27232. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27233. };
  27234. Ribbon.prototype.copy = function (id) {
  27235. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27236. };
  27237. return Ribbon;
  27238. })(_Primitive);
  27239. Primitives.Ribbon = Ribbon;
  27240. var Box = (function (_super) {
  27241. __extends(Box, _super);
  27242. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27243. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27244. this.size = size;
  27245. this.side = side;
  27246. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27247. }
  27248. Box.prototype._regenerateVertexData = function () {
  27249. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27250. };
  27251. Box.prototype.copy = function (id) {
  27252. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27253. };
  27254. Box.prototype.serialize = function () {
  27255. var serializationObject = _super.prototype.serialize.call(this);
  27256. serializationObject.size = this.size;
  27257. return serializationObject;
  27258. };
  27259. Box.Parse = function (parsedBox, scene) {
  27260. if (scene.getGeometryByID(parsedBox.id)) {
  27261. return null; // null since geometry could be something else than a box...
  27262. }
  27263. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27264. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27265. scene.pushGeometry(box, true);
  27266. return box;
  27267. };
  27268. return Box;
  27269. })(_Primitive);
  27270. Primitives.Box = Box;
  27271. var Sphere = (function (_super) {
  27272. __extends(Sphere, _super);
  27273. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27274. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27275. this.segments = segments;
  27276. this.diameter = diameter;
  27277. this.side = side;
  27278. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27279. }
  27280. Sphere.prototype._regenerateVertexData = function () {
  27281. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27282. };
  27283. Sphere.prototype.copy = function (id) {
  27284. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27285. };
  27286. Sphere.prototype.serialize = function () {
  27287. var serializationObject = _super.prototype.serialize.call(this);
  27288. serializationObject.segments = this.segments;
  27289. serializationObject.diameter = this.diameter;
  27290. return serializationObject;
  27291. };
  27292. Sphere.Parse = function (parsedSphere, scene) {
  27293. if (scene.getGeometryByID(parsedSphere.id)) {
  27294. return null; // null since geometry could be something else than a sphere...
  27295. }
  27296. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27297. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27298. scene.pushGeometry(sphere, true);
  27299. return sphere;
  27300. };
  27301. return Sphere;
  27302. })(_Primitive);
  27303. Primitives.Sphere = Sphere;
  27304. var Disc = (function (_super) {
  27305. __extends(Disc, _super);
  27306. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27307. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27308. this.radius = radius;
  27309. this.tessellation = tessellation;
  27310. this.side = side;
  27311. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27312. }
  27313. Disc.prototype._regenerateVertexData = function () {
  27314. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27315. };
  27316. Disc.prototype.copy = function (id) {
  27317. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27318. };
  27319. return Disc;
  27320. })(_Primitive);
  27321. Primitives.Disc = Disc;
  27322. var Cylinder = (function (_super) {
  27323. __extends(Cylinder, _super);
  27324. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27325. if (subdivisions === void 0) { subdivisions = 1; }
  27326. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27327. this.height = height;
  27328. this.diameterTop = diameterTop;
  27329. this.diameterBottom = diameterBottom;
  27330. this.tessellation = tessellation;
  27331. this.subdivisions = subdivisions;
  27332. this.side = side;
  27333. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27334. }
  27335. Cylinder.prototype._regenerateVertexData = function () {
  27336. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27337. };
  27338. Cylinder.prototype.copy = function (id) {
  27339. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27340. };
  27341. Cylinder.prototype.serialize = function () {
  27342. var serializationObject = _super.prototype.serialize.call(this);
  27343. serializationObject.height = this.height;
  27344. serializationObject.diameterTop = this.diameterTop;
  27345. serializationObject.diameterBottom = this.diameterBottom;
  27346. serializationObject.tessellation = this.tessellation;
  27347. return serializationObject;
  27348. };
  27349. Cylinder.Parse = function (parsedCylinder, scene) {
  27350. if (scene.getGeometryByID(parsedCylinder.id)) {
  27351. return null; // null since geometry could be something else than a cylinder...
  27352. }
  27353. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27354. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27355. scene.pushGeometry(cylinder, true);
  27356. return cylinder;
  27357. };
  27358. return Cylinder;
  27359. })(_Primitive);
  27360. Primitives.Cylinder = Cylinder;
  27361. var Torus = (function (_super) {
  27362. __extends(Torus, _super);
  27363. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27364. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27365. this.diameter = diameter;
  27366. this.thickness = thickness;
  27367. this.tessellation = tessellation;
  27368. this.side = side;
  27369. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27370. }
  27371. Torus.prototype._regenerateVertexData = function () {
  27372. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27373. };
  27374. Torus.prototype.copy = function (id) {
  27375. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27376. };
  27377. Torus.prototype.serialize = function () {
  27378. var serializationObject = _super.prototype.serialize.call(this);
  27379. serializationObject.diameter = this.diameter;
  27380. serializationObject.thickness = this.thickness;
  27381. serializationObject.tessellation = this.tessellation;
  27382. return serializationObject;
  27383. };
  27384. Torus.Parse = function (parsedTorus, scene) {
  27385. if (scene.getGeometryByID(parsedTorus.id)) {
  27386. return null; // null since geometry could be something else than a torus...
  27387. }
  27388. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27389. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27390. scene.pushGeometry(torus, true);
  27391. return torus;
  27392. };
  27393. return Torus;
  27394. })(_Primitive);
  27395. Primitives.Torus = Torus;
  27396. var Ground = (function (_super) {
  27397. __extends(Ground, _super);
  27398. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27399. this.width = width;
  27400. this.height = height;
  27401. this.subdivisions = subdivisions;
  27402. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27403. }
  27404. Ground.prototype._regenerateVertexData = function () {
  27405. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27406. };
  27407. Ground.prototype.copy = function (id) {
  27408. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27409. };
  27410. Ground.prototype.serialize = function () {
  27411. var serializationObject = _super.prototype.serialize.call(this);
  27412. serializationObject.width = this.width;
  27413. serializationObject.height = this.height;
  27414. serializationObject.subdivisions = this.subdivisions;
  27415. return serializationObject;
  27416. };
  27417. Ground.Parse = function (parsedGround, scene) {
  27418. if (scene.getGeometryByID(parsedGround.id)) {
  27419. return null; // null since geometry could be something else than a ground...
  27420. }
  27421. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27422. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27423. scene.pushGeometry(ground, true);
  27424. return ground;
  27425. };
  27426. return Ground;
  27427. })(_Primitive);
  27428. Primitives.Ground = Ground;
  27429. var TiledGround = (function (_super) {
  27430. __extends(TiledGround, _super);
  27431. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27432. this.xmin = xmin;
  27433. this.zmin = zmin;
  27434. this.xmax = xmax;
  27435. this.zmax = zmax;
  27436. this.subdivisions = subdivisions;
  27437. this.precision = precision;
  27438. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27439. }
  27440. TiledGround.prototype._regenerateVertexData = function () {
  27441. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27442. };
  27443. TiledGround.prototype.copy = function (id) {
  27444. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27445. };
  27446. return TiledGround;
  27447. })(_Primitive);
  27448. Primitives.TiledGround = TiledGround;
  27449. var Plane = (function (_super) {
  27450. __extends(Plane, _super);
  27451. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27452. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27453. this.size = size;
  27454. this.side = side;
  27455. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27456. }
  27457. Plane.prototype._regenerateVertexData = function () {
  27458. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27459. };
  27460. Plane.prototype.copy = function (id) {
  27461. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27462. };
  27463. Plane.prototype.serialize = function () {
  27464. var serializationObject = _super.prototype.serialize.call(this);
  27465. serializationObject.size = this.size;
  27466. return serializationObject;
  27467. };
  27468. Plane.Parse = function (parsedPlane, scene) {
  27469. if (scene.getGeometryByID(parsedPlane.id)) {
  27470. return null; // null since geometry could be something else than a ground...
  27471. }
  27472. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27473. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27474. scene.pushGeometry(plane, true);
  27475. return plane;
  27476. };
  27477. return Plane;
  27478. })(_Primitive);
  27479. Primitives.Plane = Plane;
  27480. var TorusKnot = (function (_super) {
  27481. __extends(TorusKnot, _super);
  27482. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27483. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27484. this.radius = radius;
  27485. this.tube = tube;
  27486. this.radialSegments = radialSegments;
  27487. this.tubularSegments = tubularSegments;
  27488. this.p = p;
  27489. this.q = q;
  27490. this.side = side;
  27491. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27492. }
  27493. TorusKnot.prototype._regenerateVertexData = function () {
  27494. 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 });
  27495. };
  27496. TorusKnot.prototype.copy = function (id) {
  27497. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27498. };
  27499. TorusKnot.prototype.serialize = function () {
  27500. var serializationObject = _super.prototype.serialize.call(this);
  27501. serializationObject.radius = this.radius;
  27502. serializationObject.tube = this.tube;
  27503. serializationObject.radialSegments = this.radialSegments;
  27504. serializationObject.tubularSegments = this.tubularSegments;
  27505. serializationObject.p = this.p;
  27506. serializationObject.q = this.q;
  27507. return serializationObject;
  27508. };
  27509. ;
  27510. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27511. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27512. return null; // null since geometry could be something else than a ground...
  27513. }
  27514. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27515. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27516. scene.pushGeometry(torusKnot, true);
  27517. return torusKnot;
  27518. };
  27519. return TorusKnot;
  27520. })(_Primitive);
  27521. Primitives.TorusKnot = TorusKnot;
  27522. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27523. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27524. })(BABYLON || (BABYLON = {}));
  27525. var BABYLON;
  27526. (function (BABYLON) {
  27527. var GroundMesh = (function (_super) {
  27528. __extends(GroundMesh, _super);
  27529. function GroundMesh(name, scene) {
  27530. _super.call(this, name, scene);
  27531. this.generateOctree = false;
  27532. this._worldInverse = new BABYLON.Matrix();
  27533. }
  27534. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27535. get: function () {
  27536. return this._subdivisions;
  27537. },
  27538. enumerable: true,
  27539. configurable: true
  27540. });
  27541. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  27542. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  27543. this._subdivisions = chunksCount;
  27544. this.subdivide(this._subdivisions);
  27545. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  27546. };
  27547. /**
  27548. * Returns a height (y) value in the Worl system :
  27549. * the ground altitude at the coordinates (x, z) expressed in the World system.
  27550. * Returns the ground y position if (x, z) are outside the ground surface.
  27551. * Not pertinent if the ground is rotated.
  27552. */
  27553. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27554. // express x and y in the ground local system
  27555. x -= this.position.x;
  27556. z -= this.position.z;
  27557. x /= this.scaling.x;
  27558. z /= this.scaling.z;
  27559. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27560. return this.position.y;
  27561. }
  27562. if (!this._heightQuads || this._heightQuads.length == 0) {
  27563. this._computeHeightQuads();
  27564. }
  27565. var facet = this._getFacetAt(x, z);
  27566. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  27567. // return y in the World system
  27568. return y * this.scaling.y + this.position.y;
  27569. };
  27570. /**
  27571. * Returns a normalized vector (Vector3) orthogonal to the ground
  27572. * at the ground coordinates (x, z) expressed in the World system.
  27573. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  27574. * Not pertinent if the ground is rotated.
  27575. */
  27576. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  27577. var normal = new BABYLON.Vector3(0, 1, 0);
  27578. this.getNormalAtCoordinatesToRef(x, z, normal);
  27579. return normal;
  27580. };
  27581. /**
  27582. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  27583. * at the ground coordinates (x, z) expressed in the World system.
  27584. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  27585. * Not pertinent if the ground is rotated.
  27586. */
  27587. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  27588. // express x and y in the ground local system
  27589. x -= this.position.x;
  27590. z -= this.position.z;
  27591. x /= this.scaling.x;
  27592. z /= this.scaling.z;
  27593. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  27594. return;
  27595. }
  27596. if (!this._heightQuads || this._heightQuads.length == 0) {
  27597. this._computeHeightQuads();
  27598. }
  27599. var facet = this._getFacetAt(x, z);
  27600. ref.x = facet.x;
  27601. ref.y = facet.y;
  27602. ref.z = facet.z;
  27603. };
  27604. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  27605. GroundMesh.prototype._getFacetAt = function (x, z) {
  27606. // retrieve col and row from x, z coordinates in the ground local system
  27607. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  27608. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  27609. var quad = this._heightQuads[row * this._subdivisions + col];
  27610. var facet;
  27611. if (z < quad.slope.x * x + quad.slope.y) {
  27612. facet = quad.facet1;
  27613. }
  27614. else {
  27615. facet = quad.facet2;
  27616. }
  27617. return facet;
  27618. };
  27619. // Populates the heightMap array with "facet" elements :
  27620. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  27621. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  27622. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  27623. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  27624. GroundMesh.prototype._computeHeightQuads = function () {
  27625. this._heightQuads = new Array();
  27626. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27627. var v1 = BABYLON.Vector3.Zero();
  27628. var v2 = BABYLON.Vector3.Zero();
  27629. var v3 = BABYLON.Vector3.Zero();
  27630. var v4 = BABYLON.Vector3.Zero();
  27631. var v1v2 = BABYLON.Vector3.Zero();
  27632. var v1v3 = BABYLON.Vector3.Zero();
  27633. var v1v4 = BABYLON.Vector3.Zero();
  27634. var norm1 = BABYLON.Vector3.Zero();
  27635. var norm2 = BABYLON.Vector3.Zero();
  27636. var i = 0;
  27637. var j = 0;
  27638. var k = 0;
  27639. var cd = 0; // 2D slope coefficient : z = cd * x + h
  27640. var h = 0;
  27641. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  27642. var d2 = 0;
  27643. for (var row = 0; row < this._subdivisions; row++) {
  27644. for (var col = 0; col < this._subdivisions; col++) {
  27645. i = col * 3;
  27646. j = row * (this._subdivisions + 1) * 3;
  27647. k = (row + 1) * (this._subdivisions + 1) * 3;
  27648. v1.x = positions[j + i];
  27649. v1.y = positions[j + i + 1];
  27650. v1.z = positions[j + i + 2];
  27651. v2.x = positions[j + i + 3];
  27652. v2.y = positions[j + i + 4];
  27653. v2.z = positions[j + i + 5];
  27654. v3.x = positions[k + i];
  27655. v3.y = positions[k + i + 1];
  27656. v3.z = positions[k + i + 2];
  27657. v4.x = positions[k + i + 3];
  27658. v4.y = positions[k + i + 4];
  27659. v4.z = positions[k + i + 5];
  27660. // 2D slope V1V4
  27661. cd = (v4.z - v1.z) / (v4.x - v1.x);
  27662. h = v1.z - cd * v1.x; // v1 belongs to the slope
  27663. var slope = new BABYLON.Vector2(cd, h);
  27664. // facet equations :
  27665. // we compute each facet normal vector
  27666. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  27667. // we compute the value d by applying the equation to v1 which belongs to the plane
  27668. // then we store the facet equation in a Vector4
  27669. v2.subtractToRef(v1, v1v2);
  27670. v3.subtractToRef(v1, v1v3);
  27671. v4.subtractToRef(v1, v1v4);
  27672. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  27673. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  27674. norm1.normalize();
  27675. norm2.normalize();
  27676. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  27677. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  27678. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  27679. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  27680. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  27681. this._heightQuads.push(quad);
  27682. }
  27683. }
  27684. };
  27685. return GroundMesh;
  27686. })(BABYLON.Mesh);
  27687. BABYLON.GroundMesh = GroundMesh;
  27688. })(BABYLON || (BABYLON = {}));
  27689. var BABYLON;
  27690. (function (BABYLON) {
  27691. var LinesMesh = (function (_super) {
  27692. __extends(LinesMesh, _super);
  27693. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  27694. if (parent === void 0) { parent = null; }
  27695. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  27696. this.color = new BABYLON.Color3(1, 1, 1);
  27697. this.alpha = 1;
  27698. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27699. attributes: ["position"],
  27700. uniforms: ["worldViewProjection", "color"],
  27701. needAlphaBlending: true
  27702. });
  27703. }
  27704. Object.defineProperty(LinesMesh.prototype, "material", {
  27705. get: function () {
  27706. return this._colorShader;
  27707. },
  27708. enumerable: true,
  27709. configurable: true
  27710. });
  27711. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27712. get: function () {
  27713. return false;
  27714. },
  27715. enumerable: true,
  27716. configurable: true
  27717. });
  27718. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27719. get: function () {
  27720. return false;
  27721. },
  27722. enumerable: true,
  27723. configurable: true
  27724. });
  27725. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27726. var engine = this.getScene().getEngine();
  27727. var indexToBind = this._geometry.getIndexBuffer();
  27728. // VBOs
  27729. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27730. // Color
  27731. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27732. };
  27733. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27734. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27735. return;
  27736. }
  27737. var engine = this.getScene().getEngine();
  27738. // Draw order
  27739. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27740. };
  27741. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27742. return null;
  27743. };
  27744. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27745. this._colorShader.dispose();
  27746. _super.prototype.dispose.call(this, doNotRecurse);
  27747. };
  27748. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  27749. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  27750. };
  27751. return LinesMesh;
  27752. })(BABYLON.Mesh);
  27753. BABYLON.LinesMesh = LinesMesh;
  27754. })(BABYLON || (BABYLON = {}));
  27755. var BABYLON;
  27756. (function (BABYLON) {
  27757. var DebugLayer = (function () {
  27758. function DebugLayer(scene) {
  27759. var _this = this;
  27760. this._transformationMatrix = BABYLON.Matrix.Identity();
  27761. this._enabled = false;
  27762. this._labelsEnabled = false;
  27763. this._displayStatistics = true;
  27764. this._displayTree = false;
  27765. this._displayLogs = false;
  27766. this._identityMatrix = BABYLON.Matrix.Identity();
  27767. this.axisRatio = 0.02;
  27768. this.accentColor = "orange";
  27769. this._scene = scene;
  27770. this._syncPositions = function () {
  27771. var engine = _this._scene.getEngine();
  27772. var canvasRect = engine.getRenderingCanvasClientRect();
  27773. if (_this._showUI) {
  27774. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27775. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27776. _this._statsDiv.style.width = "400px";
  27777. _this._statsDiv.style.height = "auto";
  27778. _this._statsSubsetDiv.style.maxHeight = "240px";
  27779. _this._optionsDiv.style.left = "0px";
  27780. _this._optionsDiv.style.top = "10px";
  27781. _this._optionsDiv.style.width = "200px";
  27782. _this._optionsDiv.style.height = "auto";
  27783. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27784. _this._logDiv.style.left = "0px";
  27785. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27786. _this._logDiv.style.width = "600px";
  27787. _this._logDiv.style.height = "160px";
  27788. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27789. _this._treeDiv.style.top = "10px";
  27790. _this._treeDiv.style.width = "300px";
  27791. _this._treeDiv.style.height = "auto";
  27792. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27793. }
  27794. _this._globalDiv.style.left = canvasRect.left + "px";
  27795. _this._globalDiv.style.top = canvasRect.top + "px";
  27796. _this._drawingCanvas.style.left = "0px";
  27797. _this._drawingCanvas.style.top = "0px";
  27798. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27799. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27800. var devicePixelRatio = window.devicePixelRatio || 1;
  27801. var context = _this._drawingContext;
  27802. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  27803. context.mozBackingStorePixelRatio ||
  27804. context.msBackingStorePixelRatio ||
  27805. context.oBackingStorePixelRatio ||
  27806. context.backingStorePixelRatio || 1;
  27807. _this._ratio = devicePixelRatio / backingStoreRatio;
  27808. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27809. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27810. };
  27811. this._onCanvasClick = function (evt) {
  27812. _this._clickPosition = {
  27813. x: evt.clientX * _this._ratio,
  27814. y: evt.clientY * _this._ratio
  27815. };
  27816. };
  27817. this._syncUI = function () {
  27818. if (_this._showUI) {
  27819. if (_this._displayStatistics) {
  27820. _this._displayStats();
  27821. _this._statsDiv.style.display = "";
  27822. }
  27823. else {
  27824. _this._statsDiv.style.display = "none";
  27825. }
  27826. if (_this._displayLogs) {
  27827. _this._logDiv.style.display = "";
  27828. }
  27829. else {
  27830. _this._logDiv.style.display = "none";
  27831. }
  27832. if (_this._displayTree) {
  27833. _this._treeDiv.style.display = "";
  27834. if (_this._needToRefreshMeshesTree) {
  27835. _this._needToRefreshMeshesTree = false;
  27836. _this._refreshMeshesTreeContent();
  27837. }
  27838. }
  27839. else {
  27840. _this._treeDiv.style.display = "none";
  27841. }
  27842. }
  27843. };
  27844. this._syncData = function () {
  27845. if (_this._labelsEnabled || !_this._showUI) {
  27846. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27847. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27848. var engine = _this._scene.getEngine();
  27849. var viewport = _this._camera.viewport;
  27850. var globalViewport = viewport.toGlobal(engine);
  27851. // Meshes
  27852. var meshes = _this._camera.getActiveMeshes();
  27853. var index;
  27854. var projectedPosition;
  27855. for (index = 0; index < meshes.length; index++) {
  27856. var mesh = meshes.data[index];
  27857. var position = mesh.getBoundingInfo().boundingSphere.center;
  27858. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27859. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27860. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27861. }
  27862. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27863. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  27864. }
  27865. }
  27866. // Cameras
  27867. var cameras = _this._scene.cameras;
  27868. for (index = 0; index < cameras.length; index++) {
  27869. var camera = cameras[index];
  27870. if (camera === _this._camera) {
  27871. continue;
  27872. }
  27873. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27874. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27875. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27876. _this._camera.detachControl(engine.getRenderingCanvas());
  27877. _this._camera = camera;
  27878. _this._camera.attachControl(engine.getRenderingCanvas());
  27879. }, function () { return "purple"; });
  27880. }
  27881. }
  27882. // Lights
  27883. var lights = _this._scene.lights;
  27884. for (index = 0; index < lights.length; index++) {
  27885. var light = lights[index];
  27886. if (light.position) {
  27887. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27888. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27889. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27890. light.setEnabled(!light.isEnabled());
  27891. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  27892. }
  27893. }
  27894. }
  27895. }
  27896. _this._clickPosition = undefined;
  27897. };
  27898. }
  27899. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27900. while (this._treeSubsetDiv.hasChildNodes()) {
  27901. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27902. }
  27903. // Add meshes
  27904. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27905. sortedArray.sort(function (a, b) {
  27906. if (a.name === b.name) {
  27907. return 0;
  27908. }
  27909. return (a.name > b.name) ? 1 : -1;
  27910. });
  27911. for (var index = 0; index < sortedArray.length; index++) {
  27912. var mesh = sortedArray[index];
  27913. if (!mesh.isEnabled()) {
  27914. continue;
  27915. }
  27916. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27917. m.isVisible = element.checked;
  27918. }, mesh);
  27919. }
  27920. };
  27921. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27922. this._drawingContext.beginPath();
  27923. this._drawingContext.moveTo(zero.x, zero.y);
  27924. this._drawingContext.lineTo(unit.x, unit.y);
  27925. this._drawingContext.strokeStyle = color;
  27926. this._drawingContext.lineWidth = 4;
  27927. this._drawingContext.stroke();
  27928. this._drawingContext.font = "normal 14px Segoe UI";
  27929. this._drawingContext.fillStyle = color;
  27930. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27931. };
  27932. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27933. var position = mesh.getBoundingInfo().boundingSphere.center;
  27934. var worldMatrix = mesh.getWorldMatrix();
  27935. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27936. var unit = (unprojectedVector.subtract(position)).length();
  27937. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27938. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27939. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27940. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27941. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27942. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27943. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27944. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27945. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27946. };
  27947. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27948. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27949. this._drawingContext.font = "normal 12px Segoe UI";
  27950. var textMetrics = this._drawingContext.measureText(text);
  27951. var centerX = projectedPosition.x - textMetrics.width / 2;
  27952. var centerY = projectedPosition.y;
  27953. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27954. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27955. onClick();
  27956. }
  27957. this._drawingContext.beginPath();
  27958. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27959. this._drawingContext.fillStyle = getFillStyle();
  27960. this._drawingContext.globalAlpha = 0.5;
  27961. this._drawingContext.fill();
  27962. this._drawingContext.globalAlpha = 1.0;
  27963. this._drawingContext.strokeStyle = '#FFFFFF';
  27964. this._drawingContext.lineWidth = 1;
  27965. this._drawingContext.stroke();
  27966. this._drawingContext.fillStyle = "#FFFFFF";
  27967. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27968. this._drawingContext.beginPath();
  27969. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27970. this._drawingContext.fill();
  27971. }
  27972. };
  27973. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27974. if (!this._clickPosition) {
  27975. return false;
  27976. }
  27977. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27978. return false;
  27979. }
  27980. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27981. return false;
  27982. }
  27983. return true;
  27984. };
  27985. DebugLayer.prototype.isVisible = function () {
  27986. return this._enabled;
  27987. };
  27988. DebugLayer.prototype.hide = function () {
  27989. if (!this._enabled) {
  27990. return;
  27991. }
  27992. this._enabled = false;
  27993. var engine = this._scene.getEngine();
  27994. this._scene.unregisterBeforeRender(this._syncData);
  27995. this._scene.unregisterAfterRender(this._syncUI);
  27996. this._rootElement.removeChild(this._globalDiv);
  27997. this._scene.forceShowBoundingBoxes = false;
  27998. this._scene.forceWireframe = false;
  27999. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28000. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28001. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28002. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28003. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28004. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28005. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28006. BABYLON.StandardMaterial.LightmapEnabled = true;
  28007. this._scene.shadowsEnabled = true;
  28008. this._scene.particlesEnabled = true;
  28009. this._scene.postProcessesEnabled = true;
  28010. this._scene.collisionsEnabled = true;
  28011. this._scene.lightsEnabled = true;
  28012. this._scene.texturesEnabled = true;
  28013. this._scene.lensFlaresEnabled = true;
  28014. this._scene.proceduralTexturesEnabled = true;
  28015. this._scene.renderTargetsEnabled = true;
  28016. this._scene.probesEnabled = true;
  28017. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28018. };
  28019. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28020. if (showUI === void 0) { showUI = true; }
  28021. if (camera === void 0) { camera = null; }
  28022. if (rootElement === void 0) { rootElement = null; }
  28023. if (this._enabled) {
  28024. return;
  28025. }
  28026. this._enabled = true;
  28027. if (camera) {
  28028. this._camera = camera;
  28029. }
  28030. else {
  28031. this._camera = this._scene.activeCamera;
  28032. }
  28033. this._showUI = showUI;
  28034. var engine = this._scene.getEngine();
  28035. this._globalDiv = document.createElement("div");
  28036. this._rootElement = rootElement || document.body;
  28037. this._rootElement.appendChild(this._globalDiv);
  28038. this._generateDOMelements();
  28039. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28040. this._syncPositions();
  28041. this._scene.registerBeforeRender(this._syncData);
  28042. this._scene.registerAfterRender(this._syncUI);
  28043. };
  28044. DebugLayer.prototype._clearLabels = function () {
  28045. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28046. for (var index = 0; index < this._scene.meshes.length; index++) {
  28047. var mesh = this._scene.meshes[index];
  28048. mesh.renderOverlay = false;
  28049. }
  28050. };
  28051. DebugLayer.prototype._generateheader = function (root, text) {
  28052. var header = document.createElement("div");
  28053. header.innerHTML = text + "&nbsp;";
  28054. header.style.textAlign = "right";
  28055. header.style.width = "100%";
  28056. header.style.color = "white";
  28057. header.style.backgroundColor = "Black";
  28058. header.style.padding = "5px 5px 4px 0px";
  28059. header.style.marginLeft = "-5px";
  28060. header.style.fontWeight = "bold";
  28061. root.appendChild(header);
  28062. };
  28063. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28064. var label = document.createElement("label");
  28065. label.innerHTML = title;
  28066. label.style.color = color;
  28067. root.appendChild(label);
  28068. root.appendChild(document.createElement("br"));
  28069. };
  28070. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28071. if (tag === void 0) { tag = null; }
  28072. var label = document.createElement("label");
  28073. var boundingBoxesCheckbox = document.createElement("input");
  28074. boundingBoxesCheckbox.type = "checkbox";
  28075. boundingBoxesCheckbox.checked = initialState;
  28076. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28077. task(evt.target, tag);
  28078. });
  28079. label.appendChild(boundingBoxesCheckbox);
  28080. var container = document.createElement("span");
  28081. var leftPart = document.createElement("span");
  28082. var rightPart = document.createElement("span");
  28083. rightPart.style.cssFloat = "right";
  28084. leftPart.innerHTML = leftTitle;
  28085. rightPart.innerHTML = rightTitle;
  28086. rightPart.style.fontSize = "12px";
  28087. rightPart.style.maxWidth = "200px";
  28088. container.appendChild(leftPart);
  28089. container.appendChild(rightPart);
  28090. label.appendChild(container);
  28091. root.appendChild(label);
  28092. root.appendChild(document.createElement("br"));
  28093. };
  28094. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28095. if (tag === void 0) { tag = null; }
  28096. var label = document.createElement("label");
  28097. var checkBox = document.createElement("input");
  28098. checkBox.type = "checkbox";
  28099. checkBox.checked = initialState;
  28100. checkBox.addEventListener("change", function (evt) {
  28101. task(evt.target, tag);
  28102. });
  28103. label.appendChild(checkBox);
  28104. label.appendChild(document.createTextNode(title));
  28105. root.appendChild(label);
  28106. root.appendChild(document.createElement("br"));
  28107. };
  28108. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28109. if (tag === void 0) { tag = null; }
  28110. var button = document.createElement("button");
  28111. button.innerHTML = title;
  28112. button.style.height = "24px";
  28113. button.style.width = "150px";
  28114. button.style.marginBottom = "5px";
  28115. button.style.color = "#444444";
  28116. button.style.border = "1px solid white";
  28117. button.className = "debugLayerButton";
  28118. button.addEventListener("click", function (evt) {
  28119. task(evt.target, tag);
  28120. });
  28121. root.appendChild(button);
  28122. root.appendChild(document.createElement("br"));
  28123. };
  28124. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28125. if (tag === void 0) { tag = null; }
  28126. var label = document.createElement("label");
  28127. var boundingBoxesRadio = document.createElement("input");
  28128. boundingBoxesRadio.type = "radio";
  28129. boundingBoxesRadio.name = name;
  28130. boundingBoxesRadio.checked = initialState;
  28131. boundingBoxesRadio.addEventListener("change", function (evt) {
  28132. task(evt.target, tag);
  28133. });
  28134. label.appendChild(boundingBoxesRadio);
  28135. label.appendChild(document.createTextNode(title));
  28136. root.appendChild(label);
  28137. root.appendChild(document.createElement("br"));
  28138. };
  28139. DebugLayer.prototype._generateDOMelements = function () {
  28140. var _this = this;
  28141. this._globalDiv.id = "DebugLayer";
  28142. this._globalDiv.style.position = "absolute";
  28143. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28144. this._globalDiv.style.fontSize = "14px";
  28145. this._globalDiv.style.color = "white";
  28146. // Drawing canvas
  28147. this._drawingCanvas = document.createElement("canvas");
  28148. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28149. this._drawingCanvas.style.position = "absolute";
  28150. this._drawingCanvas.style.pointerEvents = "none";
  28151. this._drawingCanvas.style.backgroundColor = "transparent";
  28152. this._drawingContext = this._drawingCanvas.getContext("2d");
  28153. this._globalDiv.appendChild(this._drawingCanvas);
  28154. if (this._showUI) {
  28155. var background = "rgba(128, 128, 128, 0.4)";
  28156. var border = "rgb(180, 180, 180) solid 1px";
  28157. // Stats
  28158. this._statsDiv = document.createElement("div");
  28159. this._statsDiv.id = "DebugLayerStats";
  28160. this._statsDiv.style.border = border;
  28161. this._statsDiv.style.position = "absolute";
  28162. this._statsDiv.style.background = background;
  28163. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28164. this._generateheader(this._statsDiv, "STATISTICS");
  28165. this._statsSubsetDiv = document.createElement("div");
  28166. this._statsSubsetDiv.style.paddingTop = "5px";
  28167. this._statsSubsetDiv.style.paddingBottom = "5px";
  28168. this._statsSubsetDiv.style.overflowY = "auto";
  28169. this._statsDiv.appendChild(this._statsSubsetDiv);
  28170. // Tree
  28171. this._treeDiv = document.createElement("div");
  28172. this._treeDiv.id = "DebugLayerTree";
  28173. this._treeDiv.style.border = border;
  28174. this._treeDiv.style.position = "absolute";
  28175. this._treeDiv.style.background = background;
  28176. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28177. this._treeDiv.style.display = "none";
  28178. this._generateheader(this._treeDiv, "MESHES TREE");
  28179. this._treeSubsetDiv = document.createElement("div");
  28180. this._treeSubsetDiv.style.paddingTop = "5px";
  28181. this._treeSubsetDiv.style.paddingRight = "5px";
  28182. this._treeSubsetDiv.style.overflowY = "auto";
  28183. this._treeSubsetDiv.style.maxHeight = "300px";
  28184. this._treeDiv.appendChild(this._treeSubsetDiv);
  28185. this._needToRefreshMeshesTree = true;
  28186. // Logs
  28187. this._logDiv = document.createElement("div");
  28188. this._logDiv.style.border = border;
  28189. this._logDiv.id = "DebugLayerLogs";
  28190. this._logDiv.style.position = "absolute";
  28191. this._logDiv.style.background = background;
  28192. this._logDiv.style.padding = "0px 0px 0px 5px";
  28193. this._logDiv.style.display = "none";
  28194. this._generateheader(this._logDiv, "LOGS");
  28195. this._logSubsetDiv = document.createElement("div");
  28196. this._logSubsetDiv.style.height = "127px";
  28197. this._logSubsetDiv.style.paddingTop = "5px";
  28198. this._logSubsetDiv.style.overflowY = "auto";
  28199. this._logSubsetDiv.style.fontSize = "12px";
  28200. this._logSubsetDiv.style.fontFamily = "consolas";
  28201. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28202. this._logDiv.appendChild(this._logSubsetDiv);
  28203. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28204. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28205. };
  28206. // Options
  28207. this._optionsDiv = document.createElement("div");
  28208. this._optionsDiv.id = "DebugLayerOptions";
  28209. this._optionsDiv.style.border = border;
  28210. this._optionsDiv.style.position = "absolute";
  28211. this._optionsDiv.style.background = background;
  28212. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28213. this._optionsDiv.style.overflowY = "auto";
  28214. this._generateheader(this._optionsDiv, "OPTIONS");
  28215. this._optionsSubsetDiv = document.createElement("div");
  28216. this._optionsSubsetDiv.style.paddingTop = "5px";
  28217. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28218. this._optionsSubsetDiv.style.overflowY = "auto";
  28219. this._optionsSubsetDiv.style.maxHeight = "200px";
  28220. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28221. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28222. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28223. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28224. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28225. _this._displayTree = element.checked;
  28226. _this._needToRefreshMeshesTree = true;
  28227. });
  28228. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28229. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28230. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28231. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28232. _this._labelsEnabled = element.checked;
  28233. if (!_this._labelsEnabled) {
  28234. _this._clearLabels();
  28235. }
  28236. });
  28237. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28238. if (element.checked) {
  28239. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28240. }
  28241. else {
  28242. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28243. }
  28244. });
  28245. ;
  28246. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28247. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28248. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28249. if (element.checked) {
  28250. _this._scene.forceWireframe = false;
  28251. _this._scene.forcePointsCloud = false;
  28252. }
  28253. });
  28254. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28255. if (element.checked) {
  28256. _this._scene.forceWireframe = true;
  28257. _this._scene.forcePointsCloud = false;
  28258. }
  28259. });
  28260. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28261. if (element.checked) {
  28262. _this._scene.forceWireframe = false;
  28263. _this._scene.forcePointsCloud = true;
  28264. }
  28265. });
  28266. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28267. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28268. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28269. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28270. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28271. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28272. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28273. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28274. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28275. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28276. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  28277. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28278. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28279. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28280. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28281. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28282. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28283. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28284. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28285. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28286. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28287. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28288. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28289. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28290. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28291. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28292. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28293. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28294. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28295. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28296. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28297. if (element.checked) {
  28298. _this._scene.headphone = true;
  28299. }
  28300. });
  28301. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28302. if (element.checked) {
  28303. _this._scene.headphone = false;
  28304. }
  28305. });
  28306. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28307. _this._scene.audioEnabled = !element.checked;
  28308. });
  28309. }
  28310. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28311. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28312. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28313. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28314. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28315. if (_this._camera) {
  28316. console.log(_this._camera);
  28317. }
  28318. else {
  28319. console.warn("No camera defined, or debug layer created before camera creation!");
  28320. }
  28321. });
  28322. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28323. this._globalDiv.appendChild(this._statsDiv);
  28324. this._globalDiv.appendChild(this._logDiv);
  28325. this._globalDiv.appendChild(this._optionsDiv);
  28326. this._globalDiv.appendChild(this._treeDiv);
  28327. }
  28328. };
  28329. DebugLayer.prototype._displayStats = function () {
  28330. var scene = this._scene;
  28331. var engine = scene.getEngine();
  28332. var glInfo = engine.getGlInfo();
  28333. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28334. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28335. + "<b>Count</b><br>"
  28336. + "Total meshes: " + scene.meshes.length + "<br>"
  28337. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28338. + "Total materials: " + scene.materials.length + "<br>"
  28339. + "Total textures: " + scene.textures.length + "<br>"
  28340. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28341. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28342. + "Active bones: " + scene.getActiveBones() + "<br>"
  28343. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28344. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  28345. + "<b>Duration</b><br>"
  28346. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28347. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28348. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28349. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28350. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28351. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28352. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  28353. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  28354. + "</div>"
  28355. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28356. + "<b>Extensions</b><br>"
  28357. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28358. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28359. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28360. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  28361. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28362. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28363. + "<b>Caps.</b><br>"
  28364. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28365. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28366. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  28367. + "</div><br>"
  28368. + "<b>Info</b><br>"
  28369. + glInfo.version + "<br>"
  28370. + glInfo.renderer + "<br>";
  28371. if (this.customStatsFunction) {
  28372. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28373. }
  28374. };
  28375. return DebugLayer;
  28376. })();
  28377. BABYLON.DebugLayer = DebugLayer;
  28378. })(BABYLON || (BABYLON = {}));
  28379. var BABYLON;
  28380. (function (BABYLON) {
  28381. var DefaultLoadingScreen = (function () {
  28382. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28383. var _this = this;
  28384. if (_loadingText === void 0) { _loadingText = ""; }
  28385. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28386. this._renderingCanvas = _renderingCanvas;
  28387. this._loadingText = _loadingText;
  28388. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28389. // Resize
  28390. this._resizeLoadingUI = function () {
  28391. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28392. _this._loadingDiv.style.position = "absolute";
  28393. _this._loadingDiv.style.left = canvasRect.left + "px";
  28394. _this._loadingDiv.style.top = canvasRect.top + "px";
  28395. _this._loadingDiv.style.width = canvasRect.width + "px";
  28396. _this._loadingDiv.style.height = canvasRect.height + "px";
  28397. };
  28398. }
  28399. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28400. var _this = this;
  28401. if (this._loadingDiv) {
  28402. // Do not add a loading screen if there is already one
  28403. return;
  28404. }
  28405. this._loadingDiv = document.createElement("div");
  28406. this._loadingDiv.id = "babylonjsLoadingDiv";
  28407. this._loadingDiv.style.opacity = "0";
  28408. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28409. // Loading text
  28410. this._loadingTextDiv = document.createElement("div");
  28411. this._loadingTextDiv.style.position = "absolute";
  28412. this._loadingTextDiv.style.left = "0";
  28413. this._loadingTextDiv.style.top = "50%";
  28414. this._loadingTextDiv.style.marginTop = "80px";
  28415. this._loadingTextDiv.style.width = "100%";
  28416. this._loadingTextDiv.style.height = "20px";
  28417. this._loadingTextDiv.style.fontFamily = "Arial";
  28418. this._loadingTextDiv.style.fontSize = "14px";
  28419. this._loadingTextDiv.style.color = "white";
  28420. this._loadingTextDiv.style.textAlign = "center";
  28421. this._loadingTextDiv.innerHTML = "Loading";
  28422. this._loadingDiv.appendChild(this._loadingTextDiv);
  28423. //set the predefined text
  28424. this._loadingTextDiv.innerHTML = this._loadingText;
  28425. // Loading img
  28426. var imgBack = new Image();
  28427. 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==";
  28428. imgBack.style.position = "absolute";
  28429. imgBack.style.left = "50%";
  28430. imgBack.style.top = "50%";
  28431. imgBack.style.marginLeft = "-50px";
  28432. imgBack.style.marginTop = "-50px";
  28433. imgBack.style.transition = "transform 1.0s ease";
  28434. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28435. var deg = 360;
  28436. var onTransitionEnd = function () {
  28437. deg += 360;
  28438. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28439. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28440. };
  28441. imgBack.addEventListener("transitionend", onTransitionEnd);
  28442. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28443. this._loadingDiv.appendChild(imgBack);
  28444. // front image
  28445. var imgFront = new Image();
  28446. 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=";
  28447. imgFront.style.position = "absolute";
  28448. imgFront.style.left = "50%";
  28449. imgFront.style.top = "50%";
  28450. imgFront.style.marginLeft = "-50px";
  28451. imgFront.style.marginTop = "-50px";
  28452. this._loadingDiv.appendChild(imgFront);
  28453. this._resizeLoadingUI();
  28454. window.addEventListener("resize", this._resizeLoadingUI);
  28455. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28456. document.body.appendChild(this._loadingDiv);
  28457. setTimeout(function () {
  28458. _this._loadingDiv.style.opacity = "1";
  28459. imgBack.style.transform = "rotateZ(360deg)";
  28460. imgBack.style.webkitTransform = "rotateZ(360deg)";
  28461. }, 0);
  28462. };
  28463. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  28464. var _this = this;
  28465. if (!this._loadingDiv) {
  28466. return;
  28467. }
  28468. var onTransitionEnd = function () {
  28469. if (!_this._loadingDiv) {
  28470. return;
  28471. }
  28472. document.body.removeChild(_this._loadingDiv);
  28473. window.removeEventListener("resize", _this._resizeLoadingUI);
  28474. _this._loadingDiv = null;
  28475. };
  28476. this._loadingDiv.style.opacity = "0";
  28477. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  28478. };
  28479. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  28480. set: function (text) {
  28481. this._loadingText = text;
  28482. if (this._loadingTextDiv) {
  28483. this._loadingTextDiv.innerHTML = this._loadingText;
  28484. }
  28485. },
  28486. enumerable: true,
  28487. configurable: true
  28488. });
  28489. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  28490. get: function () {
  28491. return this._loadingDivBackgroundColor;
  28492. },
  28493. set: function (color) {
  28494. this._loadingDivBackgroundColor = color;
  28495. if (!this._loadingDiv) {
  28496. return;
  28497. }
  28498. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  28499. },
  28500. enumerable: true,
  28501. configurable: true
  28502. });
  28503. return DefaultLoadingScreen;
  28504. })();
  28505. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  28506. })(BABYLON || (BABYLON = {}));
  28507. var BABYLON;
  28508. (function (BABYLON) {
  28509. var SIMDVector3 = (function () {
  28510. function SIMDVector3() {
  28511. }
  28512. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  28513. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  28514. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28515. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28516. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28517. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28518. 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));
  28519. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28520. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28521. };
  28522. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  28523. var v0 = SIMD.float32x4.splat(x);
  28524. var v1 = SIMD.float32x4.splat(y);
  28525. var v2 = SIMD.float32x4.splat(z);
  28526. var m0 = SIMD.float32x4.load(transformation.m, 0);
  28527. var m1 = SIMD.float32x4.load(transformation.m, 4);
  28528. var m2 = SIMD.float32x4.load(transformation.m, 8);
  28529. var m3 = SIMD.float32x4.load(transformation.m, 12);
  28530. 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));
  28531. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  28532. SIMD.float32x4.storeXYZ(result._data, 0, r);
  28533. };
  28534. return SIMDVector3;
  28535. })();
  28536. BABYLON.SIMDVector3 = SIMDVector3;
  28537. var SIMDMatrix = (function () {
  28538. function SIMDMatrix() {
  28539. }
  28540. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  28541. if (offset === void 0) { offset = 0; }
  28542. var tm = this.m;
  28543. var om = other.m;
  28544. var om0 = SIMD.float32x4.load(om, 0);
  28545. var om1 = SIMD.float32x4.load(om, 4);
  28546. var om2 = SIMD.float32x4.load(om, 8);
  28547. var om3 = SIMD.float32x4.load(om, 12);
  28548. var tm0 = SIMD.float32x4.load(tm, 0);
  28549. 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)))));
  28550. var tm1 = SIMD.float32x4.load(tm, 4);
  28551. 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)))));
  28552. var tm2 = SIMD.float32x4.load(tm, 8);
  28553. 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)))));
  28554. var tm3 = SIMD.float32x4.load(tm, 12);
  28555. 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)))));
  28556. };
  28557. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  28558. var src = this.m;
  28559. var dest = other.m;
  28560. var row0, row1, row2, row3;
  28561. var tmp1;
  28562. var minor0, minor1, minor2, minor3;
  28563. var det;
  28564. // Load the 4 rows
  28565. var src0 = SIMD.float32x4.load(src, 0);
  28566. var src1 = SIMD.float32x4.load(src, 4);
  28567. var src2 = SIMD.float32x4.load(src, 8);
  28568. var src3 = SIMD.float32x4.load(src, 12);
  28569. // Transpose the source matrix. Sort of. Not a true transpose operation
  28570. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28571. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28572. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  28573. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  28574. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28575. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28576. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  28577. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  28578. // This is a true transposition, but it will lead to an incorrect result
  28579. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  28580. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  28581. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28582. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28583. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  28584. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  28585. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  28586. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  28587. // ----
  28588. tmp1 = SIMD.float32x4.mul(row2, row3);
  28589. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28590. minor0 = SIMD.float32x4.mul(row1, tmp1);
  28591. minor1 = SIMD.float32x4.mul(row0, tmp1);
  28592. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28593. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  28594. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  28595. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  28596. // ----
  28597. tmp1 = SIMD.float32x4.mul(row1, row2);
  28598. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28599. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  28600. minor3 = SIMD.float32x4.mul(row0, tmp1);
  28601. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28602. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  28603. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  28604. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  28605. // ----
  28606. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  28607. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28608. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  28609. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  28610. minor2 = SIMD.float32x4.mul(row0, tmp1);
  28611. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28612. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  28613. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  28614. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  28615. // ----
  28616. tmp1 = SIMD.float32x4.mul(row0, row1);
  28617. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28618. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  28619. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  28620. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28621. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  28622. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  28623. // ----
  28624. tmp1 = SIMD.float32x4.mul(row0, row3);
  28625. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28626. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  28627. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  28628. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28629. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  28630. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  28631. // ----
  28632. tmp1 = SIMD.float32x4.mul(row0, row2);
  28633. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  28634. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  28635. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  28636. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  28637. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  28638. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  28639. // Compute determinant
  28640. det = SIMD.float32x4.mul(row0, minor0);
  28641. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  28642. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  28643. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  28644. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  28645. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  28646. // These shuffles aren't necessary if the faulty transposition is done
  28647. // up at the top of this function.
  28648. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  28649. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  28650. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  28651. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  28652. // Compute final values by multiplying with 1/det
  28653. minor0 = SIMD.float32x4.mul(det, minor0);
  28654. minor1 = SIMD.float32x4.mul(det, minor1);
  28655. minor2 = SIMD.float32x4.mul(det, minor2);
  28656. minor3 = SIMD.float32x4.mul(det, minor3);
  28657. SIMD.float32x4.store(dest, 0, minor0);
  28658. SIMD.float32x4.store(dest, 4, minor1);
  28659. SIMD.float32x4.store(dest, 8, minor2);
  28660. SIMD.float32x4.store(dest, 12, minor3);
  28661. return this;
  28662. };
  28663. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  28664. var out = result.m;
  28665. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  28666. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  28667. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  28668. // cc.kmVec3Subtract(f, pCenter, pEye);
  28669. var f = SIMD.float32x4.sub(center, eye);
  28670. // cc.kmVec3Normalize(f, f);
  28671. var tmp = SIMD.float32x4.mul(f, f);
  28672. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28673. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28674. // cc.kmVec3Assign(up, pUp);
  28675. // cc.kmVec3Normalize(up, up);
  28676. tmp = SIMD.float32x4.mul(up, up);
  28677. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28678. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28679. // cc.kmVec3Cross(s, f, up);
  28680. 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)));
  28681. // cc.kmVec3Normalize(s, s);
  28682. tmp = SIMD.float32x4.mul(s, s);
  28683. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28684. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28685. // cc.kmVec3Cross(u, s, f);
  28686. 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)));
  28687. // cc.kmVec3Normalize(s, s);
  28688. tmp = SIMD.float32x4.mul(s, s);
  28689. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  28690. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  28691. var zero = SIMD.float32x4.splat(0.0);
  28692. s = SIMD.float32x4.neg(s);
  28693. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  28694. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  28695. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28696. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  28697. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  28698. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  28699. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  28700. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  28701. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  28702. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  28703. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  28704. var b3 = SIMD.float32x4.neg(eye);
  28705. b3 = SIMD.float32x4.withW(b3, 1.0);
  28706. 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)))));
  28707. 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)))));
  28708. 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)))));
  28709. 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)))));
  28710. };
  28711. return SIMDMatrix;
  28712. })();
  28713. BABYLON.SIMDMatrix = SIMDMatrix;
  28714. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  28715. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  28716. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  28717. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  28718. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  28719. var SIMDHelper = (function () {
  28720. function SIMDHelper() {
  28721. }
  28722. Object.defineProperty(SIMDHelper, "IsEnabled", {
  28723. get: function () {
  28724. return SIMDHelper._isEnabled;
  28725. },
  28726. enumerable: true,
  28727. configurable: true
  28728. });
  28729. SIMDHelper.DisableSIMD = function () {
  28730. // Replace functions
  28731. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  28732. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  28733. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  28734. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  28735. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  28736. SIMDHelper._isEnabled = false;
  28737. };
  28738. SIMDHelper.EnableSIMD = function () {
  28739. if (window.SIMD === undefined) {
  28740. return;
  28741. }
  28742. // Replace functions
  28743. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  28744. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  28745. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  28746. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  28747. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  28748. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  28749. get: function () { return this._data[0]; },
  28750. set: function (value) {
  28751. if (!this._data) {
  28752. this._data = new Float32Array(3);
  28753. }
  28754. this._data[0] = value;
  28755. }
  28756. });
  28757. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  28758. get: function () { return this._data[1]; },
  28759. set: function (value) {
  28760. this._data[1] = value;
  28761. }
  28762. });
  28763. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  28764. get: function () { return this._data[2]; },
  28765. set: function (value) {
  28766. this._data[2] = value;
  28767. }
  28768. });
  28769. SIMDHelper._isEnabled = true;
  28770. };
  28771. SIMDHelper._isEnabled = false;
  28772. return SIMDHelper;
  28773. })();
  28774. BABYLON.SIMDHelper = SIMDHelper;
  28775. })(BABYLON || (BABYLON = {}));
  28776. var BABYLON;
  28777. (function (BABYLON) {
  28778. var ShaderMaterial = (function (_super) {
  28779. __extends(ShaderMaterial, _super);
  28780. function ShaderMaterial(name, scene, shaderPath, options) {
  28781. _super.call(this, name, scene);
  28782. this._textures = {};
  28783. this._floats = {};
  28784. this._floatsArrays = {};
  28785. this._colors3 = {};
  28786. this._colors4 = {};
  28787. this._vectors2 = {};
  28788. this._vectors3 = {};
  28789. this._vectors4 = {};
  28790. this._matrices = {};
  28791. this._matrices3x3 = {};
  28792. this._matrices2x2 = {};
  28793. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28794. this._shaderPath = shaderPath;
  28795. options.needAlphaBlending = options.needAlphaBlending || false;
  28796. options.needAlphaTesting = options.needAlphaTesting || false;
  28797. options.attributes = options.attributes || ["position", "normal", "uv"];
  28798. options.uniforms = options.uniforms || ["worldViewProjection"];
  28799. options.samplers = options.samplers || [];
  28800. options.defines = options.defines || [];
  28801. this._options = options;
  28802. }
  28803. ShaderMaterial.prototype.needAlphaBlending = function () {
  28804. return this._options.needAlphaBlending;
  28805. };
  28806. ShaderMaterial.prototype.needAlphaTesting = function () {
  28807. return this._options.needAlphaTesting;
  28808. };
  28809. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28810. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28811. this._options.uniforms.push(uniformName);
  28812. }
  28813. };
  28814. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28815. if (this._options.samplers.indexOf(name) === -1) {
  28816. this._options.samplers.push(name);
  28817. }
  28818. this._textures[name] = texture;
  28819. return this;
  28820. };
  28821. ShaderMaterial.prototype.setFloat = function (name, value) {
  28822. this._checkUniform(name);
  28823. this._floats[name] = value;
  28824. return this;
  28825. };
  28826. ShaderMaterial.prototype.setFloats = function (name, value) {
  28827. this._checkUniform(name);
  28828. this._floatsArrays[name] = value;
  28829. return this;
  28830. };
  28831. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28832. this._checkUniform(name);
  28833. this._colors3[name] = value;
  28834. return this;
  28835. };
  28836. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28837. this._checkUniform(name);
  28838. this._colors4[name] = value;
  28839. return this;
  28840. };
  28841. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28842. this._checkUniform(name);
  28843. this._vectors2[name] = value;
  28844. return this;
  28845. };
  28846. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28847. this._checkUniform(name);
  28848. this._vectors3[name] = value;
  28849. return this;
  28850. };
  28851. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28852. this._checkUniform(name);
  28853. this._vectors4[name] = value;
  28854. return this;
  28855. };
  28856. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28857. this._checkUniform(name);
  28858. this._matrices[name] = value;
  28859. return this;
  28860. };
  28861. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28862. this._checkUniform(name);
  28863. this._matrices3x3[name] = value;
  28864. return this;
  28865. };
  28866. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28867. this._checkUniform(name);
  28868. this._matrices2x2[name] = value;
  28869. return this;
  28870. };
  28871. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28872. var scene = this.getScene();
  28873. var engine = scene.getEngine();
  28874. if (!this.checkReadyOnEveryCall) {
  28875. if (this._renderId === scene.getRenderId()) {
  28876. return true;
  28877. }
  28878. }
  28879. // Instances
  28880. var defines = [];
  28881. var fallbacks = new BABYLON.EffectFallbacks();
  28882. if (useInstances) {
  28883. defines.push("#define INSTANCES");
  28884. }
  28885. for (var index = 0; index < this._options.defines.length; index++) {
  28886. defines.push(this._options.defines[index]);
  28887. }
  28888. // Bones
  28889. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28890. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28891. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28892. fallbacks.addCPUSkinningFallback(0, mesh);
  28893. }
  28894. // Alpha test
  28895. if (engine.getAlphaTesting()) {
  28896. defines.push("#define ALPHATEST");
  28897. }
  28898. var previousEffect = this._effect;
  28899. var join = defines.join("\n");
  28900. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  28901. if (!this._effect.isReady()) {
  28902. return false;
  28903. }
  28904. if (previousEffect !== this._effect) {
  28905. scene.resetCachedMaterial();
  28906. }
  28907. this._renderId = scene.getRenderId();
  28908. return true;
  28909. };
  28910. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28911. var scene = this.getScene();
  28912. if (this._options.uniforms.indexOf("world") !== -1) {
  28913. this._effect.setMatrix("world", world);
  28914. }
  28915. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28916. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28917. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28918. }
  28919. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28920. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28921. }
  28922. };
  28923. ShaderMaterial.prototype.bind = function (world, mesh) {
  28924. // Std values
  28925. this.bindOnlyWorldMatrix(world);
  28926. if (this.getScene().getCachedMaterial() !== this) {
  28927. if (this._options.uniforms.indexOf("view") !== -1) {
  28928. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28929. }
  28930. if (this._options.uniforms.indexOf("projection") !== -1) {
  28931. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28932. }
  28933. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28934. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28935. }
  28936. // Bones
  28937. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28938. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  28939. }
  28940. // Texture
  28941. for (var name in this._textures) {
  28942. this._effect.setTexture(name, this._textures[name]);
  28943. }
  28944. // Float
  28945. for (name in this._floats) {
  28946. this._effect.setFloat(name, this._floats[name]);
  28947. }
  28948. // Float s
  28949. for (name in this._floatsArrays) {
  28950. this._effect.setArray(name, this._floatsArrays[name]);
  28951. }
  28952. // Color3
  28953. for (name in this._colors3) {
  28954. this._effect.setColor3(name, this._colors3[name]);
  28955. }
  28956. // Color4
  28957. for (name in this._colors4) {
  28958. var color = this._colors4[name];
  28959. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28960. }
  28961. // Vector2
  28962. for (name in this._vectors2) {
  28963. this._effect.setVector2(name, this._vectors2[name]);
  28964. }
  28965. // Vector3
  28966. for (name in this._vectors3) {
  28967. this._effect.setVector3(name, this._vectors3[name]);
  28968. }
  28969. // Vector4
  28970. for (name in this._vectors4) {
  28971. this._effect.setVector4(name, this._vectors4[name]);
  28972. }
  28973. // Matrix
  28974. for (name in this._matrices) {
  28975. this._effect.setMatrix(name, this._matrices[name]);
  28976. }
  28977. // Matrix 3x3
  28978. for (name in this._matrices3x3) {
  28979. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28980. }
  28981. // Matrix 2x2
  28982. for (name in this._matrices2x2) {
  28983. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28984. }
  28985. }
  28986. _super.prototype.bind.call(this, world, mesh);
  28987. };
  28988. ShaderMaterial.prototype.clone = function (name) {
  28989. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28990. return newShaderMaterial;
  28991. };
  28992. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  28993. for (var name in this._textures) {
  28994. this._textures[name].dispose();
  28995. }
  28996. this._textures = {};
  28997. _super.prototype.dispose.call(this, forceDisposeEffect);
  28998. };
  28999. ShaderMaterial.prototype.serialize = function () {
  29000. var serializationObject = _super.prototype.serialize.call(this);
  29001. serializationObject.options = this._options;
  29002. serializationObject.shaderPath = this._shaderPath;
  29003. serializationObject.customType = "BABYLON.ShaderMaterial";
  29004. // Texture
  29005. serializationObject.textures = {};
  29006. for (var name in this._textures) {
  29007. serializationObject.textures[name] = this._textures[name].serialize();
  29008. }
  29009. // Float
  29010. serializationObject.floats = {};
  29011. for (name in this._floats) {
  29012. serializationObject.floats[name] = this._floats[name];
  29013. }
  29014. // Float s
  29015. serializationObject.floatArrays = {};
  29016. for (name in this._floatsArrays) {
  29017. serializationObject.floatArrays[name] = this._floatsArrays[name];
  29018. }
  29019. // Color3
  29020. serializationObject.colors3 = {};
  29021. for (name in this._colors3) {
  29022. serializationObject.colors3[name] = this._colors3[name].asArray();
  29023. }
  29024. // Color4
  29025. serializationObject.colors4 = {};
  29026. for (name in this._colors4) {
  29027. serializationObject.colors4[name] = this._colors4[name].asArray();
  29028. }
  29029. // Vector2
  29030. serializationObject.vectors2 = {};
  29031. for (name in this._vectors2) {
  29032. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  29033. }
  29034. // Vector3
  29035. serializationObject.vectors3 = {};
  29036. for (name in this._vectors3) {
  29037. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  29038. }
  29039. // Vector4
  29040. serializationObject.vectors4 = {};
  29041. for (name in this._vectors4) {
  29042. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  29043. }
  29044. // Matrix
  29045. serializationObject.matrices = {};
  29046. for (name in this._matrices) {
  29047. serializationObject.matrices[name] = this._matrices[name].asArray();
  29048. }
  29049. // Matrix 3x3
  29050. serializationObject.matrices3x3 = {};
  29051. for (name in this._matrices3x3) {
  29052. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  29053. }
  29054. // Matrix 2x2
  29055. serializationObject.matrices2x2 = {};
  29056. for (name in this._matrices2x2) {
  29057. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  29058. }
  29059. return serializationObject;
  29060. };
  29061. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  29062. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  29063. // Texture
  29064. for (var name in source.textures) {
  29065. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  29066. }
  29067. // Float
  29068. for (name in source.floats) {
  29069. material.setFloat(name, source.floats[name]);
  29070. }
  29071. // Float s
  29072. for (name in source.floatsArrays) {
  29073. material.setFloats(name, source.floatsArrays[name]);
  29074. }
  29075. // Color3
  29076. for (name in source.colors3) {
  29077. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  29078. }
  29079. // Color4
  29080. for (name in source.colors4) {
  29081. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  29082. }
  29083. // Vector2
  29084. for (name in source.vectors2) {
  29085. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  29086. }
  29087. // Vector3
  29088. for (name in source.vectors3) {
  29089. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  29090. }
  29091. // Vector4
  29092. for (name in source.vectors4) {
  29093. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  29094. }
  29095. // Matrix
  29096. for (name in source.matrices) {
  29097. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  29098. }
  29099. // Matrix 3x3
  29100. for (name in source.matrices3x3) {
  29101. material.setMatrix3x3(name, source.matrices3x3[name]);
  29102. }
  29103. // Matrix 2x2
  29104. for (name in source.matrices2x2) {
  29105. material.setMatrix2x2(name, source.matrices2x2[name]);
  29106. }
  29107. return material;
  29108. };
  29109. return ShaderMaterial;
  29110. })(BABYLON.Material);
  29111. BABYLON.ShaderMaterial = ShaderMaterial;
  29112. })(BABYLON || (BABYLON = {}));
  29113. var BABYLON;
  29114. (function (BABYLON) {
  29115. var Internals;
  29116. (function (Internals) {
  29117. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29118. // All values and structures referenced from:
  29119. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29120. var DDS_MAGIC = 0x20534444;
  29121. 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;
  29122. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29123. 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;
  29124. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29125. function FourCCToInt32(value) {
  29126. return value.charCodeAt(0) +
  29127. (value.charCodeAt(1) << 8) +
  29128. (value.charCodeAt(2) << 16) +
  29129. (value.charCodeAt(3) << 24);
  29130. }
  29131. function Int32ToFourCC(value) {
  29132. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29133. }
  29134. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29135. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29136. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29137. var headerLengthInt = 31; // The header length in 32 bit ints
  29138. // Offsets into the header array
  29139. var off_magic = 0;
  29140. var off_size = 1;
  29141. var off_flags = 2;
  29142. var off_height = 3;
  29143. var off_width = 4;
  29144. var off_mipmapCount = 7;
  29145. var off_pfFlags = 20;
  29146. var off_pfFourCC = 21;
  29147. var off_RGBbpp = 22;
  29148. var off_RMask = 23;
  29149. var off_GMask = 24;
  29150. var off_BMask = 25;
  29151. var off_AMask = 26;
  29152. var off_caps1 = 27;
  29153. var off_caps2 = 28;
  29154. ;
  29155. var DDSTools = (function () {
  29156. function DDSTools() {
  29157. }
  29158. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29159. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29160. var mipmapCount = 1;
  29161. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29162. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29163. }
  29164. return {
  29165. width: header[off_width],
  29166. height: header[off_height],
  29167. mipmapCount: mipmapCount,
  29168. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29169. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29170. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29171. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29172. };
  29173. };
  29174. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29175. var byteArray = new Uint8Array(dataLength);
  29176. var srcData = new Uint8Array(arrayBuffer);
  29177. var index = 0;
  29178. for (var y = height - 1; y >= 0; y--) {
  29179. for (var x = 0; x < width; x++) {
  29180. var srcPos = dataOffset + (x + y * width) * 4;
  29181. byteArray[index + 2] = srcData[srcPos];
  29182. byteArray[index + 1] = srcData[srcPos + 1];
  29183. byteArray[index] = srcData[srcPos + 2];
  29184. byteArray[index + 3] = srcData[srcPos + 3];
  29185. index += 4;
  29186. }
  29187. }
  29188. return byteArray;
  29189. };
  29190. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29191. var byteArray = new Uint8Array(dataLength);
  29192. var srcData = new Uint8Array(arrayBuffer);
  29193. var index = 0;
  29194. for (var y = height - 1; y >= 0; y--) {
  29195. for (var x = 0; x < width; x++) {
  29196. var srcPos = dataOffset + (x + y * width) * 3;
  29197. byteArray[index + 2] = srcData[srcPos];
  29198. byteArray[index + 1] = srcData[srcPos + 1];
  29199. byteArray[index] = srcData[srcPos + 2];
  29200. index += 3;
  29201. }
  29202. }
  29203. return byteArray;
  29204. };
  29205. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29206. var byteArray = new Uint8Array(dataLength);
  29207. var srcData = new Uint8Array(arrayBuffer);
  29208. var index = 0;
  29209. for (var y = height - 1; y >= 0; y--) {
  29210. for (var x = 0; x < width; x++) {
  29211. var srcPos = dataOffset + (x + y * width);
  29212. byteArray[index] = srcData[srcPos];
  29213. index++;
  29214. }
  29215. }
  29216. return byteArray;
  29217. };
  29218. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29219. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29220. if (header[off_magic] != DDS_MAGIC) {
  29221. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29222. return;
  29223. }
  29224. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29225. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29226. return;
  29227. }
  29228. if (info.isFourCC) {
  29229. fourCC = header[off_pfFourCC];
  29230. switch (fourCC) {
  29231. case FOURCC_DXT1:
  29232. blockBytes = 8;
  29233. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29234. break;
  29235. case FOURCC_DXT3:
  29236. blockBytes = 16;
  29237. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29238. break;
  29239. case FOURCC_DXT5:
  29240. blockBytes = 16;
  29241. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29242. break;
  29243. default:
  29244. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29245. return;
  29246. }
  29247. }
  29248. mipmapCount = 1;
  29249. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29250. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29251. }
  29252. var bpp = header[off_RGBbpp];
  29253. for (var face = 0; face < faces; face++) {
  29254. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29255. width = header[off_width];
  29256. height = header[off_height];
  29257. dataOffset = header[off_size] + 4;
  29258. for (i = 0; i < mipmapCount; ++i) {
  29259. if (info.isRGB) {
  29260. if (bpp === 24) {
  29261. dataLength = width * height * 3;
  29262. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29263. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29264. }
  29265. else {
  29266. dataLength = width * height * 4;
  29267. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29268. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29269. }
  29270. }
  29271. else if (info.isLuminance) {
  29272. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29273. var unpaddedRowSize = width;
  29274. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29275. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29276. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29277. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29278. }
  29279. else {
  29280. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29281. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29282. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29283. }
  29284. dataOffset += dataLength;
  29285. width *= 0.5;
  29286. height *= 0.5;
  29287. width = Math.max(1.0, width);
  29288. height = Math.max(1.0, height);
  29289. }
  29290. }
  29291. };
  29292. return DDSTools;
  29293. })();
  29294. Internals.DDSTools = DDSTools;
  29295. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29296. })(BABYLON || (BABYLON = {}));
  29297. var BABYLON;
  29298. (function (BABYLON) {
  29299. var CannonJSPlugin = (function () {
  29300. function CannonJSPlugin() {
  29301. this._registeredMeshes = [];
  29302. this._physicsMaterials = [];
  29303. this.name = "cannon";
  29304. this.updateBodyPosition = function (mesh) {
  29305. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29306. var registeredMesh = this._registeredMeshes[index];
  29307. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29308. var body = registeredMesh.body;
  29309. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29310. body.quaternion.copy(mesh.rotationQuaternion);
  29311. if (registeredMesh.deltaRotation) {
  29312. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29313. body.quaternion = body.quaternion.mult(tmpQ);
  29314. }
  29315. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29316. //calculate the correct body position:
  29317. var rotationQuaternion = mesh.rotationQuaternion;
  29318. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29319. mesh.computeWorldMatrix(true);
  29320. //get original center with no rotation
  29321. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29322. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29323. //rotation is back
  29324. mesh.rotationQuaternion = rotationQuaternion;
  29325. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29326. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29327. mesh.setPivotMatrix(p);
  29328. mesh.computeWorldMatrix(true);
  29329. //calculate the translation
  29330. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29331. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29332. //add it inverted to the delta
  29333. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29334. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29335. mesh.setPivotMatrix(oldPivot);
  29336. mesh.computeWorldMatrix(true);
  29337. }
  29338. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29339. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29340. }
  29341. body.position.set(center.x, center.y, center.z);
  29342. return;
  29343. }
  29344. }
  29345. };
  29346. }
  29347. CannonJSPlugin.prototype.initialize = function (iterations) {
  29348. if (iterations === void 0) { iterations = 10; }
  29349. this._world = new CANNON.World();
  29350. this._world.broadphase = new CANNON.NaiveBroadphase();
  29351. this._world.solver.iterations = iterations;
  29352. };
  29353. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29354. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29355. };
  29356. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29357. var _this = this;
  29358. this._world.step(delta);
  29359. this._registeredMeshes.forEach(function (registeredMesh) {
  29360. // Body position
  29361. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29362. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29363. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29364. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29365. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29366. if (registeredMesh.deltaRotation) {
  29367. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29368. }
  29369. //is the physics collision callback is set?
  29370. if (registeredMesh.mesh.onPhysicsCollide) {
  29371. if (!registeredMesh.collisionFunction) {
  29372. registeredMesh.collisionFunction = function (e) {
  29373. //find the mesh that collided with the registered mesh
  29374. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29375. if (_this._registeredMeshes[idx].body == e.body) {
  29376. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29377. }
  29378. }
  29379. };
  29380. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29381. }
  29382. }
  29383. else {
  29384. //unregister, in case the function was removed for some reason
  29385. if (registeredMesh.collisionFunction) {
  29386. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29387. }
  29388. }
  29389. });
  29390. };
  29391. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29392. this._gravity = gravity;
  29393. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29394. };
  29395. CannonJSPlugin.prototype.getGravity = function () {
  29396. return this._gravity;
  29397. };
  29398. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29399. this.unregisterMesh(mesh);
  29400. if (!mesh.rotationQuaternion) {
  29401. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29402. }
  29403. mesh.computeWorldMatrix(true);
  29404. var shape = this._createShape(mesh, impostor);
  29405. return this._createRigidBodyFromShape(shape, mesh, options);
  29406. };
  29407. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29408. //get the correct bounding box
  29409. var oldQuaternion = mesh.rotationQuaternion;
  29410. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29411. mesh.computeWorldMatrix(true);
  29412. var returnValue;
  29413. switch (impostor) {
  29414. case BABYLON.PhysicsEngine.SphereImpostor:
  29415. var bbox = mesh.getBoundingInfo().boundingBox;
  29416. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29417. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29418. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29419. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29420. break;
  29421. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29422. case BABYLON.PhysicsEngine.CylinderImpostor:
  29423. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29424. case BABYLON.PhysicsEngine.BoxImpostor:
  29425. bbox = mesh.getBoundingInfo().boundingBox;
  29426. var min = bbox.minimumWorld;
  29427. var max = bbox.maximumWorld;
  29428. var box = max.subtract(min).scale(0.5);
  29429. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29430. break;
  29431. case BABYLON.PhysicsEngine.PlaneImpostor:
  29432. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29433. returnValue = new CANNON.Plane();
  29434. break;
  29435. case BABYLON.PhysicsEngine.MeshImpostor:
  29436. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29437. var rawFaces = mesh.getIndices();
  29438. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29439. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29440. break;
  29441. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29442. returnValue = this._createHeightmap(mesh);
  29443. break;
  29444. }
  29445. mesh.rotationQuaternion = oldQuaternion;
  29446. return returnValue;
  29447. };
  29448. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29449. var verts = [], faces = [];
  29450. mesh.computeWorldMatrix(true);
  29451. //reuse this variable
  29452. var transformed = BABYLON.Vector3.Zero();
  29453. // Get vertices
  29454. for (var i = 0; i < rawVerts.length; i += 3) {
  29455. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  29456. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  29457. }
  29458. // Get faces
  29459. for (var j = 0; j < rawFaces.length; j += 3) {
  29460. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  29461. }
  29462. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  29463. return shape;
  29464. };
  29465. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  29466. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29467. var matrix = [];
  29468. //For now pointDepth will not be used and will be automatically calculated.
  29469. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  29470. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  29471. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  29472. var elementSize = dim * 2 / arraySize;
  29473. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  29474. for (var i = 0; i < pos.length; i = i + 3) {
  29475. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  29476. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  29477. var y = pos[i + 1] + minY;
  29478. if (!matrix[x]) {
  29479. matrix[x] = [];
  29480. }
  29481. if (!matrix[x][z]) {
  29482. matrix[x][z] = y;
  29483. }
  29484. matrix[x][z] = Math.max(y, matrix[x][z]);
  29485. }
  29486. for (var x = 0; x <= arraySize; ++x) {
  29487. if (!matrix[x]) {
  29488. var loc = 1;
  29489. while (!matrix[(x + loc) % arraySize]) {
  29490. loc++;
  29491. }
  29492. matrix[x] = matrix[(x + loc) % arraySize].slice();
  29493. }
  29494. for (var z = 0; z <= arraySize; ++z) {
  29495. if (!matrix[x][z]) {
  29496. var loc = 1;
  29497. var newValue;
  29498. while (newValue === undefined) {
  29499. newValue = matrix[x][(z + loc++) % arraySize];
  29500. }
  29501. matrix[x][z] = newValue;
  29502. }
  29503. }
  29504. }
  29505. var shape = new CANNON.Heightfield(matrix, {
  29506. elementSize: elementSize
  29507. });
  29508. //For future reference, needed for body transformation
  29509. shape.minY = minY;
  29510. return shape;
  29511. };
  29512. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  29513. var index;
  29514. var mat;
  29515. for (index = 0; index < this._physicsMaterials.length; index++) {
  29516. mat = this._physicsMaterials[index];
  29517. if (mat.friction === friction && mat.restitution === restitution) {
  29518. return mat;
  29519. }
  29520. }
  29521. var currentMat = new CANNON.Material("mat");
  29522. this._physicsMaterials.push(currentMat);
  29523. for (index = 0; index < this._physicsMaterials.length; index++) {
  29524. mat = this._physicsMaterials[index];
  29525. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  29526. this._world.addContactMaterial(contactMaterial);
  29527. }
  29528. return currentMat;
  29529. };
  29530. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  29531. if (!mesh.rotationQuaternion) {
  29532. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29533. }
  29534. // The delta between the mesh position and the mesh bounding box center
  29535. var bbox = mesh.getBoundingInfo().boundingBox;
  29536. var deltaPosition = mesh.position.subtract(bbox.center);
  29537. var deltaRotation;
  29538. var material = this._addMaterial(options.friction, options.restitution);
  29539. var body = new CANNON.Body({
  29540. mass: options.mass,
  29541. material: material,
  29542. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  29543. });
  29544. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  29545. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  29546. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29547. //-90 DEG in X, precalculated
  29548. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29549. body.quaternion = body.quaternion.mult(tmpQ);
  29550. //Invert! (Precalculated, 90 deg in X)
  29551. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  29552. }
  29553. //If it is a heightfield, if should be centered.
  29554. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  29555. //calculate the correct body position:
  29556. var rotationQuaternion = mesh.rotationQuaternion;
  29557. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29558. mesh.computeWorldMatrix(true);
  29559. //get original center with no rotation
  29560. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29561. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29562. //rotation is back
  29563. mesh.rotationQuaternion = rotationQuaternion;
  29564. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29565. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29566. mesh.setPivotMatrix(p);
  29567. mesh.computeWorldMatrix(true);
  29568. //calculate the translation
  29569. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29570. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29571. //add it inverted to the delta
  29572. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29573. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29574. mesh.setPivotMatrix(oldPivot);
  29575. mesh.computeWorldMatrix(true);
  29576. }
  29577. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  29578. deltaPosition = BABYLON.Vector3.Zero();
  29579. }
  29580. //add the shape
  29581. body.addShape(shape);
  29582. this._world.add(body);
  29583. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  29584. return body;
  29585. };
  29586. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29587. var initialMesh = parts[0].mesh;
  29588. this.unregisterMesh(initialMesh);
  29589. initialMesh.computeWorldMatrix(true);
  29590. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  29591. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  29592. for (var index = 1; index < parts.length; index++) {
  29593. var mesh = parts[index].mesh;
  29594. mesh.computeWorldMatrix(true);
  29595. var shape = this._createShape(mesh, parts[index].impostor);
  29596. var localPosition = mesh.position;
  29597. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  29598. }
  29599. return body;
  29600. };
  29601. CannonJSPlugin.prototype._unbindBody = function (body) {
  29602. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29603. var registeredMesh = this._registeredMeshes[index];
  29604. if (registeredMesh.body === body) {
  29605. this._world.remove(registeredMesh.body);
  29606. registeredMesh.body = null;
  29607. registeredMesh.delta = null;
  29608. registeredMesh.deltaRotation = null;
  29609. }
  29610. }
  29611. };
  29612. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  29613. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29614. var registeredMesh = this._registeredMeshes[index];
  29615. if (registeredMesh.mesh === mesh) {
  29616. // Remove body
  29617. if (registeredMesh.body) {
  29618. this._unbindBody(registeredMesh.body);
  29619. }
  29620. this._registeredMeshes.splice(index, 1);
  29621. return;
  29622. }
  29623. }
  29624. };
  29625. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29626. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  29627. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  29628. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29629. var registeredMesh = this._registeredMeshes[index];
  29630. if (registeredMesh.mesh === mesh) {
  29631. registeredMesh.body.applyImpulse(impulse, worldPoint);
  29632. return;
  29633. }
  29634. }
  29635. };
  29636. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  29637. var body1 = null, body2 = null;
  29638. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29639. var registeredMesh = this._registeredMeshes[index];
  29640. if (registeredMesh.mesh === mesh1) {
  29641. body1 = registeredMesh.body;
  29642. }
  29643. else if (registeredMesh.mesh === mesh2) {
  29644. body2 = registeredMesh.body;
  29645. }
  29646. }
  29647. if (!body1 || !body2) {
  29648. return false;
  29649. }
  29650. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  29651. this._world.addConstraint(constraint);
  29652. return true;
  29653. };
  29654. CannonJSPlugin.prototype.dispose = function () {
  29655. while (this._registeredMeshes.length) {
  29656. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29657. }
  29658. };
  29659. CannonJSPlugin.prototype.isSupported = function () {
  29660. return window.CANNON !== undefined;
  29661. };
  29662. CannonJSPlugin.prototype.getWorldObject = function () {
  29663. return this._world;
  29664. };
  29665. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29666. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29667. var registeredMesh = this._registeredMeshes[index];
  29668. if (registeredMesh.mesh === mesh) {
  29669. return registeredMesh.body;
  29670. }
  29671. }
  29672. return null;
  29673. };
  29674. return CannonJSPlugin;
  29675. })();
  29676. BABYLON.CannonJSPlugin = CannonJSPlugin;
  29677. })(BABYLON || (BABYLON = {}));
  29678. var BABYLON;
  29679. (function (BABYLON) {
  29680. var OimoJSPlugin = (function () {
  29681. function OimoJSPlugin() {
  29682. this._registeredMeshes = [];
  29683. this.name = "oimo";
  29684. /**
  29685. * Update the body position according to the mesh position
  29686. * @param mesh
  29687. */
  29688. this.updateBodyPosition = function (mesh) {
  29689. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29690. var registeredMesh = this._registeredMeshes[index];
  29691. var body = registeredMesh.body.body;
  29692. var updated = false;
  29693. var newPosition;
  29694. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29695. mesh.computeWorldMatrix(true);
  29696. newPosition = mesh.getBoundingInfo().boundingBox.center;
  29697. updated = true;
  29698. }
  29699. else if (registeredMesh.mesh.parent === mesh) {
  29700. mesh.computeWorldMatrix(true);
  29701. registeredMesh.mesh.computeWorldMatrix(true);
  29702. newPosition = registeredMesh.mesh.getAbsolutePosition();
  29703. updated = true;
  29704. }
  29705. if (updated) {
  29706. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  29707. body.setQuaternion(mesh.rotationQuaternion);
  29708. body.sleeping = false;
  29709. //force Oimo to update the body's position
  29710. body.updatePosition(1);
  29711. }
  29712. }
  29713. };
  29714. }
  29715. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  29716. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29717. };
  29718. OimoJSPlugin.prototype.initialize = function (iterations) {
  29719. this._world = new OIMO.World(null, null, iterations);
  29720. this._world.clear();
  29721. };
  29722. OimoJSPlugin.prototype.setGravity = function (gravity) {
  29723. this._gravity = this._world.gravity = gravity;
  29724. };
  29725. OimoJSPlugin.prototype.getGravity = function () {
  29726. return this._gravity;
  29727. };
  29728. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29729. this.unregisterMesh(mesh);
  29730. if (!mesh.rotationQuaternion) {
  29731. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29732. }
  29733. mesh.computeWorldMatrix(true);
  29734. var bbox = mesh.getBoundingInfo().boundingBox;
  29735. // The delta between the mesh position and the mesh bounding box center
  29736. var deltaPosition = mesh.position.subtract(bbox.center);
  29737. //calculate rotation to fit Oimo's needs (Euler...)
  29738. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29739. //get the correct bounding box
  29740. var oldQuaternion = mesh.rotationQuaternion;
  29741. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29742. mesh.computeWorldMatrix(true);
  29743. var bodyConfig = {
  29744. name: mesh.uniqueId,
  29745. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  29746. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  29747. move: options.mass != 0,
  29748. config: [options.mass, options.friction, options.restitution],
  29749. world: this._world
  29750. };
  29751. // register mesh
  29752. switch (impostor) {
  29753. case BABYLON.PhysicsEngine.SphereImpostor:
  29754. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29755. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29756. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29757. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29758. bodyConfig.type = 'sphere';
  29759. bodyConfig.size = [size];
  29760. break;
  29761. case BABYLON.PhysicsEngine.PlaneImpostor:
  29762. //Oimo "fakes" a cylinder as a box, so why don't we!
  29763. case BABYLON.PhysicsEngine.CylinderImpostor:
  29764. case BABYLON.PhysicsEngine.BoxImpostor:
  29765. var min = bbox.minimumWorld;
  29766. var max = bbox.maximumWorld;
  29767. var box = max.subtract(min);
  29768. var sizeX = this._checkWithEpsilon(box.x);
  29769. var sizeY = this._checkWithEpsilon(box.y);
  29770. var sizeZ = this._checkWithEpsilon(box.z);
  29771. bodyConfig.type = 'box';
  29772. bodyConfig.size = [sizeX, sizeY, sizeZ];
  29773. break;
  29774. }
  29775. var body = new OIMO.Body(bodyConfig);
  29776. //We have to access the rigid body's properties to set the quaternion.
  29777. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  29778. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  29779. //TEST
  29780. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  29781. //update the internal rotation matrix
  29782. //body.body.syncShapes();
  29783. this._registeredMeshes.push({
  29784. mesh: mesh,
  29785. body: body,
  29786. delta: deltaPosition
  29787. });
  29788. //for the sake of consistency.
  29789. mesh.rotationQuaternion = oldQuaternion;
  29790. return body;
  29791. };
  29792. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  29793. var types = [], sizes = [], positions = [], rotations = [];
  29794. var initialMesh = parts[0].mesh;
  29795. for (var index = 0; index < parts.length; index++) {
  29796. var part = parts[index];
  29797. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  29798. types.push(bodyParameters.type);
  29799. sizes.push.apply(sizes, bodyParameters.size);
  29800. positions.push.apply(positions, bodyParameters.pos);
  29801. rotations.push.apply(rotations, bodyParameters.rot);
  29802. }
  29803. var body = new OIMO.Body({
  29804. name: initialMesh.uniqueId,
  29805. type: types,
  29806. size: sizes,
  29807. pos: positions,
  29808. rot: rotations,
  29809. move: options.mass != 0,
  29810. config: [options.mass, options.friction, options.restitution],
  29811. world: this._world
  29812. });
  29813. //Reset the body's rotation to be of the initial mesh's.
  29814. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  29815. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  29816. this._registeredMeshes.push({
  29817. mesh: initialMesh,
  29818. body: body
  29819. });
  29820. return body;
  29821. };
  29822. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  29823. var mesh = part.mesh;
  29824. if (!mesh.rotationQuaternion) {
  29825. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29826. }
  29827. // We need the bounding box/sphere info to compute the physics body
  29828. mesh.computeWorldMatrix(true);
  29829. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  29830. var bodyParameters = {
  29831. name: mesh.uniqueId,
  29832. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  29833. //A bug in Oimo (Body class) prevents us from using rot directly.
  29834. rot: [0, 0, 0],
  29835. //For future reference, if the bug will ever be fixed.
  29836. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  29837. };
  29838. var oldQuaternion = mesh.rotationQuaternion;
  29839. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29840. mesh.computeWorldMatrix(true);
  29841. switch (part.impostor) {
  29842. case BABYLON.PhysicsEngine.SphereImpostor:
  29843. var bbox = mesh.getBoundingInfo().boundingBox;
  29844. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29845. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29846. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29847. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  29848. bodyParameters.type = 'sphere';
  29849. bodyParameters.size = [size, size, size];
  29850. break;
  29851. case BABYLON.PhysicsEngine.PlaneImpostor:
  29852. case BABYLON.PhysicsEngine.CylinderImpostor:
  29853. case BABYLON.PhysicsEngine.BoxImpostor:
  29854. bbox = mesh.getBoundingInfo().boundingBox;
  29855. var min = bbox.minimumWorld;
  29856. var max = bbox.maximumWorld;
  29857. var box = max.subtract(min);
  29858. var sizeX = this._checkWithEpsilon(box.x);
  29859. var sizeY = this._checkWithEpsilon(box.y);
  29860. var sizeZ = this._checkWithEpsilon(box.z);
  29861. bodyParameters.type = 'box';
  29862. bodyParameters.size = [sizeX, sizeY, sizeZ];
  29863. break;
  29864. }
  29865. mesh.rotationQuaternion = oldQuaternion;
  29866. return bodyParameters;
  29867. };
  29868. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  29869. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29870. var registeredMesh = this._registeredMeshes[index];
  29871. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29872. if (registeredMesh.body) {
  29873. this._world.removeRigidBody(registeredMesh.body.body);
  29874. this._unbindBody(registeredMesh.body);
  29875. }
  29876. this._registeredMeshes.splice(index, 1);
  29877. return;
  29878. }
  29879. }
  29880. };
  29881. OimoJSPlugin.prototype._unbindBody = function (body) {
  29882. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29883. var registeredMesh = this._registeredMeshes[index];
  29884. if (registeredMesh.body === body) {
  29885. registeredMesh.body = null;
  29886. }
  29887. }
  29888. };
  29889. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  29890. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29891. var registeredMesh = this._registeredMeshes[index];
  29892. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29893. // Get object mass to have a behaviour similar to cannon.js
  29894. var mass = registeredMesh.body.body.massInfo.mass;
  29895. // The force is scaled with the mass of object
  29896. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  29897. return;
  29898. }
  29899. }
  29900. };
  29901. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  29902. var body1 = null, body2 = null;
  29903. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29904. var registeredMesh = this._registeredMeshes[index];
  29905. if (registeredMesh.mesh === mesh1) {
  29906. body1 = registeredMesh.body.body;
  29907. }
  29908. else if (registeredMesh.mesh === mesh2) {
  29909. body2 = registeredMesh.body.body;
  29910. }
  29911. }
  29912. if (!body1 || !body2) {
  29913. return false;
  29914. }
  29915. if (!options) {
  29916. options = {};
  29917. }
  29918. new OIMO.Link({
  29919. type: options.type,
  29920. body1: body1,
  29921. body2: body2,
  29922. min: options.min,
  29923. max: options.max,
  29924. axe1: options.axe1,
  29925. axe2: options.axe2,
  29926. pos1: [pivot1.x, pivot1.y, pivot1.z],
  29927. pos2: [pivot2.x, pivot2.y, pivot2.z],
  29928. collision: options.collision,
  29929. spring: options.spring,
  29930. world: this._world
  29931. });
  29932. return true;
  29933. };
  29934. OimoJSPlugin.prototype.dispose = function () {
  29935. this._world.clear();
  29936. while (this._registeredMeshes.length) {
  29937. this.unregisterMesh(this._registeredMeshes[0].mesh);
  29938. }
  29939. };
  29940. OimoJSPlugin.prototype.isSupported = function () {
  29941. return OIMO !== undefined;
  29942. };
  29943. OimoJSPlugin.prototype.getWorldObject = function () {
  29944. return this._world;
  29945. };
  29946. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  29947. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29948. var registeredMesh = this._registeredMeshes[index];
  29949. if (registeredMesh.mesh === mesh) {
  29950. return registeredMesh.body;
  29951. }
  29952. }
  29953. return null;
  29954. };
  29955. OimoJSPlugin.prototype._getLastShape = function (body) {
  29956. var lastShape = body.shapes;
  29957. while (lastShape.next) {
  29958. lastShape = lastShape.next;
  29959. }
  29960. return lastShape;
  29961. };
  29962. OimoJSPlugin.prototype.runOneStep = function (time) {
  29963. this._world.step();
  29964. // Update the position of all registered meshes
  29965. var i = this._registeredMeshes.length;
  29966. var m;
  29967. while (i--) {
  29968. var body = this._registeredMeshes[i].body.body;
  29969. var mesh = this._registeredMeshes[i].mesh;
  29970. if (!this._registeredMeshes[i].delta) {
  29971. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  29972. }
  29973. if (!body.sleeping) {
  29974. //TODO check that
  29975. if (body.shapes.next) {
  29976. var parentShape = this._getLastShape(body);
  29977. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  29978. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  29979. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  29980. }
  29981. else {
  29982. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  29983. }
  29984. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  29985. mesh.computeWorldMatrix();
  29986. }
  29987. //check if the collide callback is set.
  29988. if (mesh.onPhysicsCollide) {
  29989. var meshUniqueName = mesh.uniqueId;
  29990. var contact = this._world.contacts;
  29991. while (contact !== null) {
  29992. //is this body colliding with any other?
  29993. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  29994. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  29995. //get the mesh and execute the callback
  29996. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  29997. if (otherMesh)
  29998. mesh.onPhysicsCollide(otherMesh, contact);
  29999. }
  30000. contact = contact.next;
  30001. }
  30002. }
  30003. }
  30004. };
  30005. return OimoJSPlugin;
  30006. })();
  30007. BABYLON.OimoJSPlugin = OimoJSPlugin;
  30008. })(BABYLON || (BABYLON = {}));
  30009. var BABYLON;
  30010. (function (BABYLON) {
  30011. var DisplayPassPostProcess = (function (_super) {
  30012. __extends(DisplayPassPostProcess, _super);
  30013. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30014. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  30015. }
  30016. return DisplayPassPostProcess;
  30017. })(BABYLON.PostProcess);
  30018. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  30019. })(BABYLON || (BABYLON = {}));
  30020. var BABYLON;
  30021. (function (BABYLON) {
  30022. var SimplificationSettings = (function () {
  30023. function SimplificationSettings(quality, distance, optimizeMesh) {
  30024. this.quality = quality;
  30025. this.distance = distance;
  30026. this.optimizeMesh = optimizeMesh;
  30027. }
  30028. return SimplificationSettings;
  30029. })();
  30030. BABYLON.SimplificationSettings = SimplificationSettings;
  30031. var SimplificationQueue = (function () {
  30032. function SimplificationQueue() {
  30033. this.running = false;
  30034. this._simplificationArray = [];
  30035. }
  30036. SimplificationQueue.prototype.addTask = function (task) {
  30037. this._simplificationArray.push(task);
  30038. };
  30039. SimplificationQueue.prototype.executeNext = function () {
  30040. var task = this._simplificationArray.pop();
  30041. if (task) {
  30042. this.running = true;
  30043. this.runSimplification(task);
  30044. }
  30045. else {
  30046. this.running = false;
  30047. }
  30048. };
  30049. SimplificationQueue.prototype.runSimplification = function (task) {
  30050. var _this = this;
  30051. if (task.parallelProcessing) {
  30052. //parallel simplifier
  30053. task.settings.forEach(function (setting) {
  30054. var simplifier = _this.getSimplifier(task);
  30055. simplifier.simplify(setting, function (newMesh) {
  30056. task.mesh.addLODLevel(setting.distance, newMesh);
  30057. newMesh.isVisible = true;
  30058. //check if it is the last
  30059. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30060. //all done, run the success callback.
  30061. task.successCallback();
  30062. }
  30063. _this.executeNext();
  30064. });
  30065. });
  30066. }
  30067. else {
  30068. //single simplifier.
  30069. var simplifier = this.getSimplifier(task);
  30070. var runDecimation = function (setting, callback) {
  30071. simplifier.simplify(setting, function (newMesh) {
  30072. task.mesh.addLODLevel(setting.distance, newMesh);
  30073. newMesh.isVisible = true;
  30074. //run the next quality level
  30075. callback();
  30076. });
  30077. };
  30078. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30079. runDecimation(task.settings[loop.index], function () {
  30080. loop.executeNext();
  30081. });
  30082. }, function () {
  30083. //execution ended, run the success callback.
  30084. if (task.successCallback) {
  30085. task.successCallback();
  30086. }
  30087. _this.executeNext();
  30088. });
  30089. }
  30090. };
  30091. SimplificationQueue.prototype.getSimplifier = function (task) {
  30092. switch (task.simplificationType) {
  30093. case SimplificationType.QUADRATIC:
  30094. default:
  30095. return new QuadraticErrorSimplification(task.mesh);
  30096. }
  30097. };
  30098. return SimplificationQueue;
  30099. })();
  30100. BABYLON.SimplificationQueue = SimplificationQueue;
  30101. /**
  30102. * The implemented types of simplification.
  30103. * At the moment only Quadratic Error Decimation is implemented.
  30104. */
  30105. (function (SimplificationType) {
  30106. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30107. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30108. var SimplificationType = BABYLON.SimplificationType;
  30109. var DecimationTriangle = (function () {
  30110. function DecimationTriangle(vertices) {
  30111. this.vertices = vertices;
  30112. this.error = new Array(4);
  30113. this.deleted = false;
  30114. this.isDirty = false;
  30115. this.deletePending = false;
  30116. this.borderFactor = 0;
  30117. }
  30118. return DecimationTriangle;
  30119. })();
  30120. BABYLON.DecimationTriangle = DecimationTriangle;
  30121. var DecimationVertex = (function () {
  30122. function DecimationVertex(position, id) {
  30123. this.position = position;
  30124. this.id = id;
  30125. this.isBorder = true;
  30126. this.q = new QuadraticMatrix();
  30127. this.triangleCount = 0;
  30128. this.triangleStart = 0;
  30129. this.originalOffsets = [];
  30130. }
  30131. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30132. this.position.copyFrom(newPosition);
  30133. };
  30134. return DecimationVertex;
  30135. })();
  30136. BABYLON.DecimationVertex = DecimationVertex;
  30137. var QuadraticMatrix = (function () {
  30138. function QuadraticMatrix(data) {
  30139. this.data = new Array(10);
  30140. for (var i = 0; i < 10; ++i) {
  30141. if (data && data[i]) {
  30142. this.data[i] = data[i];
  30143. }
  30144. else {
  30145. this.data[i] = 0;
  30146. }
  30147. }
  30148. }
  30149. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30150. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30151. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30152. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30153. return det;
  30154. };
  30155. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30156. for (var i = 0; i < 10; ++i) {
  30157. this.data[i] += matrix.data[i];
  30158. }
  30159. };
  30160. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30161. for (var i = 0; i < 10; ++i) {
  30162. this.data[i] += data[i];
  30163. }
  30164. };
  30165. QuadraticMatrix.prototype.add = function (matrix) {
  30166. var m = new QuadraticMatrix();
  30167. for (var i = 0; i < 10; ++i) {
  30168. m.data[i] = this.data[i] + matrix.data[i];
  30169. }
  30170. return m;
  30171. };
  30172. QuadraticMatrix.FromData = function (a, b, c, d) {
  30173. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30174. };
  30175. //returning an array to avoid garbage collection
  30176. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30177. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30178. };
  30179. return QuadraticMatrix;
  30180. })();
  30181. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30182. var Reference = (function () {
  30183. function Reference(vertexId, triangleId) {
  30184. this.vertexId = vertexId;
  30185. this.triangleId = triangleId;
  30186. }
  30187. return Reference;
  30188. })();
  30189. BABYLON.Reference = Reference;
  30190. /**
  30191. * An implementation of the Quadratic Error simplification algorithm.
  30192. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30193. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30194. * @author RaananW
  30195. */
  30196. var QuadraticErrorSimplification = (function () {
  30197. function QuadraticErrorSimplification(_mesh) {
  30198. this._mesh = _mesh;
  30199. this.initialized = false;
  30200. this.syncIterations = 5000;
  30201. this.aggressiveness = 7;
  30202. this.decimationIterations = 100;
  30203. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30204. }
  30205. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30206. var _this = this;
  30207. this.initDecimatedMesh();
  30208. //iterating through the submeshes array, one after the other.
  30209. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30210. _this.initWithMesh(loop.index, function () {
  30211. _this.runDecimation(settings, loop.index, function () {
  30212. loop.executeNext();
  30213. });
  30214. }, settings.optimizeMesh);
  30215. }, function () {
  30216. setTimeout(function () {
  30217. successCallback(_this._reconstructedMesh);
  30218. }, 0);
  30219. });
  30220. };
  30221. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30222. var _this = this;
  30223. var gCount = 0;
  30224. triangle.vertices.forEach(function (vertex) {
  30225. var count = 0;
  30226. var vPos = vertex.position;
  30227. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30228. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30229. ++count;
  30230. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30231. ++count;
  30232. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30233. ++count;
  30234. if (count > 1) {
  30235. ++gCount;
  30236. }
  30237. ;
  30238. });
  30239. if (gCount > 1) {
  30240. console.log(triangle, gCount);
  30241. }
  30242. return gCount > 1;
  30243. };
  30244. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30245. var _this = this;
  30246. var targetCount = ~~(this.triangles.length * settings.quality);
  30247. var deletedTriangles = 0;
  30248. var triangleCount = this.triangles.length;
  30249. var iterationFunction = function (iteration, callback) {
  30250. setTimeout(function () {
  30251. if (iteration % 5 === 0) {
  30252. _this.updateMesh(iteration === 0);
  30253. }
  30254. for (var i = 0; i < _this.triangles.length; ++i) {
  30255. _this.triangles[i].isDirty = false;
  30256. }
  30257. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30258. var trianglesIterator = function (i) {
  30259. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30260. var t = _this.triangles[tIdx];
  30261. if (!t)
  30262. return;
  30263. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30264. return;
  30265. }
  30266. for (var j = 0; j < 3; ++j) {
  30267. if (t.error[j] < threshold) {
  30268. var deleted0 = [];
  30269. var deleted1 = [];
  30270. var v0 = t.vertices[j];
  30271. var v1 = t.vertices[(j + 1) % 3];
  30272. if (v0.isBorder !== v1.isBorder)
  30273. continue;
  30274. var p = BABYLON.Vector3.Zero();
  30275. var n = BABYLON.Vector3.Zero();
  30276. var uv = BABYLON.Vector2.Zero();
  30277. var color = new BABYLON.Color4(0, 0, 0, 1);
  30278. _this.calculateError(v0, v1, p, n, uv, color);
  30279. var delTr = [];
  30280. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30281. continue;
  30282. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30283. continue;
  30284. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30285. continue;
  30286. var uniqueArray = [];
  30287. delTr.forEach(function (deletedT) {
  30288. if (uniqueArray.indexOf(deletedT) === -1) {
  30289. deletedT.deletePending = true;
  30290. uniqueArray.push(deletedT);
  30291. }
  30292. });
  30293. if (uniqueArray.length % 2 !== 0) {
  30294. continue;
  30295. }
  30296. v0.q = v1.q.add(v0.q);
  30297. v0.updatePosition(p);
  30298. var tStart = _this.references.length;
  30299. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30300. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30301. var tCount = _this.references.length - tStart;
  30302. if (tCount <= v0.triangleCount) {
  30303. if (tCount) {
  30304. for (var c = 0; c < tCount; c++) {
  30305. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30306. }
  30307. }
  30308. }
  30309. else {
  30310. v0.triangleStart = tStart;
  30311. }
  30312. v0.triangleCount = tCount;
  30313. break;
  30314. }
  30315. }
  30316. };
  30317. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30318. }, 0);
  30319. };
  30320. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30321. if (triangleCount - deletedTriangles <= targetCount)
  30322. loop.breakLoop();
  30323. else {
  30324. iterationFunction(loop.index, function () {
  30325. loop.executeNext();
  30326. });
  30327. }
  30328. }, function () {
  30329. setTimeout(function () {
  30330. //reconstruct this part of the mesh
  30331. _this.reconstructMesh(submeshIndex);
  30332. successCallback();
  30333. }, 0);
  30334. });
  30335. };
  30336. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30337. var _this = this;
  30338. this.vertices = [];
  30339. this.triangles = [];
  30340. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30341. var indices = this._mesh.getIndices();
  30342. var submesh = this._mesh.subMeshes[submeshIndex];
  30343. var findInVertices = function (positionToSearch) {
  30344. if (optimizeMesh) {
  30345. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30346. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30347. return _this.vertices[ii];
  30348. }
  30349. }
  30350. }
  30351. return null;
  30352. };
  30353. var vertexReferences = [];
  30354. var vertexInit = function (i) {
  30355. var offset = i + submesh.verticesStart;
  30356. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30357. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30358. vertex.originalOffsets.push(offset);
  30359. if (vertex.id === _this.vertices.length) {
  30360. _this.vertices.push(vertex);
  30361. }
  30362. vertexReferences.push(vertex.id);
  30363. };
  30364. //var totalVertices = mesh.getTotalVertices();
  30365. var totalVertices = submesh.verticesCount;
  30366. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30367. var indicesInit = function (i) {
  30368. var offset = (submesh.indexStart / 3) + i;
  30369. var pos = (offset * 3);
  30370. var i0 = indices[pos + 0];
  30371. var i1 = indices[pos + 1];
  30372. var i2 = indices[pos + 2];
  30373. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30374. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30375. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30376. var triangle = new DecimationTriangle([v0, v1, v2]);
  30377. triangle.originalOffset = pos;
  30378. _this.triangles.push(triangle);
  30379. };
  30380. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30381. _this.init(callback);
  30382. });
  30383. });
  30384. };
  30385. QuadraticErrorSimplification.prototype.init = function (callback) {
  30386. var _this = this;
  30387. var triangleInit1 = function (i) {
  30388. var t = _this.triangles[i];
  30389. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30390. for (var j = 0; j < 3; j++) {
  30391. 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))));
  30392. }
  30393. };
  30394. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30395. var triangleInit2 = function (i) {
  30396. var t = _this.triangles[i];
  30397. for (var j = 0; j < 3; ++j) {
  30398. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30399. }
  30400. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30401. };
  30402. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30403. _this.initialized = true;
  30404. callback();
  30405. });
  30406. });
  30407. };
  30408. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30409. var newTriangles = [];
  30410. var i;
  30411. for (i = 0; i < this.vertices.length; ++i) {
  30412. this.vertices[i].triangleCount = 0;
  30413. }
  30414. var t;
  30415. var j;
  30416. for (i = 0; i < this.triangles.length; ++i) {
  30417. if (!this.triangles[i].deleted) {
  30418. t = this.triangles[i];
  30419. for (j = 0; j < 3; ++j) {
  30420. t.vertices[j].triangleCount = 1;
  30421. }
  30422. newTriangles.push(t);
  30423. }
  30424. }
  30425. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30426. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30427. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30428. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30429. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30430. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30431. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30432. var vertexCount = 0;
  30433. for (i = 0; i < this.vertices.length; ++i) {
  30434. var vertex = this.vertices[i];
  30435. vertex.id = vertexCount;
  30436. if (vertex.triangleCount) {
  30437. vertex.originalOffsets.forEach(function (originalOffset) {
  30438. newPositionData.push(vertex.position.x);
  30439. newPositionData.push(vertex.position.y);
  30440. newPositionData.push(vertex.position.z);
  30441. newNormalData.push(normalData[originalOffset * 3]);
  30442. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30443. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30444. if (uvs && uvs.length) {
  30445. newUVsData.push(uvs[(originalOffset * 2)]);
  30446. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30447. }
  30448. else if (colorsData && colorsData.length) {
  30449. newColorsData.push(colorsData[(originalOffset * 4)]);
  30450. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30451. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30452. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30453. }
  30454. ++vertexCount;
  30455. });
  30456. }
  30457. }
  30458. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30459. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30460. var submeshesArray = this._reconstructedMesh.subMeshes;
  30461. this._reconstructedMesh.subMeshes = [];
  30462. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30463. var originalIndices = this._mesh.getIndices();
  30464. for (i = 0; i < newTriangles.length; ++i) {
  30465. t = newTriangles[i]; //now get the new referencing point for each vertex
  30466. [0, 1, 2].forEach(function (idx) {
  30467. var id = originalIndices[t.originalOffset + idx];
  30468. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30469. if (offset < 0)
  30470. offset = 0;
  30471. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30472. });
  30473. }
  30474. //overwriting the old vertex buffers and indices.
  30475. this._reconstructedMesh.setIndices(newIndicesArray);
  30476. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30477. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30478. if (newUVsData.length > 0)
  30479. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30480. if (newColorsData.length > 0)
  30481. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30482. //create submesh
  30483. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30484. if (submeshIndex > 0) {
  30485. this._reconstructedMesh.subMeshes = [];
  30486. submeshesArray.forEach(function (submesh) {
  30487. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30488. });
  30489. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30490. }
  30491. };
  30492. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30493. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30494. this._reconstructedMesh.material = this._mesh.material;
  30495. this._reconstructedMesh.parent = this._mesh.parent;
  30496. this._reconstructedMesh.isVisible = false;
  30497. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  30498. };
  30499. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30500. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30501. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30502. if (t.deleted)
  30503. continue;
  30504. var s = this.references[vertex1.triangleStart + i].vertexId;
  30505. var v1 = t.vertices[(s + 1) % 3];
  30506. var v2 = t.vertices[(s + 2) % 3];
  30507. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30508. deletedArray[i] = true;
  30509. delTr.push(t);
  30510. continue;
  30511. }
  30512. var d1 = v1.position.subtract(point);
  30513. d1 = d1.normalize();
  30514. var d2 = v2.position.subtract(point);
  30515. d2 = d2.normalize();
  30516. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30517. return true;
  30518. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30519. deletedArray[i] = false;
  30520. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30521. return true;
  30522. }
  30523. return false;
  30524. };
  30525. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30526. var newDeleted = deletedTriangles;
  30527. for (var i = 0; i < vertex.triangleCount; ++i) {
  30528. var ref = this.references[vertex.triangleStart + i];
  30529. var t = this.triangles[ref.triangleId];
  30530. if (t.deleted)
  30531. continue;
  30532. if (deletedArray[i] && t.deletePending) {
  30533. t.deleted = true;
  30534. newDeleted++;
  30535. continue;
  30536. }
  30537. t.vertices[ref.vertexId] = origVertex;
  30538. t.isDirty = true;
  30539. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30540. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30541. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30542. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30543. this.references.push(ref);
  30544. }
  30545. return newDeleted;
  30546. };
  30547. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30548. for (var i = 0; i < this.vertices.length; ++i) {
  30549. var vCount = [];
  30550. var vId = [];
  30551. var v = this.vertices[i];
  30552. var j;
  30553. for (j = 0; j < v.triangleCount; ++j) {
  30554. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30555. for (var ii = 0; ii < 3; ii++) {
  30556. var ofs = 0;
  30557. var vv = triangle.vertices[ii];
  30558. while (ofs < vCount.length) {
  30559. if (vId[ofs] === vv.id)
  30560. break;
  30561. ++ofs;
  30562. }
  30563. if (ofs === vCount.length) {
  30564. vCount.push(1);
  30565. vId.push(vv.id);
  30566. }
  30567. else {
  30568. vCount[ofs]++;
  30569. }
  30570. }
  30571. }
  30572. for (j = 0; j < vCount.length; ++j) {
  30573. if (vCount[j] === 1) {
  30574. this.vertices[vId[j]].isBorder = true;
  30575. }
  30576. else {
  30577. this.vertices[vId[j]].isBorder = false;
  30578. }
  30579. }
  30580. }
  30581. };
  30582. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30583. if (identifyBorders === void 0) { identifyBorders = false; }
  30584. var i;
  30585. if (!identifyBorders) {
  30586. var newTrianglesVector = [];
  30587. for (i = 0; i < this.triangles.length; ++i) {
  30588. if (!this.triangles[i].deleted) {
  30589. newTrianglesVector.push(this.triangles[i]);
  30590. }
  30591. }
  30592. this.triangles = newTrianglesVector;
  30593. }
  30594. for (i = 0; i < this.vertices.length; ++i) {
  30595. this.vertices[i].triangleCount = 0;
  30596. this.vertices[i].triangleStart = 0;
  30597. }
  30598. var t;
  30599. var j;
  30600. var v;
  30601. for (i = 0; i < this.triangles.length; ++i) {
  30602. t = this.triangles[i];
  30603. for (j = 0; j < 3; ++j) {
  30604. v = t.vertices[j];
  30605. v.triangleCount++;
  30606. }
  30607. }
  30608. var tStart = 0;
  30609. for (i = 0; i < this.vertices.length; ++i) {
  30610. this.vertices[i].triangleStart = tStart;
  30611. tStart += this.vertices[i].triangleCount;
  30612. this.vertices[i].triangleCount = 0;
  30613. }
  30614. var newReferences = new Array(this.triangles.length * 3);
  30615. for (i = 0; i < this.triangles.length; ++i) {
  30616. t = this.triangles[i];
  30617. for (j = 0; j < 3; ++j) {
  30618. v = t.vertices[j];
  30619. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30620. v.triangleCount++;
  30621. }
  30622. }
  30623. this.references = newReferences;
  30624. if (identifyBorders) {
  30625. this.identifyBorder();
  30626. }
  30627. };
  30628. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30629. var x = point.x;
  30630. var y = point.y;
  30631. var z = point.z;
  30632. 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
  30633. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30634. };
  30635. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30636. var q = vertex1.q.add(vertex2.q);
  30637. var border = vertex1.isBorder && vertex2.isBorder;
  30638. var error = 0;
  30639. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30640. if (qDet !== 0 && !border) {
  30641. if (!pointResult) {
  30642. pointResult = BABYLON.Vector3.Zero();
  30643. }
  30644. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30645. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30646. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30647. error = this.vertexError(q, pointResult);
  30648. }
  30649. else {
  30650. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30651. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30652. var error1 = this.vertexError(q, vertex1.position);
  30653. var error2 = this.vertexError(q, vertex2.position);
  30654. var error3 = this.vertexError(q, p3);
  30655. error = Math.min(error1, error2, error3);
  30656. if (error === error1) {
  30657. if (pointResult) {
  30658. pointResult.copyFrom(vertex1.position);
  30659. }
  30660. }
  30661. else if (error === error2) {
  30662. if (pointResult) {
  30663. pointResult.copyFrom(vertex2.position);
  30664. }
  30665. }
  30666. else {
  30667. if (pointResult) {
  30668. pointResult.copyFrom(p3);
  30669. }
  30670. }
  30671. }
  30672. return error;
  30673. };
  30674. return QuadraticErrorSimplification;
  30675. })();
  30676. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30677. })(BABYLON || (BABYLON = {}));
  30678. var BABYLON;
  30679. (function (BABYLON) {
  30680. var serializedGeometries = [];
  30681. var serializeGeometry = function (geometry, serializationGeometries) {
  30682. if (serializedGeometries[geometry.id]) {
  30683. return;
  30684. }
  30685. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  30686. serializationGeometries.boxes.push(geometry.serialize());
  30687. }
  30688. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  30689. serializationGeometries.spheres.push(geometry.serialize());
  30690. }
  30691. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  30692. serializationGeometries.cylinders.push(geometry.serialize());
  30693. }
  30694. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  30695. serializationGeometries.toruses.push(geometry.serialize());
  30696. }
  30697. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  30698. serializationGeometries.grounds.push(geometry.serialize());
  30699. }
  30700. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  30701. serializationGeometries.planes.push(geometry.serialize());
  30702. }
  30703. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  30704. serializationGeometries.torusKnots.push(geometry.serialize());
  30705. }
  30706. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  30707. throw new Error("Unknown primitive type");
  30708. }
  30709. else {
  30710. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  30711. }
  30712. serializedGeometries[geometry.id] = true;
  30713. };
  30714. var serializeMesh = function (mesh, serializationScene) {
  30715. var serializationObject = {};
  30716. serializationObject.name = mesh.name;
  30717. serializationObject.id = mesh.id;
  30718. if (BABYLON.Tags.HasTags(mesh)) {
  30719. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30720. }
  30721. serializationObject.position = mesh.position.asArray();
  30722. if (mesh.rotationQuaternion) {
  30723. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30724. }
  30725. else if (mesh.rotation) {
  30726. serializationObject.rotation = mesh.rotation.asArray();
  30727. }
  30728. serializationObject.scaling = mesh.scaling.asArray();
  30729. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30730. serializationObject.isEnabled = mesh.isEnabled();
  30731. serializationObject.isVisible = mesh.isVisible;
  30732. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30733. serializationObject.pickable = mesh.isPickable;
  30734. serializationObject.receiveShadows = mesh.receiveShadows;
  30735. serializationObject.billboardMode = mesh.billboardMode;
  30736. serializationObject.visibility = mesh.visibility;
  30737. serializationObject.checkCollisions = mesh.checkCollisions;
  30738. // Parent
  30739. if (mesh.parent) {
  30740. serializationObject.parentId = mesh.parent.id;
  30741. }
  30742. // Geometry
  30743. var geometry = mesh._geometry;
  30744. if (geometry) {
  30745. var geometryId = geometry.id;
  30746. serializationObject.geometryId = geometryId;
  30747. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30748. // 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
  30749. serializeGeometry(geometry, serializationScene.geometries);
  30750. }
  30751. // SubMeshes
  30752. serializationObject.subMeshes = [];
  30753. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30754. var subMesh = mesh.subMeshes[subIndex];
  30755. serializationObject.subMeshes.push({
  30756. materialIndex: subMesh.materialIndex,
  30757. verticesStart: subMesh.verticesStart,
  30758. verticesCount: subMesh.verticesCount,
  30759. indexStart: subMesh.indexStart,
  30760. indexCount: subMesh.indexCount
  30761. });
  30762. }
  30763. }
  30764. // Material
  30765. if (mesh.material) {
  30766. serializationObject.materialId = mesh.material.id;
  30767. }
  30768. else {
  30769. mesh.material = null;
  30770. }
  30771. // Skeleton
  30772. if (mesh.skeleton) {
  30773. serializationObject.skeletonId = mesh.skeleton.id;
  30774. }
  30775. // Physics
  30776. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30777. serializationObject.physicsMass = mesh.getPhysicsMass();
  30778. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30779. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30780. switch (mesh.getPhysicsImpostor()) {
  30781. case BABYLON.PhysicsEngine.BoxImpostor:
  30782. serializationObject.physicsImpostor = 1;
  30783. break;
  30784. case BABYLON.PhysicsEngine.SphereImpostor:
  30785. serializationObject.physicsImpostor = 2;
  30786. break;
  30787. }
  30788. }
  30789. // Instances
  30790. serializationObject.instances = [];
  30791. for (var index = 0; index < mesh.instances.length; index++) {
  30792. var instance = mesh.instances[index];
  30793. var serializationInstance = {
  30794. name: instance.name,
  30795. position: instance.position.asArray(),
  30796. scaling: instance.scaling.asArray()
  30797. };
  30798. if (instance.rotationQuaternion) {
  30799. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30800. }
  30801. else if (instance.rotation) {
  30802. serializationInstance.rotation = instance.rotation.asArray();
  30803. }
  30804. serializationObject.instances.push(serializationInstance);
  30805. // Animations
  30806. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30807. serializationInstance.ranges = instance.serializeAnimationRanges();
  30808. }
  30809. // Animations
  30810. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  30811. serializationObject.ranges = mesh.serializeAnimationRanges();
  30812. // Layer mask
  30813. serializationObject.layerMask = mesh.layerMask;
  30814. return serializationObject;
  30815. };
  30816. var finalizeSingleMesh = function (mesh, serializationObject) {
  30817. //only works if the mesh is already loaded
  30818. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30819. //serialize material
  30820. if (mesh.material) {
  30821. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30822. serializationObject.materials = serializationObject.materials || [];
  30823. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30824. serializationObject.materials.push(mesh.material.serialize());
  30825. }
  30826. }
  30827. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30828. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30829. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30830. serializationObject.multiMaterials.push(mesh.material.serialize());
  30831. }
  30832. }
  30833. }
  30834. //serialize geometry
  30835. var geometry = mesh._geometry;
  30836. if (geometry) {
  30837. if (!serializationObject.geometries) {
  30838. serializationObject.geometries = {};
  30839. serializationObject.geometries.boxes = [];
  30840. serializationObject.geometries.spheres = [];
  30841. serializationObject.geometries.cylinders = [];
  30842. serializationObject.geometries.toruses = [];
  30843. serializationObject.geometries.grounds = [];
  30844. serializationObject.geometries.planes = [];
  30845. serializationObject.geometries.torusKnots = [];
  30846. serializationObject.geometries.vertexData = [];
  30847. }
  30848. serializeGeometry(geometry, serializationObject.geometries);
  30849. }
  30850. // Skeletons
  30851. if (mesh.skeleton) {
  30852. serializationObject.skeletons = serializationObject.skeletons || [];
  30853. serializationObject.skeletons.push(mesh.skeleton.serialize());
  30854. }
  30855. //serialize the actual mesh
  30856. serializationObject.meshes = serializationObject.meshes || [];
  30857. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30858. }
  30859. };
  30860. var SceneSerializer = (function () {
  30861. function SceneSerializer() {
  30862. }
  30863. SceneSerializer.Serialize = function (scene) {
  30864. var serializationObject = {};
  30865. // Scene
  30866. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30867. serializationObject.autoClear = scene.autoClear;
  30868. serializationObject.clearColor = scene.clearColor.asArray();
  30869. serializationObject.ambientColor = scene.ambientColor.asArray();
  30870. serializationObject.gravity = scene.gravity.asArray();
  30871. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  30872. serializationObject.workerCollisions = scene.workerCollisions;
  30873. // Fog
  30874. if (scene.fogMode && scene.fogMode !== 0) {
  30875. serializationObject.fogMode = scene.fogMode;
  30876. serializationObject.fogColor = scene.fogColor.asArray();
  30877. serializationObject.fogStart = scene.fogStart;
  30878. serializationObject.fogEnd = scene.fogEnd;
  30879. serializationObject.fogDensity = scene.fogDensity;
  30880. }
  30881. //Physics
  30882. if (scene.isPhysicsEnabled()) {
  30883. serializationObject.physicsEnabled = true;
  30884. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  30885. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  30886. }
  30887. // Lights
  30888. serializationObject.lights = [];
  30889. var index;
  30890. var light;
  30891. for (index = 0; index < scene.lights.length; index++) {
  30892. light = scene.lights[index];
  30893. serializationObject.lights.push(light.serialize());
  30894. }
  30895. // Cameras
  30896. serializationObject.cameras = [];
  30897. for (index = 0; index < scene.cameras.length; index++) {
  30898. var camera = scene.cameras[index];
  30899. serializationObject.cameras.push(camera.serialize());
  30900. }
  30901. if (scene.activeCamera) {
  30902. serializationObject.activeCameraID = scene.activeCamera.id;
  30903. }
  30904. // Materials
  30905. serializationObject.materials = [];
  30906. serializationObject.multiMaterials = [];
  30907. var material;
  30908. for (index = 0; index < scene.materials.length; index++) {
  30909. material = scene.materials[index];
  30910. serializationObject.materials.push(material.serialize());
  30911. }
  30912. // MultiMaterials
  30913. serializationObject.multiMaterials = [];
  30914. for (index = 0; index < scene.multiMaterials.length; index++) {
  30915. var multiMaterial = scene.multiMaterials[index];
  30916. serializationObject.multiMaterials.push(multiMaterial.serialize());
  30917. }
  30918. // Skeletons
  30919. serializationObject.skeletons = [];
  30920. for (index = 0; index < scene.skeletons.length; index++) {
  30921. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  30922. }
  30923. // Geometries
  30924. serializationObject.geometries = {};
  30925. serializationObject.geometries.boxes = [];
  30926. serializationObject.geometries.spheres = [];
  30927. serializationObject.geometries.cylinders = [];
  30928. serializationObject.geometries.toruses = [];
  30929. serializationObject.geometries.grounds = [];
  30930. serializationObject.geometries.planes = [];
  30931. serializationObject.geometries.torusKnots = [];
  30932. serializationObject.geometries.vertexData = [];
  30933. serializedGeometries = [];
  30934. var geometries = scene.getGeometries();
  30935. for (index = 0; index < geometries.length; index++) {
  30936. var geometry = geometries[index];
  30937. if (geometry.isReady()) {
  30938. serializeGeometry(geometry, serializationObject.geometries);
  30939. }
  30940. }
  30941. // Meshes
  30942. serializationObject.meshes = [];
  30943. for (index = 0; index < scene.meshes.length; index++) {
  30944. var abstractMesh = scene.meshes[index];
  30945. if (abstractMesh instanceof BABYLON.Mesh) {
  30946. var mesh = abstractMesh;
  30947. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30948. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30949. }
  30950. }
  30951. }
  30952. // Particles Systems
  30953. serializationObject.particleSystems = [];
  30954. for (index = 0; index < scene.particleSystems.length; index++) {
  30955. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  30956. }
  30957. // Lens flares
  30958. serializationObject.lensFlareSystems = [];
  30959. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30960. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  30961. }
  30962. // Shadows
  30963. serializationObject.shadowGenerators = [];
  30964. for (index = 0; index < scene.lights.length; index++) {
  30965. light = scene.lights[index];
  30966. if (light.getShadowGenerator()) {
  30967. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  30968. }
  30969. }
  30970. return serializationObject;
  30971. };
  30972. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30973. if (withParents === void 0) { withParents = false; }
  30974. if (withChildren === void 0) { withChildren = false; }
  30975. var serializationObject = {};
  30976. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30977. if (withParents || withChildren) {
  30978. //deliberate for loop! not for each, appended should be processed as well.
  30979. for (var i = 0; i < toSerialize.length; ++i) {
  30980. if (withChildren) {
  30981. toSerialize[i].getDescendants().forEach(function (node) {
  30982. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30983. toSerialize.push(node);
  30984. }
  30985. });
  30986. }
  30987. //make sure the array doesn't contain the object already
  30988. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30989. toSerialize.push(toSerialize[i].parent);
  30990. }
  30991. }
  30992. }
  30993. toSerialize.forEach(function (mesh) {
  30994. finalizeSingleMesh(mesh, serializationObject);
  30995. });
  30996. return serializationObject;
  30997. };
  30998. return SceneSerializer;
  30999. })();
  31000. BABYLON.SceneSerializer = SceneSerializer;
  31001. })(BABYLON || (BABYLON = {}));
  31002. var BABYLON;
  31003. (function (BABYLON) {
  31004. // Unique ID when we import meshes from Babylon to CSG
  31005. var currentCSGMeshId = 0;
  31006. // # class Vertex
  31007. // Represents a vertex of a polygon. Use your own vertex class instead of this
  31008. // one to provide additional features like texture coordinates and vertex
  31009. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  31010. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  31011. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  31012. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  31013. // is not used anywhere else.
  31014. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  31015. var Vertex = (function () {
  31016. function Vertex(pos, normal, uv) {
  31017. this.pos = pos;
  31018. this.normal = normal;
  31019. this.uv = uv;
  31020. }
  31021. Vertex.prototype.clone = function () {
  31022. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  31023. };
  31024. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  31025. // orientation of a polygon is flipped.
  31026. Vertex.prototype.flip = function () {
  31027. this.normal = this.normal.scale(-1);
  31028. };
  31029. // Create a new vertex between this vertex and `other` by linearly
  31030. // interpolating all properties using a parameter of `t`. Subclasses should
  31031. // override this to interpolate additional properties.
  31032. Vertex.prototype.interpolate = function (other, t) {
  31033. 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));
  31034. };
  31035. return Vertex;
  31036. })();
  31037. // # class Plane
  31038. // Represents a plane in 3D space.
  31039. var Plane = (function () {
  31040. function Plane(normal, w) {
  31041. this.normal = normal;
  31042. this.w = w;
  31043. }
  31044. Plane.FromPoints = function (a, b, c) {
  31045. var v0 = c.subtract(a);
  31046. var v1 = b.subtract(a);
  31047. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  31048. return null;
  31049. }
  31050. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  31051. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  31052. };
  31053. Plane.prototype.clone = function () {
  31054. return new Plane(this.normal.clone(), this.w);
  31055. };
  31056. Plane.prototype.flip = function () {
  31057. this.normal.scaleInPlace(-1);
  31058. this.w = -this.w;
  31059. };
  31060. // Split `polygon` by this plane if needed, then put the polygon or polygon
  31061. // fragments in the appropriate lists. Coplanar polygons go into either
  31062. // `coplanarFront` or `coplanarBack` depending on their orientation with
  31063. // respect to this plane. Polygons in front or in back of this plane go into
  31064. // either `front` or `back`.
  31065. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  31066. var COPLANAR = 0;
  31067. var FRONT = 1;
  31068. var BACK = 2;
  31069. var SPANNING = 3;
  31070. // Classify each point as well as the entire polygon into one of the above
  31071. // four classes.
  31072. var polygonType = 0;
  31073. var types = [];
  31074. var i;
  31075. var t;
  31076. for (i = 0; i < polygon.vertices.length; i++) {
  31077. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  31078. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  31079. polygonType |= type;
  31080. types.push(type);
  31081. }
  31082. // Put the polygon in the correct list, splitting it when necessary.
  31083. switch (polygonType) {
  31084. case COPLANAR:
  31085. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  31086. break;
  31087. case FRONT:
  31088. front.push(polygon);
  31089. break;
  31090. case BACK:
  31091. back.push(polygon);
  31092. break;
  31093. case SPANNING:
  31094. var f = [], b = [];
  31095. for (i = 0; i < polygon.vertices.length; i++) {
  31096. var j = (i + 1) % polygon.vertices.length;
  31097. var ti = types[i], tj = types[j];
  31098. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  31099. if (ti !== BACK)
  31100. f.push(vi);
  31101. if (ti !== FRONT)
  31102. b.push(ti !== BACK ? vi.clone() : vi);
  31103. if ((ti | tj) === SPANNING) {
  31104. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31105. var v = vi.interpolate(vj, t);
  31106. f.push(v);
  31107. b.push(v.clone());
  31108. }
  31109. }
  31110. var poly;
  31111. if (f.length >= 3) {
  31112. poly = new Polygon(f, polygon.shared);
  31113. if (poly.plane)
  31114. front.push(poly);
  31115. }
  31116. if (b.length >= 3) {
  31117. poly = new Polygon(b, polygon.shared);
  31118. if (poly.plane)
  31119. back.push(poly);
  31120. }
  31121. break;
  31122. }
  31123. };
  31124. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31125. // point is on the plane.
  31126. Plane.EPSILON = 1e-5;
  31127. return Plane;
  31128. })();
  31129. // # class Polygon
  31130. // Represents a convex polygon. The vertices used to initialize a polygon must
  31131. // be coplanar and form a convex loop.
  31132. //
  31133. // Each convex polygon has a `shared` property, which is shared between all
  31134. // polygons that are clones of each other or were split from the same polygon.
  31135. // This can be used to define per-polygon properties (such as surface color).
  31136. var Polygon = (function () {
  31137. function Polygon(vertices, shared) {
  31138. this.vertices = vertices;
  31139. this.shared = shared;
  31140. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31141. }
  31142. Polygon.prototype.clone = function () {
  31143. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31144. return new Polygon(vertices, this.shared);
  31145. };
  31146. Polygon.prototype.flip = function () {
  31147. this.vertices.reverse().map(function (v) { v.flip(); });
  31148. this.plane.flip();
  31149. };
  31150. return Polygon;
  31151. })();
  31152. // # class Node
  31153. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31154. // by picking a polygon to split along. That polygon (and all other coplanar
  31155. // polygons) are added directly to that node and the other polygons are added to
  31156. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31157. // no distinction between internal and leaf nodes.
  31158. var Node = (function () {
  31159. function Node(polygons) {
  31160. this.plane = null;
  31161. this.front = null;
  31162. this.back = null;
  31163. this.polygons = [];
  31164. if (polygons) {
  31165. this.build(polygons);
  31166. }
  31167. }
  31168. Node.prototype.clone = function () {
  31169. var node = new Node();
  31170. node.plane = this.plane && this.plane.clone();
  31171. node.front = this.front && this.front.clone();
  31172. node.back = this.back && this.back.clone();
  31173. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31174. return node;
  31175. };
  31176. // Convert solid space to empty space and empty space to solid space.
  31177. Node.prototype.invert = function () {
  31178. for (var i = 0; i < this.polygons.length; i++) {
  31179. this.polygons[i].flip();
  31180. }
  31181. if (this.plane) {
  31182. this.plane.flip();
  31183. }
  31184. if (this.front) {
  31185. this.front.invert();
  31186. }
  31187. if (this.back) {
  31188. this.back.invert();
  31189. }
  31190. var temp = this.front;
  31191. this.front = this.back;
  31192. this.back = temp;
  31193. };
  31194. // Recursively remove all polygons in `polygons` that are inside this BSP
  31195. // tree.
  31196. Node.prototype.clipPolygons = function (polygons) {
  31197. if (!this.plane)
  31198. return polygons.slice();
  31199. var front = [], back = [];
  31200. for (var i = 0; i < polygons.length; i++) {
  31201. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31202. }
  31203. if (this.front) {
  31204. front = this.front.clipPolygons(front);
  31205. }
  31206. if (this.back) {
  31207. back = this.back.clipPolygons(back);
  31208. }
  31209. else {
  31210. back = [];
  31211. }
  31212. return front.concat(back);
  31213. };
  31214. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31215. // `bsp`.
  31216. Node.prototype.clipTo = function (bsp) {
  31217. this.polygons = bsp.clipPolygons(this.polygons);
  31218. if (this.front)
  31219. this.front.clipTo(bsp);
  31220. if (this.back)
  31221. this.back.clipTo(bsp);
  31222. };
  31223. // Return a list of all polygons in this BSP tree.
  31224. Node.prototype.allPolygons = function () {
  31225. var polygons = this.polygons.slice();
  31226. if (this.front)
  31227. polygons = polygons.concat(this.front.allPolygons());
  31228. if (this.back)
  31229. polygons = polygons.concat(this.back.allPolygons());
  31230. return polygons;
  31231. };
  31232. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31233. // new polygons are filtered down to the bottom of the tree and become new
  31234. // nodes there. Each set of polygons is partitioned using the first polygon
  31235. // (no heuristic is used to pick a good split).
  31236. Node.prototype.build = function (polygons) {
  31237. if (!polygons.length)
  31238. return;
  31239. if (!this.plane)
  31240. this.plane = polygons[0].plane.clone();
  31241. var front = [], back = [];
  31242. for (var i = 0; i < polygons.length; i++) {
  31243. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31244. }
  31245. if (front.length) {
  31246. if (!this.front)
  31247. this.front = new Node();
  31248. this.front.build(front);
  31249. }
  31250. if (back.length) {
  31251. if (!this.back)
  31252. this.back = new Node();
  31253. this.back.build(back);
  31254. }
  31255. };
  31256. return Node;
  31257. })();
  31258. var CSG = (function () {
  31259. function CSG() {
  31260. this.polygons = new Array();
  31261. }
  31262. // Convert BABYLON.Mesh to BABYLON.CSG
  31263. CSG.FromMesh = function (mesh) {
  31264. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31265. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31266. if (mesh instanceof BABYLON.Mesh) {
  31267. mesh.computeWorldMatrix(true);
  31268. matrix = mesh.getWorldMatrix();
  31269. meshPosition = mesh.position.clone();
  31270. meshRotation = mesh.rotation.clone();
  31271. if (mesh.rotationQuaternion) {
  31272. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31273. }
  31274. meshScaling = mesh.scaling.clone();
  31275. }
  31276. else {
  31277. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31278. }
  31279. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31280. var subMeshes = mesh.subMeshes;
  31281. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31282. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31283. vertices = [];
  31284. for (var j = 0; j < 3; j++) {
  31285. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31286. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31287. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31288. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31289. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31290. vertex = new Vertex(position, normal, uv);
  31291. vertices.push(vertex);
  31292. }
  31293. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31294. // To handle the case of degenerated triangle
  31295. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31296. if (polygon.plane)
  31297. polygons.push(polygon);
  31298. }
  31299. }
  31300. var csg = CSG.FromPolygons(polygons);
  31301. csg.matrix = matrix;
  31302. csg.position = meshPosition;
  31303. csg.rotation = meshRotation;
  31304. csg.scaling = meshScaling;
  31305. csg.rotationQuaternion = meshRotationQuaternion;
  31306. currentCSGMeshId++;
  31307. return csg;
  31308. };
  31309. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31310. CSG.FromPolygons = function (polygons) {
  31311. var csg = new CSG();
  31312. csg.polygons = polygons;
  31313. return csg;
  31314. };
  31315. CSG.prototype.clone = function () {
  31316. var csg = new CSG();
  31317. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31318. csg.copyTransformAttributes(this);
  31319. return csg;
  31320. };
  31321. CSG.prototype.toPolygons = function () {
  31322. return this.polygons;
  31323. };
  31324. CSG.prototype.union = function (csg) {
  31325. var a = new Node(this.clone().polygons);
  31326. var b = new Node(csg.clone().polygons);
  31327. a.clipTo(b);
  31328. b.clipTo(a);
  31329. b.invert();
  31330. b.clipTo(a);
  31331. b.invert();
  31332. a.build(b.allPolygons());
  31333. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31334. };
  31335. CSG.prototype.unionInPlace = function (csg) {
  31336. var a = new Node(this.polygons);
  31337. var b = new Node(csg.polygons);
  31338. a.clipTo(b);
  31339. b.clipTo(a);
  31340. b.invert();
  31341. b.clipTo(a);
  31342. b.invert();
  31343. a.build(b.allPolygons());
  31344. this.polygons = a.allPolygons();
  31345. };
  31346. CSG.prototype.subtract = function (csg) {
  31347. var a = new Node(this.clone().polygons);
  31348. var b = new Node(csg.clone().polygons);
  31349. a.invert();
  31350. a.clipTo(b);
  31351. b.clipTo(a);
  31352. b.invert();
  31353. b.clipTo(a);
  31354. b.invert();
  31355. a.build(b.allPolygons());
  31356. a.invert();
  31357. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31358. };
  31359. CSG.prototype.subtractInPlace = function (csg) {
  31360. var a = new Node(this.polygons);
  31361. var b = new Node(csg.polygons);
  31362. a.invert();
  31363. a.clipTo(b);
  31364. b.clipTo(a);
  31365. b.invert();
  31366. b.clipTo(a);
  31367. b.invert();
  31368. a.build(b.allPolygons());
  31369. a.invert();
  31370. this.polygons = a.allPolygons();
  31371. };
  31372. CSG.prototype.intersect = function (csg) {
  31373. var a = new Node(this.clone().polygons);
  31374. var b = new Node(csg.clone().polygons);
  31375. a.invert();
  31376. b.clipTo(a);
  31377. b.invert();
  31378. a.clipTo(b);
  31379. b.clipTo(a);
  31380. a.build(b.allPolygons());
  31381. a.invert();
  31382. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31383. };
  31384. CSG.prototype.intersectInPlace = function (csg) {
  31385. var a = new Node(this.polygons);
  31386. var b = new Node(csg.polygons);
  31387. a.invert();
  31388. b.clipTo(a);
  31389. b.invert();
  31390. a.clipTo(b);
  31391. b.clipTo(a);
  31392. a.build(b.allPolygons());
  31393. a.invert();
  31394. this.polygons = a.allPolygons();
  31395. };
  31396. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31397. // not modified.
  31398. CSG.prototype.inverse = function () {
  31399. var csg = this.clone();
  31400. csg.inverseInPlace();
  31401. return csg;
  31402. };
  31403. CSG.prototype.inverseInPlace = function () {
  31404. this.polygons.map(function (p) { p.flip(); });
  31405. };
  31406. // This is used to keep meshes transformations so they can be restored
  31407. // when we build back a Babylon Mesh
  31408. // NB : All CSG operations are performed in world coordinates
  31409. CSG.prototype.copyTransformAttributes = function (csg) {
  31410. this.matrix = csg.matrix;
  31411. this.position = csg.position;
  31412. this.rotation = csg.rotation;
  31413. this.scaling = csg.scaling;
  31414. this.rotationQuaternion = csg.rotationQuaternion;
  31415. return this;
  31416. };
  31417. // Build Raw mesh from CSG
  31418. // Coordinates here are in world space
  31419. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31420. var matrix = this.matrix.clone();
  31421. matrix.invert();
  31422. 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;
  31423. if (keepSubMeshes) {
  31424. // Sort Polygons, since subMeshes are indices range
  31425. polygons.sort(function (a, b) {
  31426. if (a.shared.meshId === b.shared.meshId) {
  31427. return a.shared.subMeshId - b.shared.subMeshId;
  31428. }
  31429. else {
  31430. return a.shared.meshId - b.shared.meshId;
  31431. }
  31432. });
  31433. }
  31434. for (var i = 0, il = polygons.length; i < il; i++) {
  31435. polygon = polygons[i];
  31436. // Building SubMeshes
  31437. if (!subMesh_dict[polygon.shared.meshId]) {
  31438. subMesh_dict[polygon.shared.meshId] = {};
  31439. }
  31440. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31441. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  31442. indexStart: +Infinity,
  31443. indexEnd: -Infinity,
  31444. materialIndex: polygon.shared.materialIndex
  31445. };
  31446. }
  31447. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  31448. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  31449. polygonIndices[0] = 0;
  31450. polygonIndices[1] = j - 1;
  31451. polygonIndices[2] = j;
  31452. for (var k = 0; k < 3; k++) {
  31453. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  31454. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  31455. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  31456. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  31457. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  31458. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  31459. // Check if 2 points can be merged
  31460. if (!(typeof vertex_idx !== 'undefined' &&
  31461. normals[vertex_idx * 3] === localNormal.x &&
  31462. normals[vertex_idx * 3 + 1] === localNormal.y &&
  31463. normals[vertex_idx * 3 + 2] === localNormal.z &&
  31464. uvs[vertex_idx * 2] === uv.x &&
  31465. uvs[vertex_idx * 2 + 1] === uv.y)) {
  31466. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  31467. uvs.push(uv.x, uv.y);
  31468. normals.push(normal.x, normal.y, normal.z);
  31469. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  31470. }
  31471. indices.push(vertex_idx);
  31472. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  31473. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  31474. currentIndex++;
  31475. }
  31476. }
  31477. }
  31478. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  31479. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31480. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  31481. mesh.setIndices(indices);
  31482. if (keepSubMeshes) {
  31483. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  31484. var materialIndexOffset = 0, materialMaxIndex;
  31485. mesh.subMeshes = new Array();
  31486. for (var m in subMesh_dict) {
  31487. materialMaxIndex = -1;
  31488. for (var sm in subMesh_dict[m]) {
  31489. subMesh_obj = subMesh_dict[m][sm];
  31490. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  31491. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  31492. }
  31493. materialIndexOffset += ++materialMaxIndex;
  31494. }
  31495. }
  31496. return mesh;
  31497. };
  31498. // Build Mesh from CSG taking material and transforms into account
  31499. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  31500. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  31501. mesh.material = material;
  31502. mesh.position.copyFrom(this.position);
  31503. mesh.rotation.copyFrom(this.rotation);
  31504. if (this.rotationQuaternion) {
  31505. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  31506. }
  31507. mesh.scaling.copyFrom(this.scaling);
  31508. mesh.computeWorldMatrix(true);
  31509. return mesh;
  31510. };
  31511. return CSG;
  31512. })();
  31513. BABYLON.CSG = CSG;
  31514. })(BABYLON || (BABYLON = {}));
  31515. var BABYLON;
  31516. (function (BABYLON) {
  31517. var VRDistortionCorrectionPostProcess = (function (_super) {
  31518. __extends(VRDistortionCorrectionPostProcess, _super);
  31519. //ANY
  31520. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  31521. var _this = this;
  31522. _super.call(this, name, "vrDistortionCorrection", [
  31523. 'LensCenter',
  31524. 'Scale',
  31525. 'ScaleIn',
  31526. 'HmdWarpParam'
  31527. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  31528. this._isRightEye = isRightEye;
  31529. this._distortionFactors = vrMetrics.distortionK;
  31530. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  31531. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  31532. this.onSizeChanged = function () {
  31533. _this.aspectRatio = _this.width * .5 / _this.height;
  31534. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  31535. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  31536. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  31537. };
  31538. this.onApply = function (effect) {
  31539. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  31540. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  31541. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  31542. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  31543. };
  31544. }
  31545. return VRDistortionCorrectionPostProcess;
  31546. })(BABYLON.PostProcess);
  31547. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  31548. })(BABYLON || (BABYLON = {}));
  31549. // Mainly based on these 2 articles :
  31550. // 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
  31551. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  31552. var BABYLON;
  31553. (function (BABYLON) {
  31554. (function (JoystickAxis) {
  31555. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  31556. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  31557. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  31558. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  31559. var JoystickAxis = BABYLON.JoystickAxis;
  31560. var VirtualJoystick = (function () {
  31561. function VirtualJoystick(leftJoystick) {
  31562. var _this = this;
  31563. if (leftJoystick) {
  31564. this._leftJoystick = true;
  31565. }
  31566. else {
  31567. this._leftJoystick = false;
  31568. }
  31569. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  31570. VirtualJoystick._globalJoystickIndex++;
  31571. // By default left & right arrow keys are moving the X
  31572. // and up & down keys are moving the Y
  31573. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31574. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31575. this.reverseLeftRight = false;
  31576. this.reverseUpDown = false;
  31577. // collections of pointers
  31578. this._touches = new BABYLON.SmartCollection();
  31579. this.deltaPosition = BABYLON.Vector3.Zero();
  31580. this._joystickSensibility = 25;
  31581. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31582. this._rotationSpeed = 25;
  31583. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  31584. this._rotateOnAxisRelativeToMesh = false;
  31585. this._onResize = function (evt) {
  31586. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31587. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31588. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  31589. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  31590. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  31591. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  31592. };
  31593. // injecting a canvas element on top of the canvas 3D game
  31594. if (!VirtualJoystick.vjCanvas) {
  31595. window.addEventListener("resize", this._onResize, false);
  31596. VirtualJoystick.vjCanvas = document.createElement("canvas");
  31597. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  31598. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  31599. VirtualJoystick.vjCanvas.width = window.innerWidth;
  31600. VirtualJoystick.vjCanvas.height = window.innerHeight;
  31601. VirtualJoystick.vjCanvas.style.width = "100%";
  31602. VirtualJoystick.vjCanvas.style.height = "100%";
  31603. VirtualJoystick.vjCanvas.style.position = "absolute";
  31604. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  31605. VirtualJoystick.vjCanvas.style.top = "0px";
  31606. VirtualJoystick.vjCanvas.style.left = "0px";
  31607. VirtualJoystick.vjCanvas.style.zIndex = "5";
  31608. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  31609. // Support for jQuery PEP polyfill
  31610. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  31611. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  31612. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  31613. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31614. document.body.appendChild(VirtualJoystick.vjCanvas);
  31615. }
  31616. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  31617. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  31618. this.pressed = false;
  31619. // default joystick color
  31620. this._joystickColor = "cyan";
  31621. this._joystickPointerID = -1;
  31622. // current joystick position
  31623. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  31624. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  31625. // origin joystick position
  31626. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  31627. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  31628. this._onPointerDownHandlerRef = function (evt) {
  31629. _this._onPointerDown(evt);
  31630. };
  31631. this._onPointerMoveHandlerRef = function (evt) {
  31632. _this._onPointerMove(evt);
  31633. };
  31634. this._onPointerOutHandlerRef = function (evt) {
  31635. _this._onPointerUp(evt);
  31636. };
  31637. this._onPointerUpHandlerRef = function (evt) {
  31638. _this._onPointerUp(evt);
  31639. };
  31640. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  31641. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  31642. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  31643. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  31644. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  31645. evt.preventDefault(); // Disables system menu
  31646. }, false);
  31647. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31648. }
  31649. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  31650. this._joystickSensibility = newJoystickSensibility;
  31651. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  31652. };
  31653. VirtualJoystick.prototype._onPointerDown = function (e) {
  31654. var positionOnScreenCondition;
  31655. e.preventDefault();
  31656. if (this._leftJoystick === true) {
  31657. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  31658. }
  31659. else {
  31660. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  31661. }
  31662. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  31663. // First contact will be dedicated to the virtual joystick
  31664. this._joystickPointerID = e.pointerId;
  31665. this._joystickPointerStartPos.x = e.clientX;
  31666. this._joystickPointerStartPos.y = e.clientY;
  31667. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  31668. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  31669. this._deltaJoystickVector.x = 0;
  31670. this._deltaJoystickVector.y = 0;
  31671. this.pressed = true;
  31672. this._touches.add(e.pointerId.toString(), e);
  31673. }
  31674. else {
  31675. // You can only trigger the action buttons with a joystick declared
  31676. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  31677. this._action();
  31678. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  31679. }
  31680. }
  31681. };
  31682. VirtualJoystick.prototype._onPointerMove = function (e) {
  31683. // If the current pointer is the one associated to the joystick (first touch contact)
  31684. if (this._joystickPointerID == e.pointerId) {
  31685. this._joystickPointerPos.x = e.clientX;
  31686. this._joystickPointerPos.y = e.clientY;
  31687. this._deltaJoystickVector = this._joystickPointerPos.clone();
  31688. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  31689. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  31690. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  31691. switch (this._axisTargetedByLeftAndRight) {
  31692. case JoystickAxis.X:
  31693. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  31694. break;
  31695. case JoystickAxis.Y:
  31696. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  31697. break;
  31698. case JoystickAxis.Z:
  31699. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  31700. break;
  31701. }
  31702. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31703. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31704. switch (this._axisTargetedByUpAndDown) {
  31705. case JoystickAxis.X:
  31706. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31707. break;
  31708. case JoystickAxis.Y:
  31709. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31710. break;
  31711. case JoystickAxis.Z:
  31712. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31713. break;
  31714. }
  31715. }
  31716. else {
  31717. if (this._touches.item(e.pointerId.toString())) {
  31718. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31719. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31720. }
  31721. }
  31722. };
  31723. VirtualJoystick.prototype._onPointerUp = function (e) {
  31724. if (this._joystickPointerID == e.pointerId) {
  31725. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31726. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31727. this._joystickPointerID = -1;
  31728. this.pressed = false;
  31729. }
  31730. else {
  31731. var touch = this._touches.item(e.pointerId.toString());
  31732. if (touch) {
  31733. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31734. }
  31735. }
  31736. this._deltaJoystickVector.x = 0;
  31737. this._deltaJoystickVector.y = 0;
  31738. this._touches.remove(e.pointerId.toString());
  31739. };
  31740. /**
  31741. * Change the color of the virtual joystick
  31742. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31743. */
  31744. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31745. this._joystickColor = newColor;
  31746. };
  31747. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31748. this._action = action;
  31749. };
  31750. // Define which axis you'd like to control for left & right
  31751. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31752. switch (axis) {
  31753. case JoystickAxis.X:
  31754. case JoystickAxis.Y:
  31755. case JoystickAxis.Z:
  31756. this._axisTargetedByLeftAndRight = axis;
  31757. break;
  31758. default:
  31759. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31760. break;
  31761. }
  31762. };
  31763. // Define which axis you'd like to control for up & down
  31764. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31765. switch (axis) {
  31766. case JoystickAxis.X:
  31767. case JoystickAxis.Y:
  31768. case JoystickAxis.Z:
  31769. this._axisTargetedByUpAndDown = axis;
  31770. break;
  31771. default:
  31772. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31773. break;
  31774. }
  31775. };
  31776. VirtualJoystick.prototype._clearCanvas = function () {
  31777. if (this._leftJoystick) {
  31778. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31779. }
  31780. else {
  31781. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31782. }
  31783. };
  31784. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31785. var _this = this;
  31786. if (this.pressed) {
  31787. this._touches.forEach(function (touch) {
  31788. if (touch.pointerId === _this._joystickPointerID) {
  31789. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31790. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31791. VirtualJoystick.vjCanvasContext.beginPath();
  31792. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31793. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31794. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31795. VirtualJoystick.vjCanvasContext.stroke();
  31796. VirtualJoystick.vjCanvasContext.closePath();
  31797. VirtualJoystick.vjCanvasContext.beginPath();
  31798. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31799. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31800. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31801. VirtualJoystick.vjCanvasContext.stroke();
  31802. VirtualJoystick.vjCanvasContext.closePath();
  31803. VirtualJoystick.vjCanvasContext.beginPath();
  31804. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31805. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31806. VirtualJoystick.vjCanvasContext.stroke();
  31807. VirtualJoystick.vjCanvasContext.closePath();
  31808. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31809. }
  31810. else {
  31811. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31812. VirtualJoystick.vjCanvasContext.beginPath();
  31813. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31814. VirtualJoystick.vjCanvasContext.beginPath();
  31815. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31816. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31817. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31818. VirtualJoystick.vjCanvasContext.stroke();
  31819. VirtualJoystick.vjCanvasContext.closePath();
  31820. touch.prevX = touch.x;
  31821. touch.prevY = touch.y;
  31822. }
  31823. ;
  31824. });
  31825. }
  31826. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31827. };
  31828. VirtualJoystick.prototype.releaseCanvas = function () {
  31829. if (VirtualJoystick.vjCanvas) {
  31830. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31831. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31832. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31833. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31834. window.removeEventListener("resize", this._onResize);
  31835. document.body.removeChild(VirtualJoystick.vjCanvas);
  31836. VirtualJoystick.vjCanvas = null;
  31837. }
  31838. };
  31839. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31840. VirtualJoystick._globalJoystickIndex = 0;
  31841. return VirtualJoystick;
  31842. })();
  31843. BABYLON.VirtualJoystick = VirtualJoystick;
  31844. })(BABYLON || (BABYLON = {}));
  31845. var BABYLON;
  31846. (function (BABYLON) {
  31847. // We're mainly based on the logic defined into the FreeCamera code
  31848. var VirtualJoysticksCamera = (function (_super) {
  31849. __extends(VirtualJoysticksCamera, _super);
  31850. function VirtualJoysticksCamera(name, position, scene) {
  31851. _super.call(this, name, position, scene);
  31852. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31853. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31854. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31855. this._leftjoystick.setJoystickSensibility(0.15);
  31856. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31857. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31858. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31859. this._rightjoystick.reverseUpDown = true;
  31860. this._rightjoystick.setJoystickSensibility(0.05);
  31861. this._rightjoystick.setJoystickColor("yellow");
  31862. }
  31863. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31864. return this._leftjoystick;
  31865. };
  31866. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31867. return this._rightjoystick;
  31868. };
  31869. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31870. var speed = this._computeLocalCameraSpeed() * 50;
  31871. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31872. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31873. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31874. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31875. if (!this._leftjoystick.pressed) {
  31876. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31877. }
  31878. if (!this._rightjoystick.pressed) {
  31879. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31880. }
  31881. _super.prototype._checkInputs.call(this);
  31882. };
  31883. VirtualJoysticksCamera.prototype.dispose = function () {
  31884. this._leftjoystick.releaseCanvas();
  31885. _super.prototype.dispose.call(this);
  31886. };
  31887. return VirtualJoysticksCamera;
  31888. })(BABYLON.FreeCamera);
  31889. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31890. })(BABYLON || (BABYLON = {}));
  31891. var BABYLON;
  31892. (function (BABYLON) {
  31893. var AnaglyphPostProcess = (function (_super) {
  31894. __extends(AnaglyphPostProcess, _super);
  31895. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31896. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31897. }
  31898. return AnaglyphPostProcess;
  31899. })(BABYLON.PostProcess);
  31900. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31901. })(BABYLON || (BABYLON = {}));
  31902. var BABYLON;
  31903. (function (BABYLON) {
  31904. var OutlineRenderer = (function () {
  31905. function OutlineRenderer(scene) {
  31906. this._scene = scene;
  31907. }
  31908. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31909. var _this = this;
  31910. if (useOverlay === void 0) { useOverlay = false; }
  31911. var scene = this._scene;
  31912. var engine = this._scene.getEngine();
  31913. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31914. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31915. return;
  31916. }
  31917. var mesh = subMesh.getRenderingMesh();
  31918. var material = subMesh.getMaterial();
  31919. engine.enableEffect(this._effect);
  31920. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31921. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31922. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31923. // Bones
  31924. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31925. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  31926. }
  31927. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31928. // Alpha test
  31929. if (material && material.needAlphaTesting()) {
  31930. var alphaTexture = material.getAlphaTestTexture();
  31931. this._effect.setTexture("diffuseSampler", alphaTexture);
  31932. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31933. }
  31934. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31935. };
  31936. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31937. var defines = [];
  31938. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31939. var mesh = subMesh.getMesh();
  31940. var material = subMesh.getMaterial();
  31941. // Alpha test
  31942. if (material && material.needAlphaTesting()) {
  31943. defines.push("#define ALPHATEST");
  31944. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31945. attribs.push(BABYLON.VertexBuffer.UVKind);
  31946. defines.push("#define UV1");
  31947. }
  31948. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31949. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31950. defines.push("#define UV2");
  31951. }
  31952. }
  31953. // Bones
  31954. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31955. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31956. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31957. if (mesh.numBoneInfluencers > 4) {
  31958. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31959. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31960. }
  31961. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31962. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31963. }
  31964. else {
  31965. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31966. }
  31967. // Instances
  31968. if (useInstances) {
  31969. defines.push("#define INSTANCES");
  31970. attribs.push("world0");
  31971. attribs.push("world1");
  31972. attribs.push("world2");
  31973. attribs.push("world3");
  31974. }
  31975. // Get correct effect
  31976. var join = defines.join("\n");
  31977. if (this._cachedDefines !== join) {
  31978. this._cachedDefines = join;
  31979. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31980. }
  31981. return this._effect.isReady();
  31982. };
  31983. return OutlineRenderer;
  31984. })();
  31985. BABYLON.OutlineRenderer = OutlineRenderer;
  31986. })(BABYLON || (BABYLON = {}));
  31987. var BABYLON;
  31988. (function (BABYLON) {
  31989. var MeshAssetTask = (function () {
  31990. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31991. this.name = name;
  31992. this.meshesNames = meshesNames;
  31993. this.rootUrl = rootUrl;
  31994. this.sceneFilename = sceneFilename;
  31995. this.isCompleted = false;
  31996. }
  31997. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31998. var _this = this;
  31999. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  32000. _this.loadedMeshes = meshes;
  32001. _this.loadedParticleSystems = particleSystems;
  32002. _this.loadedSkeletons = skeletons;
  32003. _this.isCompleted = true;
  32004. if (_this.onSuccess) {
  32005. _this.onSuccess(_this);
  32006. }
  32007. onSuccess();
  32008. }, null, function () {
  32009. if (_this.onError) {
  32010. _this.onError(_this);
  32011. }
  32012. onError();
  32013. });
  32014. };
  32015. return MeshAssetTask;
  32016. })();
  32017. BABYLON.MeshAssetTask = MeshAssetTask;
  32018. var TextFileAssetTask = (function () {
  32019. function TextFileAssetTask(name, url) {
  32020. this.name = name;
  32021. this.url = url;
  32022. this.isCompleted = false;
  32023. }
  32024. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32025. var _this = this;
  32026. BABYLON.Tools.LoadFile(this.url, function (data) {
  32027. _this.text = data;
  32028. _this.isCompleted = true;
  32029. if (_this.onSuccess) {
  32030. _this.onSuccess(_this);
  32031. }
  32032. onSuccess();
  32033. }, null, scene.database, false, function () {
  32034. if (_this.onError) {
  32035. _this.onError(_this);
  32036. }
  32037. onError();
  32038. });
  32039. };
  32040. return TextFileAssetTask;
  32041. })();
  32042. BABYLON.TextFileAssetTask = TextFileAssetTask;
  32043. var BinaryFileAssetTask = (function () {
  32044. function BinaryFileAssetTask(name, url) {
  32045. this.name = name;
  32046. this.url = url;
  32047. this.isCompleted = false;
  32048. }
  32049. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32050. var _this = this;
  32051. BABYLON.Tools.LoadFile(this.url, function (data) {
  32052. _this.data = data;
  32053. _this.isCompleted = true;
  32054. if (_this.onSuccess) {
  32055. _this.onSuccess(_this);
  32056. }
  32057. onSuccess();
  32058. }, null, scene.database, true, function () {
  32059. if (_this.onError) {
  32060. _this.onError(_this);
  32061. }
  32062. onError();
  32063. });
  32064. };
  32065. return BinaryFileAssetTask;
  32066. })();
  32067. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  32068. var ImageAssetTask = (function () {
  32069. function ImageAssetTask(name, url) {
  32070. this.name = name;
  32071. this.url = url;
  32072. this.isCompleted = false;
  32073. }
  32074. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32075. var _this = this;
  32076. var img = new Image();
  32077. img.onload = function () {
  32078. _this.image = img;
  32079. _this.isCompleted = true;
  32080. if (_this.onSuccess) {
  32081. _this.onSuccess(_this);
  32082. }
  32083. onSuccess();
  32084. };
  32085. img.onerror = function () {
  32086. if (_this.onError) {
  32087. _this.onError(_this);
  32088. }
  32089. onError();
  32090. };
  32091. img.src = this.url;
  32092. };
  32093. return ImageAssetTask;
  32094. })();
  32095. BABYLON.ImageAssetTask = ImageAssetTask;
  32096. var TextureAssetTask = (function () {
  32097. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  32098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32099. this.name = name;
  32100. this.url = url;
  32101. this.noMipmap = noMipmap;
  32102. this.invertY = invertY;
  32103. this.samplingMode = samplingMode;
  32104. this.isCompleted = false;
  32105. }
  32106. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32107. var _this = this;
  32108. var onload = function () {
  32109. _this.isCompleted = true;
  32110. if (_this.onSuccess) {
  32111. _this.onSuccess(_this);
  32112. }
  32113. onSuccess();
  32114. };
  32115. var onerror = function () {
  32116. if (_this.onError) {
  32117. _this.onError(_this);
  32118. }
  32119. onError();
  32120. };
  32121. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  32122. };
  32123. return TextureAssetTask;
  32124. })();
  32125. BABYLON.TextureAssetTask = TextureAssetTask;
  32126. var AssetsManager = (function () {
  32127. function AssetsManager(scene) {
  32128. this._tasks = new Array();
  32129. this._waitingTasksCount = 0;
  32130. this.useDefaultLoadingScreen = true;
  32131. this._scene = scene;
  32132. }
  32133. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32134. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32135. this._tasks.push(task);
  32136. return task;
  32137. };
  32138. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32139. var task = new TextFileAssetTask(taskName, url);
  32140. this._tasks.push(task);
  32141. return task;
  32142. };
  32143. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32144. var task = new BinaryFileAssetTask(taskName, url);
  32145. this._tasks.push(task);
  32146. return task;
  32147. };
  32148. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32149. var task = new ImageAssetTask(taskName, url);
  32150. this._tasks.push(task);
  32151. return task;
  32152. };
  32153. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32155. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32156. this._tasks.push(task);
  32157. return task;
  32158. };
  32159. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32160. this._waitingTasksCount--;
  32161. if (this._waitingTasksCount === 0) {
  32162. if (this.onFinish) {
  32163. this.onFinish(this._tasks);
  32164. }
  32165. this._scene.getEngine().hideLoadingUI();
  32166. }
  32167. };
  32168. AssetsManager.prototype._runTask = function (task) {
  32169. var _this = this;
  32170. task.run(this._scene, function () {
  32171. if (_this.onTaskSuccess) {
  32172. _this.onTaskSuccess(task);
  32173. }
  32174. _this._decreaseWaitingTasksCount();
  32175. }, function () {
  32176. if (_this.onTaskError) {
  32177. _this.onTaskError(task);
  32178. }
  32179. _this._decreaseWaitingTasksCount();
  32180. });
  32181. };
  32182. AssetsManager.prototype.reset = function () {
  32183. this._tasks = new Array();
  32184. return this;
  32185. };
  32186. AssetsManager.prototype.load = function () {
  32187. this._waitingTasksCount = this._tasks.length;
  32188. if (this._waitingTasksCount === 0) {
  32189. if (this.onFinish) {
  32190. this.onFinish(this._tasks);
  32191. }
  32192. return this;
  32193. }
  32194. if (this.useDefaultLoadingScreen) {
  32195. this._scene.getEngine().displayLoadingUI();
  32196. }
  32197. for (var index = 0; index < this._tasks.length; index++) {
  32198. var task = this._tasks[index];
  32199. this._runTask(task);
  32200. }
  32201. return this;
  32202. };
  32203. return AssetsManager;
  32204. })();
  32205. BABYLON.AssetsManager = AssetsManager;
  32206. })(BABYLON || (BABYLON = {}));
  32207. var BABYLON;
  32208. (function (BABYLON) {
  32209. var VRDeviceOrientationFreeCamera = (function (_super) {
  32210. __extends(VRDeviceOrientationFreeCamera, _super);
  32211. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32212. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32213. _super.call(this, name, position, scene);
  32214. this._alpha = 0;
  32215. this._beta = 0;
  32216. this._gamma = 0;
  32217. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32218. metrics.compensateDistortion = compensateDistortion;
  32219. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32220. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32221. }
  32222. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32223. this._alpha = +evt.alpha | 0;
  32224. this._beta = +evt.beta | 0;
  32225. this._gamma = +evt.gamma | 0;
  32226. if (this._gamma < 0) {
  32227. this._gamma = 90 + this._gamma;
  32228. }
  32229. else {
  32230. // Incline it in the correct angle.
  32231. this._gamma = 270 - this._gamma;
  32232. }
  32233. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32234. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32235. this.rotation.z = this._beta / 180.0 * Math.PI;
  32236. };
  32237. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32238. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32239. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32240. };
  32241. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32242. _super.prototype.detachControl.call(this, element);
  32243. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32244. };
  32245. return VRDeviceOrientationFreeCamera;
  32246. })(BABYLON.FreeCamera);
  32247. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32248. })(BABYLON || (BABYLON = {}));
  32249. var BABYLON;
  32250. (function (BABYLON) {
  32251. var WebVRFreeCamera = (function (_super) {
  32252. __extends(WebVRFreeCamera, _super);
  32253. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32254. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32255. _super.call(this, name, position, scene);
  32256. this._hmdDevice = null;
  32257. this._sensorDevice = null;
  32258. this._cacheState = null;
  32259. this._cacheQuaternion = new BABYLON.Quaternion();
  32260. this._cacheRotation = BABYLON.Vector3.Zero();
  32261. this._vrEnabled = false;
  32262. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32263. metrics.compensateDistortion = compensateDistortion;
  32264. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32265. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32266. }
  32267. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32268. var size = devices.length;
  32269. var i = 0;
  32270. // Reset devices.
  32271. this._sensorDevice = null;
  32272. this._hmdDevice = null;
  32273. // Search for a HmdDevice.
  32274. while (i < size && this._hmdDevice === null) {
  32275. if (devices[i] instanceof HMDVRDevice) {
  32276. this._hmdDevice = devices[i];
  32277. }
  32278. i++;
  32279. }
  32280. i = 0;
  32281. while (i < size && this._sensorDevice === null) {
  32282. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32283. this._sensorDevice = devices[i];
  32284. }
  32285. i++;
  32286. }
  32287. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32288. };
  32289. WebVRFreeCamera.prototype._checkInputs = function () {
  32290. if (this._vrEnabled) {
  32291. this._cacheState = this._sensorDevice.getState();
  32292. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32293. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32294. this.rotation.x = -this._cacheRotation.z;
  32295. this.rotation.y = -this._cacheRotation.y;
  32296. this.rotation.z = this._cacheRotation.x;
  32297. }
  32298. _super.prototype._checkInputs.call(this);
  32299. };
  32300. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32301. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32302. if (navigator.getVRDevices) {
  32303. navigator.getVRDevices().then(this._getWebVRDevices);
  32304. }
  32305. else if (navigator.mozGetVRDevices) {
  32306. navigator.mozGetVRDevices(this._getWebVRDevices);
  32307. }
  32308. };
  32309. WebVRFreeCamera.prototype.detachControl = function (element) {
  32310. _super.prototype.detachControl.call(this, element);
  32311. this._vrEnabled = false;
  32312. };
  32313. return WebVRFreeCamera;
  32314. })(BABYLON.FreeCamera);
  32315. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32316. })(BABYLON || (BABYLON = {}));
  32317. var BABYLON;
  32318. (function (BABYLON) {
  32319. // Standard optimizations
  32320. var SceneOptimization = (function () {
  32321. function SceneOptimization(priority) {
  32322. if (priority === void 0) { priority = 0; }
  32323. this.priority = priority;
  32324. this.apply = function (scene) {
  32325. return true; // Return true if everything that can be done was applied
  32326. };
  32327. }
  32328. return SceneOptimization;
  32329. })();
  32330. BABYLON.SceneOptimization = SceneOptimization;
  32331. var TextureOptimization = (function (_super) {
  32332. __extends(TextureOptimization, _super);
  32333. function TextureOptimization(priority, maximumSize) {
  32334. var _this = this;
  32335. if (priority === void 0) { priority = 0; }
  32336. if (maximumSize === void 0) { maximumSize = 1024; }
  32337. _super.call(this, priority);
  32338. this.priority = priority;
  32339. this.maximumSize = maximumSize;
  32340. this.apply = function (scene) {
  32341. var allDone = true;
  32342. for (var index = 0; index < scene.textures.length; index++) {
  32343. var texture = scene.textures[index];
  32344. if (!texture.canRescale) {
  32345. continue;
  32346. }
  32347. var currentSize = texture.getSize();
  32348. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32349. if (maxDimension > _this.maximumSize) {
  32350. texture.scale(0.5);
  32351. allDone = false;
  32352. }
  32353. }
  32354. return allDone;
  32355. };
  32356. }
  32357. return TextureOptimization;
  32358. })(SceneOptimization);
  32359. BABYLON.TextureOptimization = TextureOptimization;
  32360. var HardwareScalingOptimization = (function (_super) {
  32361. __extends(HardwareScalingOptimization, _super);
  32362. function HardwareScalingOptimization(priority, maximumScale) {
  32363. var _this = this;
  32364. if (priority === void 0) { priority = 0; }
  32365. if (maximumScale === void 0) { maximumScale = 2; }
  32366. _super.call(this, priority);
  32367. this.priority = priority;
  32368. this.maximumScale = maximumScale;
  32369. this._currentScale = 1;
  32370. this.apply = function (scene) {
  32371. _this._currentScale++;
  32372. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32373. return _this._currentScale >= _this.maximumScale;
  32374. };
  32375. }
  32376. return HardwareScalingOptimization;
  32377. })(SceneOptimization);
  32378. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32379. var ShadowsOptimization = (function (_super) {
  32380. __extends(ShadowsOptimization, _super);
  32381. function ShadowsOptimization() {
  32382. _super.apply(this, arguments);
  32383. this.apply = function (scene) {
  32384. scene.shadowsEnabled = false;
  32385. return true;
  32386. };
  32387. }
  32388. return ShadowsOptimization;
  32389. })(SceneOptimization);
  32390. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32391. var PostProcessesOptimization = (function (_super) {
  32392. __extends(PostProcessesOptimization, _super);
  32393. function PostProcessesOptimization() {
  32394. _super.apply(this, arguments);
  32395. this.apply = function (scene) {
  32396. scene.postProcessesEnabled = false;
  32397. return true;
  32398. };
  32399. }
  32400. return PostProcessesOptimization;
  32401. })(SceneOptimization);
  32402. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32403. var LensFlaresOptimization = (function (_super) {
  32404. __extends(LensFlaresOptimization, _super);
  32405. function LensFlaresOptimization() {
  32406. _super.apply(this, arguments);
  32407. this.apply = function (scene) {
  32408. scene.lensFlaresEnabled = false;
  32409. return true;
  32410. };
  32411. }
  32412. return LensFlaresOptimization;
  32413. })(SceneOptimization);
  32414. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32415. var ParticlesOptimization = (function (_super) {
  32416. __extends(ParticlesOptimization, _super);
  32417. function ParticlesOptimization() {
  32418. _super.apply(this, arguments);
  32419. this.apply = function (scene) {
  32420. scene.particlesEnabled = false;
  32421. return true;
  32422. };
  32423. }
  32424. return ParticlesOptimization;
  32425. })(SceneOptimization);
  32426. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32427. var RenderTargetsOptimization = (function (_super) {
  32428. __extends(RenderTargetsOptimization, _super);
  32429. function RenderTargetsOptimization() {
  32430. _super.apply(this, arguments);
  32431. this.apply = function (scene) {
  32432. scene.renderTargetsEnabled = false;
  32433. return true;
  32434. };
  32435. }
  32436. return RenderTargetsOptimization;
  32437. })(SceneOptimization);
  32438. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32439. var MergeMeshesOptimization = (function (_super) {
  32440. __extends(MergeMeshesOptimization, _super);
  32441. function MergeMeshesOptimization() {
  32442. var _this = this;
  32443. _super.apply(this, arguments);
  32444. this._canBeMerged = function (abstractMesh) {
  32445. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  32446. return false;
  32447. }
  32448. var mesh = abstractMesh;
  32449. if (!mesh.isVisible || !mesh.isEnabled()) {
  32450. return false;
  32451. }
  32452. if (mesh.instances.length > 0) {
  32453. return false;
  32454. }
  32455. if (mesh.skeleton || mesh.hasLODLevels) {
  32456. return false;
  32457. }
  32458. if (mesh.parent) {
  32459. return false;
  32460. }
  32461. return true;
  32462. };
  32463. this.apply = function (scene, updateSelectionTree) {
  32464. var globalPool = scene.meshes.slice(0);
  32465. var globalLength = globalPool.length;
  32466. for (var index = 0; index < globalLength; index++) {
  32467. var currentPool = new Array();
  32468. var current = globalPool[index];
  32469. // Checks
  32470. if (!_this._canBeMerged(current)) {
  32471. continue;
  32472. }
  32473. currentPool.push(current);
  32474. // Find compatible meshes
  32475. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  32476. var otherMesh = globalPool[subIndex];
  32477. if (!_this._canBeMerged(otherMesh)) {
  32478. continue;
  32479. }
  32480. if (otherMesh.material !== current.material) {
  32481. continue;
  32482. }
  32483. if (otherMesh.checkCollisions !== current.checkCollisions) {
  32484. continue;
  32485. }
  32486. currentPool.push(otherMesh);
  32487. globalLength--;
  32488. globalPool.splice(subIndex, 1);
  32489. subIndex--;
  32490. }
  32491. if (currentPool.length < 2) {
  32492. continue;
  32493. }
  32494. // Merge meshes
  32495. BABYLON.Mesh.MergeMeshes(currentPool);
  32496. }
  32497. if (updateSelectionTree != undefined) {
  32498. if (updateSelectionTree) {
  32499. scene.createOrUpdateSelectionOctree();
  32500. }
  32501. }
  32502. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  32503. scene.createOrUpdateSelectionOctree();
  32504. }
  32505. return true;
  32506. };
  32507. }
  32508. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  32509. get: function () {
  32510. return MergeMeshesOptimization._UpdateSelectionTree;
  32511. },
  32512. set: function (value) {
  32513. MergeMeshesOptimization._UpdateSelectionTree = value;
  32514. },
  32515. enumerable: true,
  32516. configurable: true
  32517. });
  32518. MergeMeshesOptimization._UpdateSelectionTree = false;
  32519. return MergeMeshesOptimization;
  32520. })(SceneOptimization);
  32521. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  32522. // Options
  32523. var SceneOptimizerOptions = (function () {
  32524. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  32525. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  32526. if (trackerDuration === void 0) { trackerDuration = 2000; }
  32527. this.targetFrameRate = targetFrameRate;
  32528. this.trackerDuration = trackerDuration;
  32529. this.optimizations = new Array();
  32530. }
  32531. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  32532. var result = new SceneOptimizerOptions(targetFrameRate);
  32533. var priority = 0;
  32534. result.optimizations.push(new MergeMeshesOptimization(priority));
  32535. result.optimizations.push(new ShadowsOptimization(priority));
  32536. result.optimizations.push(new LensFlaresOptimization(priority));
  32537. // Next priority
  32538. priority++;
  32539. result.optimizations.push(new PostProcessesOptimization(priority));
  32540. result.optimizations.push(new ParticlesOptimization(priority));
  32541. // Next priority
  32542. priority++;
  32543. result.optimizations.push(new TextureOptimization(priority, 1024));
  32544. return result;
  32545. };
  32546. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  32547. var result = new SceneOptimizerOptions(targetFrameRate);
  32548. var priority = 0;
  32549. result.optimizations.push(new MergeMeshesOptimization(priority));
  32550. result.optimizations.push(new ShadowsOptimization(priority));
  32551. result.optimizations.push(new LensFlaresOptimization(priority));
  32552. // Next priority
  32553. priority++;
  32554. result.optimizations.push(new PostProcessesOptimization(priority));
  32555. result.optimizations.push(new ParticlesOptimization(priority));
  32556. // Next priority
  32557. priority++;
  32558. result.optimizations.push(new TextureOptimization(priority, 512));
  32559. // Next priority
  32560. priority++;
  32561. result.optimizations.push(new RenderTargetsOptimization(priority));
  32562. // Next priority
  32563. priority++;
  32564. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  32565. return result;
  32566. };
  32567. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  32568. var result = new SceneOptimizerOptions(targetFrameRate);
  32569. var priority = 0;
  32570. result.optimizations.push(new MergeMeshesOptimization(priority));
  32571. result.optimizations.push(new ShadowsOptimization(priority));
  32572. result.optimizations.push(new LensFlaresOptimization(priority));
  32573. // Next priority
  32574. priority++;
  32575. result.optimizations.push(new PostProcessesOptimization(priority));
  32576. result.optimizations.push(new ParticlesOptimization(priority));
  32577. // Next priority
  32578. priority++;
  32579. result.optimizations.push(new TextureOptimization(priority, 256));
  32580. // Next priority
  32581. priority++;
  32582. result.optimizations.push(new RenderTargetsOptimization(priority));
  32583. // Next priority
  32584. priority++;
  32585. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  32586. return result;
  32587. };
  32588. return SceneOptimizerOptions;
  32589. })();
  32590. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  32591. // Scene optimizer tool
  32592. var SceneOptimizer = (function () {
  32593. function SceneOptimizer() {
  32594. }
  32595. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  32596. // TODO: add an epsilon
  32597. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  32598. if (onSuccess) {
  32599. onSuccess();
  32600. }
  32601. return;
  32602. }
  32603. // Apply current level of optimizations
  32604. var allDone = true;
  32605. var noOptimizationApplied = true;
  32606. for (var index = 0; index < options.optimizations.length; index++) {
  32607. var optimization = options.optimizations[index];
  32608. if (optimization.priority === currentPriorityLevel) {
  32609. noOptimizationApplied = false;
  32610. allDone = allDone && optimization.apply(scene);
  32611. }
  32612. }
  32613. // If no optimization was applied, this is a failure :(
  32614. if (noOptimizationApplied) {
  32615. if (onFailure) {
  32616. onFailure();
  32617. }
  32618. return;
  32619. }
  32620. // If all optimizations were done, move to next level
  32621. if (allDone) {
  32622. currentPriorityLevel++;
  32623. }
  32624. // Let's the system running for a specific amount of time before checking FPS
  32625. scene.executeWhenReady(function () {
  32626. setTimeout(function () {
  32627. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  32628. }, options.trackerDuration);
  32629. });
  32630. };
  32631. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  32632. if (!options) {
  32633. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  32634. }
  32635. // Let's the system running for a specific amount of time before checking FPS
  32636. scene.executeWhenReady(function () {
  32637. setTimeout(function () {
  32638. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  32639. }, options.trackerDuration);
  32640. });
  32641. };
  32642. return SceneOptimizer;
  32643. })();
  32644. BABYLON.SceneOptimizer = SceneOptimizer;
  32645. })(BABYLON || (BABYLON = {}));
  32646. var BABYLON;
  32647. (function (BABYLON) {
  32648. var Internals;
  32649. (function (Internals) {
  32650. var MeshLODLevel = (function () {
  32651. function MeshLODLevel(distance, mesh) {
  32652. this.distance = distance;
  32653. this.mesh = mesh;
  32654. }
  32655. return MeshLODLevel;
  32656. })();
  32657. Internals.MeshLODLevel = MeshLODLevel;
  32658. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32659. })(BABYLON || (BABYLON = {}));
  32660. var BABYLON;
  32661. (function (BABYLON) {
  32662. var RawTexture = (function (_super) {
  32663. __extends(RawTexture, _super);
  32664. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32666. if (invertY === void 0) { invertY = false; }
  32667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32668. _super.call(this, null, scene, !generateMipMaps, invertY);
  32669. this.format = format;
  32670. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32671. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32672. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32673. }
  32674. RawTexture.prototype.update = function (data) {
  32675. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32676. };
  32677. // Statics
  32678. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32679. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32680. if (invertY === void 0) { invertY = false; }
  32681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32682. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32683. };
  32684. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32685. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32686. if (invertY === void 0) { invertY = false; }
  32687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32688. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32689. };
  32690. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32691. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32692. if (invertY === void 0) { invertY = false; }
  32693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32694. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32695. };
  32696. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32697. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32698. if (invertY === void 0) { invertY = false; }
  32699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32700. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32701. };
  32702. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32703. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32704. if (invertY === void 0) { invertY = false; }
  32705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32706. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32707. };
  32708. return RawTexture;
  32709. })(BABYLON.Texture);
  32710. BABYLON.RawTexture = RawTexture;
  32711. })(BABYLON || (BABYLON = {}));
  32712. var BABYLON;
  32713. (function (BABYLON) {
  32714. var IndexedVector2 = (function (_super) {
  32715. __extends(IndexedVector2, _super);
  32716. function IndexedVector2(original, index) {
  32717. _super.call(this, original.x, original.y);
  32718. this.index = index;
  32719. }
  32720. return IndexedVector2;
  32721. })(BABYLON.Vector2);
  32722. var PolygonPoints = (function () {
  32723. function PolygonPoints() {
  32724. this.elements = new Array();
  32725. }
  32726. PolygonPoints.prototype.add = function (originalPoints) {
  32727. var _this = this;
  32728. var result = new Array();
  32729. originalPoints.forEach(function (point) {
  32730. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32731. var newPoint = new IndexedVector2(point, _this.elements.length);
  32732. result.push(newPoint);
  32733. _this.elements.push(newPoint);
  32734. }
  32735. });
  32736. return result;
  32737. };
  32738. PolygonPoints.prototype.computeBounds = function () {
  32739. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32740. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32741. this.elements.forEach(function (point) {
  32742. // x
  32743. if (point.x < lmin.x) {
  32744. lmin.x = point.x;
  32745. }
  32746. else if (point.x > lmax.x) {
  32747. lmax.x = point.x;
  32748. }
  32749. // y
  32750. if (point.y < lmin.y) {
  32751. lmin.y = point.y;
  32752. }
  32753. else if (point.y > lmax.y) {
  32754. lmax.y = point.y;
  32755. }
  32756. });
  32757. return {
  32758. min: lmin,
  32759. max: lmax,
  32760. width: lmax.x - lmin.x,
  32761. height: lmax.y - lmin.y
  32762. };
  32763. };
  32764. return PolygonPoints;
  32765. })();
  32766. var Polygon = (function () {
  32767. function Polygon() {
  32768. }
  32769. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32770. return [
  32771. new BABYLON.Vector2(xmin, ymin),
  32772. new BABYLON.Vector2(xmax, ymin),
  32773. new BABYLON.Vector2(xmax, ymax),
  32774. new BABYLON.Vector2(xmin, ymax)
  32775. ];
  32776. };
  32777. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32778. if (cx === void 0) { cx = 0; }
  32779. if (cy === void 0) { cy = 0; }
  32780. if (numberOfSides === void 0) { numberOfSides = 32; }
  32781. var result = new Array();
  32782. var angle = 0;
  32783. var increment = (Math.PI * 2) / numberOfSides;
  32784. for (var i = 0; i < numberOfSides; i++) {
  32785. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32786. angle -= increment;
  32787. }
  32788. return result;
  32789. };
  32790. Polygon.Parse = function (input) {
  32791. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32792. var i, result = [];
  32793. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32794. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32795. }
  32796. return result;
  32797. };
  32798. Polygon.StartingAt = function (x, y) {
  32799. return BABYLON.Path2.StartingAt(x, y);
  32800. };
  32801. return Polygon;
  32802. })();
  32803. BABYLON.Polygon = Polygon;
  32804. var PolygonMeshBuilder = (function () {
  32805. function PolygonMeshBuilder(name, contours, scene) {
  32806. this._points = new PolygonPoints();
  32807. this._outlinepoints = new PolygonPoints();
  32808. this._holes = [];
  32809. if (!("poly2tri" in window)) {
  32810. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32811. }
  32812. this._name = name;
  32813. this._scene = scene;
  32814. var points;
  32815. if (contours instanceof BABYLON.Path2) {
  32816. points = contours.getPoints();
  32817. }
  32818. else {
  32819. points = contours;
  32820. }
  32821. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32822. this._outlinepoints.add(points);
  32823. }
  32824. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32825. this._swctx.addHole(this._points.add(hole));
  32826. var holepoints = new PolygonPoints();
  32827. holepoints.add(hole);
  32828. this._holes.push(holepoints);
  32829. return this;
  32830. };
  32831. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32832. var _this = this;
  32833. if (updatable === void 0) { updatable = false; }
  32834. var result = new BABYLON.Mesh(this._name, this._scene);
  32835. var normals = [];
  32836. var positions = [];
  32837. var uvs = [];
  32838. var bounds = this._points.computeBounds();
  32839. this._points.elements.forEach(function (p) {
  32840. normals.push(0, 1.0, 0);
  32841. positions.push(p.x, 0, p.y);
  32842. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32843. });
  32844. var indices = [];
  32845. this._swctx.triangulate();
  32846. this._swctx.getTriangles().forEach(function (triangle) {
  32847. triangle.getPoints().forEach(function (point) {
  32848. indices.push(point.index);
  32849. });
  32850. });
  32851. if (depth > 0) {
  32852. var positionscount = (positions.length / 3); //get the current pointcount
  32853. this._points.elements.forEach(function (p) {
  32854. normals.push(0, -1.0, 0);
  32855. positions.push(p.x, -depth, p.y);
  32856. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32857. });
  32858. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32859. var p2;
  32860. var poscounter = 0;
  32861. this._swctx.getTriangles().forEach(function (triangle) {
  32862. triangle.getPoints().forEach(function (point) {
  32863. switch (poscounter) {
  32864. case 0:
  32865. p1 = point;
  32866. break;
  32867. case 1:
  32868. p2 = point;
  32869. break;
  32870. case 2:
  32871. indices.push(point.index + positionscount);
  32872. indices.push(p2.index + positionscount);
  32873. indices.push(p1.index + positionscount);
  32874. poscounter = -1;
  32875. break;
  32876. }
  32877. poscounter++;
  32878. //indices.push((<IndexedVector2>point).index + positionscount);
  32879. });
  32880. });
  32881. //Add the sides
  32882. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32883. this._holes.forEach(function (hole) {
  32884. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32885. });
  32886. }
  32887. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32888. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32889. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32890. result.setIndices(indices);
  32891. return result;
  32892. };
  32893. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32894. var StartIndex = positions.length / 3;
  32895. var ulength = 0;
  32896. for (var i = 0; i < points.elements.length; i++) {
  32897. var p = points.elements[i];
  32898. var p1;
  32899. if ((i + 1) > points.elements.length - 1) {
  32900. p1 = points.elements[0];
  32901. }
  32902. else {
  32903. p1 = points.elements[i + 1];
  32904. }
  32905. positions.push(p.x, 0, p.y);
  32906. positions.push(p.x, -depth, p.y);
  32907. positions.push(p1.x, 0, p1.y);
  32908. positions.push(p1.x, -depth, p1.y);
  32909. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32910. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32911. var v3 = v2.subtract(v1);
  32912. var v4 = new BABYLON.Vector3(0, 1, 0);
  32913. var vn = BABYLON.Vector3.Cross(v3, v4);
  32914. vn = vn.normalize();
  32915. uvs.push(ulength / bounds.width, 0);
  32916. uvs.push(ulength / bounds.width, 1);
  32917. ulength += v3.length();
  32918. uvs.push((ulength / bounds.width), 0);
  32919. uvs.push((ulength / bounds.width), 1);
  32920. if (!flip) {
  32921. normals.push(-vn.x, -vn.y, -vn.z);
  32922. normals.push(-vn.x, -vn.y, -vn.z);
  32923. normals.push(-vn.x, -vn.y, -vn.z);
  32924. normals.push(-vn.x, -vn.y, -vn.z);
  32925. indices.push(StartIndex);
  32926. indices.push(StartIndex + 1);
  32927. indices.push(StartIndex + 2);
  32928. indices.push(StartIndex + 1);
  32929. indices.push(StartIndex + 3);
  32930. indices.push(StartIndex + 2);
  32931. }
  32932. else {
  32933. normals.push(vn.x, vn.y, vn.z);
  32934. normals.push(vn.x, vn.y, vn.z);
  32935. normals.push(vn.x, vn.y, vn.z);
  32936. normals.push(vn.x, vn.y, vn.z);
  32937. indices.push(StartIndex);
  32938. indices.push(StartIndex + 2);
  32939. indices.push(StartIndex + 1);
  32940. indices.push(StartIndex + 1);
  32941. indices.push(StartIndex + 2);
  32942. indices.push(StartIndex + 3);
  32943. }
  32944. StartIndex += 4;
  32945. }
  32946. ;
  32947. };
  32948. return PolygonMeshBuilder;
  32949. })();
  32950. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32951. })(BABYLON || (BABYLON = {}));
  32952. var BABYLON;
  32953. (function (BABYLON) {
  32954. var Octree = (function () {
  32955. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32956. if (maxDepth === void 0) { maxDepth = 2; }
  32957. this.maxDepth = maxDepth;
  32958. this.dynamicContent = new Array();
  32959. this._maxBlockCapacity = maxBlockCapacity || 64;
  32960. this._selectionContent = new BABYLON.SmartArray(1024);
  32961. this._creationFunc = creationFunc;
  32962. }
  32963. // Methods
  32964. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32965. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32966. };
  32967. Octree.prototype.addMesh = function (entry) {
  32968. for (var index = 0; index < this.blocks.length; index++) {
  32969. var block = this.blocks[index];
  32970. block.addEntry(entry);
  32971. }
  32972. };
  32973. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32974. this._selectionContent.reset();
  32975. for (var index = 0; index < this.blocks.length; index++) {
  32976. var block = this.blocks[index];
  32977. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32978. }
  32979. if (allowDuplicate) {
  32980. this._selectionContent.concat(this.dynamicContent);
  32981. }
  32982. else {
  32983. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32984. }
  32985. return this._selectionContent;
  32986. };
  32987. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32988. this._selectionContent.reset();
  32989. for (var index = 0; index < this.blocks.length; index++) {
  32990. var block = this.blocks[index];
  32991. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32992. }
  32993. if (allowDuplicate) {
  32994. this._selectionContent.concat(this.dynamicContent);
  32995. }
  32996. else {
  32997. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32998. }
  32999. return this._selectionContent;
  33000. };
  33001. Octree.prototype.intersectsRay = function (ray) {
  33002. this._selectionContent.reset();
  33003. for (var index = 0; index < this.blocks.length; index++) {
  33004. var block = this.blocks[index];
  33005. block.intersectsRay(ray, this._selectionContent);
  33006. }
  33007. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33008. return this._selectionContent;
  33009. };
  33010. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  33011. target.blocks = new Array();
  33012. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  33013. // Segmenting space
  33014. for (var x = 0; x < 2; x++) {
  33015. for (var y = 0; y < 2; y++) {
  33016. for (var z = 0; z < 2; z++) {
  33017. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  33018. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  33019. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  33020. block.addEntries(entries);
  33021. target.blocks.push(block);
  33022. }
  33023. }
  33024. }
  33025. };
  33026. Octree.CreationFuncForMeshes = function (entry, block) {
  33027. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33028. block.entries.push(entry);
  33029. }
  33030. };
  33031. Octree.CreationFuncForSubMeshes = function (entry, block) {
  33032. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33033. block.entries.push(entry);
  33034. }
  33035. };
  33036. return Octree;
  33037. })();
  33038. BABYLON.Octree = Octree;
  33039. })(BABYLON || (BABYLON = {}));
  33040. var BABYLON;
  33041. (function (BABYLON) {
  33042. var OctreeBlock = (function () {
  33043. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  33044. this.entries = new Array();
  33045. this._boundingVectors = new Array();
  33046. this._capacity = capacity;
  33047. this._depth = depth;
  33048. this._maxDepth = maxDepth;
  33049. this._creationFunc = creationFunc;
  33050. this._minPoint = minPoint;
  33051. this._maxPoint = maxPoint;
  33052. this._boundingVectors.push(minPoint.clone());
  33053. this._boundingVectors.push(maxPoint.clone());
  33054. this._boundingVectors.push(minPoint.clone());
  33055. this._boundingVectors[2].x = maxPoint.x;
  33056. this._boundingVectors.push(minPoint.clone());
  33057. this._boundingVectors[3].y = maxPoint.y;
  33058. this._boundingVectors.push(minPoint.clone());
  33059. this._boundingVectors[4].z = maxPoint.z;
  33060. this._boundingVectors.push(maxPoint.clone());
  33061. this._boundingVectors[5].z = minPoint.z;
  33062. this._boundingVectors.push(maxPoint.clone());
  33063. this._boundingVectors[6].x = minPoint.x;
  33064. this._boundingVectors.push(maxPoint.clone());
  33065. this._boundingVectors[7].y = minPoint.y;
  33066. }
  33067. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  33068. // Property
  33069. get: function () {
  33070. return this._capacity;
  33071. },
  33072. enumerable: true,
  33073. configurable: true
  33074. });
  33075. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  33076. get: function () {
  33077. return this._minPoint;
  33078. },
  33079. enumerable: true,
  33080. configurable: true
  33081. });
  33082. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  33083. get: function () {
  33084. return this._maxPoint;
  33085. },
  33086. enumerable: true,
  33087. configurable: true
  33088. });
  33089. // Methods
  33090. OctreeBlock.prototype.addEntry = function (entry) {
  33091. if (this.blocks) {
  33092. for (var index = 0; index < this.blocks.length; index++) {
  33093. var block = this.blocks[index];
  33094. block.addEntry(entry);
  33095. }
  33096. return;
  33097. }
  33098. this._creationFunc(entry, this);
  33099. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  33100. this.createInnerBlocks();
  33101. }
  33102. };
  33103. OctreeBlock.prototype.addEntries = function (entries) {
  33104. for (var index = 0; index < entries.length; index++) {
  33105. var mesh = entries[index];
  33106. this.addEntry(mesh);
  33107. }
  33108. };
  33109. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  33110. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  33111. if (this.blocks) {
  33112. for (var index = 0; index < this.blocks.length; index++) {
  33113. var block = this.blocks[index];
  33114. block.select(frustumPlanes, selection, allowDuplicate);
  33115. }
  33116. return;
  33117. }
  33118. if (allowDuplicate) {
  33119. selection.concat(this.entries);
  33120. }
  33121. else {
  33122. selection.concatWithNoDuplicate(this.entries);
  33123. }
  33124. }
  33125. };
  33126. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  33127. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  33128. if (this.blocks) {
  33129. for (var index = 0; index < this.blocks.length; index++) {
  33130. var block = this.blocks[index];
  33131. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  33132. }
  33133. return;
  33134. }
  33135. if (allowDuplicate) {
  33136. selection.concat(this.entries);
  33137. }
  33138. else {
  33139. selection.concatWithNoDuplicate(this.entries);
  33140. }
  33141. }
  33142. };
  33143. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  33144. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  33145. if (this.blocks) {
  33146. for (var index = 0; index < this.blocks.length; index++) {
  33147. var block = this.blocks[index];
  33148. block.intersectsRay(ray, selection);
  33149. }
  33150. return;
  33151. }
  33152. selection.concatWithNoDuplicate(this.entries);
  33153. }
  33154. };
  33155. OctreeBlock.prototype.createInnerBlocks = function () {
  33156. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33157. };
  33158. return OctreeBlock;
  33159. })();
  33160. BABYLON.OctreeBlock = OctreeBlock;
  33161. })(BABYLON || (BABYLON = {}));
  33162. var BABYLON;
  33163. (function (BABYLON) {
  33164. var BlurPostProcess = (function (_super) {
  33165. __extends(BlurPostProcess, _super);
  33166. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33167. var _this = this;
  33168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33169. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33170. this.direction = direction;
  33171. this.blurWidth = blurWidth;
  33172. this.onApply = function (effect) {
  33173. effect.setFloat2("screenSize", _this.width, _this.height);
  33174. effect.setVector2("direction", _this.direction);
  33175. effect.setFloat("blurWidth", _this.blurWidth);
  33176. };
  33177. }
  33178. return BlurPostProcess;
  33179. })(BABYLON.PostProcess);
  33180. BABYLON.BlurPostProcess = BlurPostProcess;
  33181. })(BABYLON || (BABYLON = {}));
  33182. var BABYLON;
  33183. (function (BABYLON) {
  33184. var RefractionPostProcess = (function (_super) {
  33185. __extends(RefractionPostProcess, _super);
  33186. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33187. var _this = this;
  33188. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33189. this.color = color;
  33190. this.depth = depth;
  33191. this.colorLevel = colorLevel;
  33192. this.onActivate = function (cam) {
  33193. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33194. };
  33195. this.onApply = function (effect) {
  33196. effect.setColor3("baseColor", _this.color);
  33197. effect.setFloat("depth", _this.depth);
  33198. effect.setFloat("colorLevel", _this.colorLevel);
  33199. effect.setTexture("refractionSampler", _this._refRexture);
  33200. };
  33201. }
  33202. // Methods
  33203. RefractionPostProcess.prototype.dispose = function (camera) {
  33204. if (this._refRexture) {
  33205. this._refRexture.dispose();
  33206. }
  33207. _super.prototype.dispose.call(this, camera);
  33208. };
  33209. return RefractionPostProcess;
  33210. })(BABYLON.PostProcess);
  33211. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33212. })(BABYLON || (BABYLON = {}));
  33213. var BABYLON;
  33214. (function (BABYLON) {
  33215. var BlackAndWhitePostProcess = (function (_super) {
  33216. __extends(BlackAndWhitePostProcess, _super);
  33217. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33218. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33219. }
  33220. return BlackAndWhitePostProcess;
  33221. })(BABYLON.PostProcess);
  33222. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33223. })(BABYLON || (BABYLON = {}));
  33224. var BABYLON;
  33225. (function (BABYLON) {
  33226. var ConvolutionPostProcess = (function (_super) {
  33227. __extends(ConvolutionPostProcess, _super);
  33228. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33229. var _this = this;
  33230. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33231. this.kernel = kernel;
  33232. this.onApply = function (effect) {
  33233. effect.setFloat2("screenSize", _this.width, _this.height);
  33234. effect.setArray("kernel", _this.kernel);
  33235. };
  33236. }
  33237. // Statics
  33238. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33239. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33240. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33241. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33242. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33243. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33244. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33245. return ConvolutionPostProcess;
  33246. })(BABYLON.PostProcess);
  33247. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33248. })(BABYLON || (BABYLON = {}));
  33249. var BABYLON;
  33250. (function (BABYLON) {
  33251. var FilterPostProcess = (function (_super) {
  33252. __extends(FilterPostProcess, _super);
  33253. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33254. var _this = this;
  33255. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33256. this.kernelMatrix = kernelMatrix;
  33257. this.onApply = function (effect) {
  33258. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33259. };
  33260. }
  33261. return FilterPostProcess;
  33262. })(BABYLON.PostProcess);
  33263. BABYLON.FilterPostProcess = FilterPostProcess;
  33264. })(BABYLON || (BABYLON = {}));
  33265. var BABYLON;
  33266. (function (BABYLON) {
  33267. var FxaaPostProcess = (function (_super) {
  33268. __extends(FxaaPostProcess, _super);
  33269. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33270. var _this = this;
  33271. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33272. this.onSizeChanged = function () {
  33273. _this.texelWidth = 1.0 / _this.width;
  33274. _this.texelHeight = 1.0 / _this.height;
  33275. };
  33276. this.onApply = function (effect) {
  33277. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33278. };
  33279. }
  33280. return FxaaPostProcess;
  33281. })(BABYLON.PostProcess);
  33282. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33283. })(BABYLON || (BABYLON = {}));
  33284. var BABYLON;
  33285. (function (BABYLON) {
  33286. var StereoscopicInterlacePostProcess = (function (_super) {
  33287. __extends(StereoscopicInterlacePostProcess, _super);
  33288. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33289. var _this = this;
  33290. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33291. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33292. this.onSizeChanged = function () {
  33293. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33294. };
  33295. this.onApply = function (effect) {
  33296. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33297. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33298. };
  33299. }
  33300. return StereoscopicInterlacePostProcess;
  33301. })(BABYLON.PostProcess);
  33302. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33303. })(BABYLON || (BABYLON = {}));
  33304. var BABYLON;
  33305. (function (BABYLON) {
  33306. var LensFlare = (function () {
  33307. function LensFlare(size, position, color, imgUrl, system) {
  33308. this.size = size;
  33309. this.position = position;
  33310. this.dispose = function () {
  33311. if (this.texture) {
  33312. this.texture.dispose();
  33313. }
  33314. // Remove from scene
  33315. var index = this._system.lensFlares.indexOf(this);
  33316. this._system.lensFlares.splice(index, 1);
  33317. };
  33318. this.color = color || new BABYLON.Color3(1, 1, 1);
  33319. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33320. this._system = system;
  33321. system.lensFlares.push(this);
  33322. }
  33323. return LensFlare;
  33324. })();
  33325. BABYLON.LensFlare = LensFlare;
  33326. })(BABYLON || (BABYLON = {}));
  33327. var BABYLON;
  33328. (function (BABYLON) {
  33329. var LensFlareSystem = (function () {
  33330. function LensFlareSystem(name, emitter, scene) {
  33331. this.name = name;
  33332. this.lensFlares = new Array();
  33333. this.borderLimit = 300;
  33334. this.layerMask = 0x0FFFFFFF;
  33335. this._vertexDeclaration = [2];
  33336. this._vertexStrideSize = 2 * 4;
  33337. this._isEnabled = true;
  33338. this._scene = scene;
  33339. this._emitter = emitter;
  33340. scene.lensFlareSystems.push(this);
  33341. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33342. // VBO
  33343. var vertices = [];
  33344. vertices.push(1, 1);
  33345. vertices.push(-1, 1);
  33346. vertices.push(-1, -1);
  33347. vertices.push(1, -1);
  33348. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33349. // Indices
  33350. var indices = [];
  33351. indices.push(0);
  33352. indices.push(1);
  33353. indices.push(2);
  33354. indices.push(0);
  33355. indices.push(2);
  33356. indices.push(3);
  33357. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33358. // Effects
  33359. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33360. }
  33361. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33362. get: function () {
  33363. return this._isEnabled;
  33364. },
  33365. set: function (value) {
  33366. this._isEnabled = value;
  33367. },
  33368. enumerable: true,
  33369. configurable: true
  33370. });
  33371. LensFlareSystem.prototype.getScene = function () {
  33372. return this._scene;
  33373. };
  33374. LensFlareSystem.prototype.getEmitter = function () {
  33375. return this._emitter;
  33376. };
  33377. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33378. this._emitter = newEmitter;
  33379. };
  33380. LensFlareSystem.prototype.getEmitterPosition = function () {
  33381. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33382. };
  33383. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33384. var position = this.getEmitterPosition();
  33385. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33386. this._positionX = position.x;
  33387. this._positionY = position.y;
  33388. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33389. if (position.z > 0) {
  33390. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33391. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33392. return true;
  33393. }
  33394. }
  33395. return false;
  33396. };
  33397. LensFlareSystem.prototype._isVisible = function () {
  33398. if (!this._isEnabled) {
  33399. return false;
  33400. }
  33401. var emitterPosition = this.getEmitterPosition();
  33402. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33403. var distance = direction.length();
  33404. direction.normalize();
  33405. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33406. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33407. return !pickInfo.hit || pickInfo.distance > distance;
  33408. };
  33409. LensFlareSystem.prototype.render = function () {
  33410. if (!this._effect.isReady())
  33411. return false;
  33412. var engine = this._scene.getEngine();
  33413. var viewport = this._scene.activeCamera.viewport;
  33414. var globalViewport = viewport.toScreenGlobal(engine);
  33415. // Position
  33416. if (!this.computeEffectivePosition(globalViewport)) {
  33417. return false;
  33418. }
  33419. // Visibility
  33420. if (!this._isVisible()) {
  33421. return false;
  33422. }
  33423. // Intensity
  33424. var awayX;
  33425. var awayY;
  33426. if (this._positionX < this.borderLimit + globalViewport.x) {
  33427. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33428. }
  33429. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33430. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33431. }
  33432. else {
  33433. awayX = 0;
  33434. }
  33435. if (this._positionY < this.borderLimit + globalViewport.y) {
  33436. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33437. }
  33438. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33439. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33440. }
  33441. else {
  33442. awayY = 0;
  33443. }
  33444. var away = (awayX > awayY) ? awayX : awayY;
  33445. if (away > this.borderLimit) {
  33446. away = this.borderLimit;
  33447. }
  33448. var intensity = 1.0 - (away / this.borderLimit);
  33449. if (intensity < 0) {
  33450. return false;
  33451. }
  33452. if (intensity > 1.0) {
  33453. intensity = 1.0;
  33454. }
  33455. // Position
  33456. var centerX = globalViewport.x + globalViewport.width / 2;
  33457. var centerY = globalViewport.y + globalViewport.height / 2;
  33458. var distX = centerX - this._positionX;
  33459. var distY = centerY - this._positionY;
  33460. // Effects
  33461. engine.enableEffect(this._effect);
  33462. engine.setState(false);
  33463. engine.setDepthBuffer(false);
  33464. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  33465. // VBOs
  33466. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  33467. // Flares
  33468. for (var index = 0; index < this.lensFlares.length; index++) {
  33469. var flare = this.lensFlares[index];
  33470. var x = centerX - (distX * flare.position);
  33471. var y = centerY - (distY * flare.position);
  33472. var cw = flare.size;
  33473. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  33474. var cx = 2 * (x / globalViewport.width) - 1.0;
  33475. var cy = 1.0 - 2 * (y / globalViewport.height);
  33476. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  33477. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  33478. // Texture
  33479. this._effect.setTexture("textureSampler", flare.texture);
  33480. // Color
  33481. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  33482. // Draw order
  33483. engine.draw(true, 0, 6);
  33484. }
  33485. engine.setDepthBuffer(true);
  33486. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33487. return true;
  33488. };
  33489. LensFlareSystem.prototype.dispose = function () {
  33490. if (this._vertexBuffer) {
  33491. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  33492. this._vertexBuffer = null;
  33493. }
  33494. if (this._indexBuffer) {
  33495. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33496. this._indexBuffer = null;
  33497. }
  33498. while (this.lensFlares.length) {
  33499. this.lensFlares[0].dispose();
  33500. }
  33501. // Remove from scene
  33502. var index = this._scene.lensFlareSystems.indexOf(this);
  33503. this._scene.lensFlareSystems.splice(index, 1);
  33504. };
  33505. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  33506. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  33507. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  33508. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  33509. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  33510. var parsedFlare = parsedLensFlareSystem.flares[index];
  33511. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  33512. }
  33513. return lensFlareSystem;
  33514. };
  33515. LensFlareSystem.prototype.serialize = function () {
  33516. var serializationObject = {};
  33517. serializationObject.emitterId = this.getEmitter().id;
  33518. serializationObject.borderLimit = this.borderLimit;
  33519. serializationObject.flares = [];
  33520. for (var index = 0; index < this.lensFlares.length; index++) {
  33521. var flare = this.lensFlares[index];
  33522. serializationObject.flares.push({
  33523. size: flare.size,
  33524. position: flare.position,
  33525. color: flare.color.asArray(),
  33526. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  33527. });
  33528. }
  33529. return serializationObject;
  33530. };
  33531. return LensFlareSystem;
  33532. })();
  33533. BABYLON.LensFlareSystem = LensFlareSystem;
  33534. })(BABYLON || (BABYLON = {}));
  33535. var BABYLON;
  33536. (function (BABYLON) {
  33537. // We're mainly based on the logic defined into the FreeCamera code
  33538. var DeviceOrientationCamera = (function (_super) {
  33539. __extends(DeviceOrientationCamera, _super);
  33540. function DeviceOrientationCamera(name, position, scene) {
  33541. var _this = this;
  33542. _super.call(this, name, position, scene);
  33543. this._offsetX = null;
  33544. this._offsetY = null;
  33545. this._orientationGamma = 0;
  33546. this._orientationBeta = 0;
  33547. this._initialOrientationGamma = 0;
  33548. this._initialOrientationBeta = 0;
  33549. this.angularSensibility = 10000.0;
  33550. this.moveSensibility = 50.0;
  33551. window.addEventListener("resize", function () {
  33552. _this._initialOrientationGamma = null;
  33553. }, false);
  33554. }
  33555. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  33556. var _this = this;
  33557. if (this._attachedCanvas) {
  33558. return;
  33559. }
  33560. this._attachedCanvas = canvas;
  33561. if (!this._orientationChanged) {
  33562. this._orientationChanged = function (evt) {
  33563. if (!_this._initialOrientationGamma) {
  33564. _this._initialOrientationGamma = evt.gamma;
  33565. _this._initialOrientationBeta = evt.beta;
  33566. }
  33567. _this._orientationGamma = evt.gamma;
  33568. _this._orientationBeta = evt.beta;
  33569. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  33570. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  33571. };
  33572. }
  33573. window.addEventListener("deviceorientation", this._orientationChanged);
  33574. };
  33575. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  33576. if (this._attachedCanvas !== canvas) {
  33577. return;
  33578. }
  33579. window.removeEventListener("deviceorientation", this._orientationChanged);
  33580. this._attachedCanvas = null;
  33581. this._orientationGamma = 0;
  33582. this._orientationBeta = 0;
  33583. this._initialOrientationGamma = 0;
  33584. this._initialOrientationBeta = 0;
  33585. };
  33586. DeviceOrientationCamera.prototype._checkInputs = function () {
  33587. if (!this._offsetX) {
  33588. return;
  33589. }
  33590. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  33591. var speed = this._computeLocalCameraSpeed();
  33592. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  33593. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  33594. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  33595. _super.prototype._checkInputs.call(this);
  33596. };
  33597. return DeviceOrientationCamera;
  33598. })(BABYLON.FreeCamera);
  33599. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  33600. })(BABYLON || (BABYLON = {}));
  33601. var BABYLON;
  33602. (function (BABYLON) {
  33603. var Gamepads = (function () {
  33604. function Gamepads(ongamedpadconnected) {
  33605. var _this = this;
  33606. this.babylonGamepads = [];
  33607. this.oneGamepadConnected = false;
  33608. this.isMonitoring = false;
  33609. this.gamepadEventSupported = 'GamepadEvent' in window;
  33610. this.gamepadSupportAvailable = (navigator.getGamepads ||
  33611. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  33612. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  33613. this._callbackGamepadConnected = ongamedpadconnected;
  33614. if (this.gamepadSupportAvailable) {
  33615. // Checking if the gamepad connected event is supported (like in Firefox)
  33616. if (this.gamepadEventSupported) {
  33617. window.addEventListener('gamepadconnected', function (evt) {
  33618. _this._onGamepadConnected(evt);
  33619. }, false);
  33620. window.addEventListener('gamepaddisconnected', function (evt) {
  33621. _this._onGamepadDisconnected(evt);
  33622. }, false);
  33623. }
  33624. else {
  33625. this._startMonitoringGamepads();
  33626. }
  33627. if (!this.oneGamepadConnected) {
  33628. this._insertGamepadDOMInstructions();
  33629. }
  33630. }
  33631. else {
  33632. this._insertGamepadDOMNotSupported();
  33633. }
  33634. }
  33635. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  33636. Gamepads.gamepadDOMInfo = document.createElement("div");
  33637. var buttonAImage = document.createElement("img");
  33638. buttonAImage.src = this.buttonADataURL;
  33639. var spanMessage = document.createElement("span");
  33640. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  33641. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  33642. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33643. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33644. Gamepads.gamepadDOMInfo.style.width = "100%";
  33645. Gamepads.gamepadDOMInfo.style.height = "48px";
  33646. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33647. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33648. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33649. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33650. buttonAImage.style.position = "relative";
  33651. buttonAImage.style.bottom = "8px";
  33652. spanMessage.style.position = "relative";
  33653. spanMessage.style.fontSize = "32px";
  33654. spanMessage.style.bottom = "32px";
  33655. spanMessage.style.color = "green";
  33656. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33657. };
  33658. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  33659. Gamepads.gamepadDOMInfo = document.createElement("div");
  33660. var spanMessage = document.createElement("span");
  33661. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  33662. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  33663. Gamepads.gamepadDOMInfo.style.position = "absolute";
  33664. Gamepads.gamepadDOMInfo.style.width = "100%";
  33665. Gamepads.gamepadDOMInfo.style.height = "40px";
  33666. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  33667. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  33668. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  33669. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  33670. spanMessage.style.position = "relative";
  33671. spanMessage.style.fontSize = "32px";
  33672. spanMessage.style.color = "red";
  33673. document.body.appendChild(Gamepads.gamepadDOMInfo);
  33674. };
  33675. Gamepads.prototype.dispose = function () {
  33676. if (Gamepads.gamepadDOMInfo) {
  33677. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33678. }
  33679. };
  33680. Gamepads.prototype._onGamepadConnected = function (evt) {
  33681. var newGamepad = this._addNewGamepad(evt.gamepad);
  33682. if (this._callbackGamepadConnected)
  33683. this._callbackGamepadConnected(newGamepad);
  33684. this._startMonitoringGamepads();
  33685. };
  33686. Gamepads.prototype._addNewGamepad = function (gamepad) {
  33687. if (!this.oneGamepadConnected) {
  33688. this.oneGamepadConnected = true;
  33689. if (Gamepads.gamepadDOMInfo) {
  33690. document.body.removeChild(Gamepads.gamepadDOMInfo);
  33691. Gamepads.gamepadDOMInfo = null;
  33692. }
  33693. }
  33694. var newGamepad;
  33695. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  33696. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  33697. }
  33698. else {
  33699. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  33700. }
  33701. this.babylonGamepads.push(newGamepad);
  33702. return newGamepad;
  33703. };
  33704. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  33705. // Remove the gamepad from the list of gamepads to monitor.
  33706. for (var i in this.babylonGamepads) {
  33707. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  33708. this.babylonGamepads.splice(i, 1);
  33709. break;
  33710. }
  33711. }
  33712. // If no gamepads are left, stop the polling loop.
  33713. if (this.babylonGamepads.length == 0) {
  33714. this._stopMonitoringGamepads();
  33715. }
  33716. };
  33717. Gamepads.prototype._startMonitoringGamepads = function () {
  33718. if (!this.isMonitoring) {
  33719. this.isMonitoring = true;
  33720. this._checkGamepadsStatus();
  33721. }
  33722. };
  33723. Gamepads.prototype._stopMonitoringGamepads = function () {
  33724. this.isMonitoring = false;
  33725. };
  33726. Gamepads.prototype._checkGamepadsStatus = function () {
  33727. var _this = this;
  33728. // updating gamepad objects
  33729. this._updateGamepadObjects();
  33730. for (var i in this.babylonGamepads) {
  33731. this.babylonGamepads[i].update();
  33732. }
  33733. if (this.isMonitoring) {
  33734. if (window.requestAnimationFrame) {
  33735. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33736. }
  33737. else if (window.mozRequestAnimationFrame) {
  33738. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33739. }
  33740. else if (window.webkitRequestAnimationFrame) {
  33741. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33742. }
  33743. }
  33744. };
  33745. // This function is called only on Chrome, which does not yet support
  33746. // connection/disconnection events, but requires you to monitor
  33747. // an array for changes.
  33748. Gamepads.prototype._updateGamepadObjects = function () {
  33749. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33750. for (var i = 0; i < gamepads.length; i++) {
  33751. if (gamepads[i]) {
  33752. if (!(gamepads[i].index in this.babylonGamepads)) {
  33753. var newGamepad = this._addNewGamepad(gamepads[i]);
  33754. if (this._callbackGamepadConnected) {
  33755. this._callbackGamepadConnected(newGamepad);
  33756. }
  33757. }
  33758. else {
  33759. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33760. }
  33761. }
  33762. }
  33763. };
  33764. return Gamepads;
  33765. })();
  33766. BABYLON.Gamepads = Gamepads;
  33767. var StickValues = (function () {
  33768. function StickValues(x, y) {
  33769. this.x = x;
  33770. this.y = y;
  33771. }
  33772. return StickValues;
  33773. })();
  33774. BABYLON.StickValues = StickValues;
  33775. var Gamepad = (function () {
  33776. function Gamepad(id, index, browserGamepad) {
  33777. this.id = id;
  33778. this.index = index;
  33779. this.browserGamepad = browserGamepad;
  33780. if (this.browserGamepad.axes.length >= 2) {
  33781. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33782. }
  33783. if (this.browserGamepad.axes.length >= 4) {
  33784. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33785. }
  33786. }
  33787. Gamepad.prototype.onleftstickchanged = function (callback) {
  33788. this._onleftstickchanged = callback;
  33789. };
  33790. Gamepad.prototype.onrightstickchanged = function (callback) {
  33791. this._onrightstickchanged = callback;
  33792. };
  33793. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33794. get: function () {
  33795. return this._leftStick;
  33796. },
  33797. set: function (newValues) {
  33798. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33799. this._onleftstickchanged(newValues);
  33800. }
  33801. this._leftStick = newValues;
  33802. },
  33803. enumerable: true,
  33804. configurable: true
  33805. });
  33806. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33807. get: function () {
  33808. return this._rightStick;
  33809. },
  33810. set: function (newValues) {
  33811. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33812. this._onrightstickchanged(newValues);
  33813. }
  33814. this._rightStick = newValues;
  33815. },
  33816. enumerable: true,
  33817. configurable: true
  33818. });
  33819. Gamepad.prototype.update = function () {
  33820. if (this._leftStick) {
  33821. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33822. }
  33823. if (this._rightStick) {
  33824. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33825. }
  33826. };
  33827. return Gamepad;
  33828. })();
  33829. BABYLON.Gamepad = Gamepad;
  33830. var GenericPad = (function (_super) {
  33831. __extends(GenericPad, _super);
  33832. function GenericPad(id, index, gamepad) {
  33833. _super.call(this, id, index, gamepad);
  33834. this.id = id;
  33835. this.index = index;
  33836. this.gamepad = gamepad;
  33837. this._buttons = new Array(gamepad.buttons.length);
  33838. }
  33839. GenericPad.prototype.onbuttondown = function (callback) {
  33840. this._onbuttondown = callback;
  33841. };
  33842. GenericPad.prototype.onbuttonup = function (callback) {
  33843. this._onbuttonup = callback;
  33844. };
  33845. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33846. if (newValue !== currentValue) {
  33847. if (this._onbuttondown && newValue === 1) {
  33848. this._onbuttondown(buttonIndex);
  33849. }
  33850. if (this._onbuttonup && newValue === 0) {
  33851. this._onbuttonup(buttonIndex);
  33852. }
  33853. }
  33854. return newValue;
  33855. };
  33856. GenericPad.prototype.update = function () {
  33857. _super.prototype.update.call(this);
  33858. for (var index = 0; index < this._buttons.length; index++) {
  33859. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33860. }
  33861. };
  33862. return GenericPad;
  33863. })(Gamepad);
  33864. BABYLON.GenericPad = GenericPad;
  33865. (function (Xbox360Button) {
  33866. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33867. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33868. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33869. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33870. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33871. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33872. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33873. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33874. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33875. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33876. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33877. var Xbox360Button = BABYLON.Xbox360Button;
  33878. (function (Xbox360Dpad) {
  33879. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33880. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33881. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33882. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33883. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33884. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33885. var Xbox360Pad = (function (_super) {
  33886. __extends(Xbox360Pad, _super);
  33887. function Xbox360Pad() {
  33888. _super.apply(this, arguments);
  33889. this._leftTrigger = 0;
  33890. this._rightTrigger = 0;
  33891. this._buttonA = 0;
  33892. this._buttonB = 0;
  33893. this._buttonX = 0;
  33894. this._buttonY = 0;
  33895. this._buttonBack = 0;
  33896. this._buttonStart = 0;
  33897. this._buttonLB = 0;
  33898. this._buttonRB = 0;
  33899. this._buttonLeftStick = 0;
  33900. this._buttonRightStick = 0;
  33901. this._dPadUp = 0;
  33902. this._dPadDown = 0;
  33903. this._dPadLeft = 0;
  33904. this._dPadRight = 0;
  33905. }
  33906. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33907. this._onlefttriggerchanged = callback;
  33908. };
  33909. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33910. this._onrighttriggerchanged = callback;
  33911. };
  33912. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33913. get: function () {
  33914. return this._leftTrigger;
  33915. },
  33916. set: function (newValue) {
  33917. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33918. this._onlefttriggerchanged(newValue);
  33919. }
  33920. this._leftTrigger = newValue;
  33921. },
  33922. enumerable: true,
  33923. configurable: true
  33924. });
  33925. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33926. get: function () {
  33927. return this._rightTrigger;
  33928. },
  33929. set: function (newValue) {
  33930. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33931. this._onrighttriggerchanged(newValue);
  33932. }
  33933. this._rightTrigger = newValue;
  33934. },
  33935. enumerable: true,
  33936. configurable: true
  33937. });
  33938. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33939. this._onbuttondown = callback;
  33940. };
  33941. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33942. this._onbuttonup = callback;
  33943. };
  33944. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33945. this._ondpaddown = callback;
  33946. };
  33947. Xbox360Pad.prototype.ondpadup = function (callback) {
  33948. this._ondpadup = callback;
  33949. };
  33950. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33951. if (newValue !== currentValue) {
  33952. if (this._onbuttondown && newValue === 1) {
  33953. this._onbuttondown(buttonType);
  33954. }
  33955. if (this._onbuttonup && newValue === 0) {
  33956. this._onbuttonup(buttonType);
  33957. }
  33958. }
  33959. return newValue;
  33960. };
  33961. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33962. if (newValue !== currentValue) {
  33963. if (this._ondpaddown && newValue === 1) {
  33964. this._ondpaddown(buttonType);
  33965. }
  33966. if (this._ondpadup && newValue === 0) {
  33967. this._ondpadup(buttonType);
  33968. }
  33969. }
  33970. return newValue;
  33971. };
  33972. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33973. get: function () {
  33974. return this._buttonA;
  33975. },
  33976. set: function (value) {
  33977. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33978. },
  33979. enumerable: true,
  33980. configurable: true
  33981. });
  33982. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33983. get: function () {
  33984. return this._buttonB;
  33985. },
  33986. set: function (value) {
  33987. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33988. },
  33989. enumerable: true,
  33990. configurable: true
  33991. });
  33992. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33993. get: function () {
  33994. return this._buttonX;
  33995. },
  33996. set: function (value) {
  33997. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33998. },
  33999. enumerable: true,
  34000. configurable: true
  34001. });
  34002. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  34003. get: function () {
  34004. return this._buttonY;
  34005. },
  34006. set: function (value) {
  34007. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  34008. },
  34009. enumerable: true,
  34010. configurable: true
  34011. });
  34012. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  34013. get: function () {
  34014. return this._buttonStart;
  34015. },
  34016. set: function (value) {
  34017. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  34018. },
  34019. enumerable: true,
  34020. configurable: true
  34021. });
  34022. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  34023. get: function () {
  34024. return this._buttonBack;
  34025. },
  34026. set: function (value) {
  34027. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  34028. },
  34029. enumerable: true,
  34030. configurable: true
  34031. });
  34032. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  34033. get: function () {
  34034. return this._buttonLB;
  34035. },
  34036. set: function (value) {
  34037. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  34038. },
  34039. enumerable: true,
  34040. configurable: true
  34041. });
  34042. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  34043. get: function () {
  34044. return this._buttonRB;
  34045. },
  34046. set: function (value) {
  34047. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  34048. },
  34049. enumerable: true,
  34050. configurable: true
  34051. });
  34052. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  34053. get: function () {
  34054. return this._buttonLeftStick;
  34055. },
  34056. set: function (value) {
  34057. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  34058. },
  34059. enumerable: true,
  34060. configurable: true
  34061. });
  34062. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  34063. get: function () {
  34064. return this._buttonRightStick;
  34065. },
  34066. set: function (value) {
  34067. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  34068. },
  34069. enumerable: true,
  34070. configurable: true
  34071. });
  34072. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  34073. get: function () {
  34074. return this._dPadUp;
  34075. },
  34076. set: function (value) {
  34077. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  34078. },
  34079. enumerable: true,
  34080. configurable: true
  34081. });
  34082. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  34083. get: function () {
  34084. return this._dPadDown;
  34085. },
  34086. set: function (value) {
  34087. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  34088. },
  34089. enumerable: true,
  34090. configurable: true
  34091. });
  34092. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  34093. get: function () {
  34094. return this._dPadLeft;
  34095. },
  34096. set: function (value) {
  34097. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  34098. },
  34099. enumerable: true,
  34100. configurable: true
  34101. });
  34102. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  34103. get: function () {
  34104. return this._dPadRight;
  34105. },
  34106. set: function (value) {
  34107. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  34108. },
  34109. enumerable: true,
  34110. configurable: true
  34111. });
  34112. Xbox360Pad.prototype.update = function () {
  34113. _super.prototype.update.call(this);
  34114. this.buttonA = this.browserGamepad.buttons[0].value;
  34115. this.buttonB = this.browserGamepad.buttons[1].value;
  34116. this.buttonX = this.browserGamepad.buttons[2].value;
  34117. this.buttonY = this.browserGamepad.buttons[3].value;
  34118. this.buttonLB = this.browserGamepad.buttons[4].value;
  34119. this.buttonRB = this.browserGamepad.buttons[5].value;
  34120. this.leftTrigger = this.browserGamepad.buttons[6].value;
  34121. this.rightTrigger = this.browserGamepad.buttons[7].value;
  34122. this.buttonBack = this.browserGamepad.buttons[8].value;
  34123. this.buttonStart = this.browserGamepad.buttons[9].value;
  34124. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  34125. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  34126. this.dPadUp = this.browserGamepad.buttons[12].value;
  34127. this.dPadDown = this.browserGamepad.buttons[13].value;
  34128. this.dPadLeft = this.browserGamepad.buttons[14].value;
  34129. this.dPadRight = this.browserGamepad.buttons[15].value;
  34130. };
  34131. return Xbox360Pad;
  34132. })(Gamepad);
  34133. BABYLON.Xbox360Pad = Xbox360Pad;
  34134. })(BABYLON || (BABYLON = {}));
  34135. var BABYLON;
  34136. (function (BABYLON) {
  34137. // We're mainly based on the logic defined into the FreeCamera code
  34138. var GamepadCamera = (function (_super) {
  34139. __extends(GamepadCamera, _super);
  34140. function GamepadCamera(name, position, scene) {
  34141. var _this = this;
  34142. _super.call(this, name, position, scene);
  34143. this.angularSensibility = 200;
  34144. this.moveSensibility = 75;
  34145. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  34146. }
  34147. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  34148. // Only the first gamepad can control the camera
  34149. if (gamepad.index === 0) {
  34150. this._gamepad = gamepad;
  34151. }
  34152. };
  34153. GamepadCamera.prototype._checkInputs = function () {
  34154. if (this._gamepad) {
  34155. var LSValues = this._gamepad.leftStick;
  34156. var normalizedLX = LSValues.x / this.moveSensibility;
  34157. var normalizedLY = LSValues.y / this.moveSensibility;
  34158. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  34159. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  34160. var RSValues = this._gamepad.rightStick;
  34161. var normalizedRX = RSValues.x / this.angularSensibility;
  34162. var normalizedRY = RSValues.y / this.angularSensibility;
  34163. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  34164. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  34165. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  34166. var speed = this._computeLocalCameraSpeed() * 50.0;
  34167. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  34168. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  34169. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  34170. }
  34171. _super.prototype._checkInputs.call(this);
  34172. };
  34173. GamepadCamera.prototype.dispose = function () {
  34174. this._gamepads.dispose();
  34175. _super.prototype.dispose.call(this);
  34176. };
  34177. return GamepadCamera;
  34178. })(BABYLON.FreeCamera);
  34179. BABYLON.GamepadCamera = GamepadCamera;
  34180. })(BABYLON || (BABYLON = {}));
  34181. var BABYLON;
  34182. (function (BABYLON) {
  34183. var Analyser = (function () {
  34184. function Analyser(scene) {
  34185. this.SMOOTHING = 0.75;
  34186. this.FFT_SIZE = 512;
  34187. this.BARGRAPHAMPLITUDE = 256;
  34188. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34189. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34190. this._scene = scene;
  34191. this._audioEngine = BABYLON.Engine.audioEngine;
  34192. if (this._audioEngine.canUseWebAudio) {
  34193. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34194. this._webAudioAnalyser.minDecibels = -140;
  34195. this._webAudioAnalyser.maxDecibels = 0;
  34196. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34197. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34198. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34199. }
  34200. }
  34201. Analyser.prototype.getFrequencyBinCount = function () {
  34202. if (this._audioEngine.canUseWebAudio) {
  34203. return this._webAudioAnalyser.frequencyBinCount;
  34204. }
  34205. else {
  34206. return 0;
  34207. }
  34208. };
  34209. Analyser.prototype.getByteFrequencyData = function () {
  34210. if (this._audioEngine.canUseWebAudio) {
  34211. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34212. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34213. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34214. }
  34215. return this._byteFreqs;
  34216. };
  34217. Analyser.prototype.getByteTimeDomainData = function () {
  34218. if (this._audioEngine.canUseWebAudio) {
  34219. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34220. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34221. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34222. }
  34223. return this._byteTime;
  34224. };
  34225. Analyser.prototype.getFloatFrequencyData = function () {
  34226. if (this._audioEngine.canUseWebAudio) {
  34227. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34228. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34229. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34230. }
  34231. return this._floatFreqs;
  34232. };
  34233. Analyser.prototype.drawDebugCanvas = function () {
  34234. var _this = this;
  34235. if (this._audioEngine.canUseWebAudio) {
  34236. if (!this._debugCanvas) {
  34237. this._debugCanvas = document.createElement("canvas");
  34238. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34239. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34240. this._debugCanvas.style.position = "absolute";
  34241. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34242. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34243. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34244. document.body.appendChild(this._debugCanvas);
  34245. this._registerFunc = function () {
  34246. _this.drawDebugCanvas();
  34247. };
  34248. this._scene.registerBeforeRender(this._registerFunc);
  34249. }
  34250. if (this._registerFunc) {
  34251. var workingArray = this.getByteFrequencyData();
  34252. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34253. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34254. // Draw the frequency domain chart.
  34255. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34256. var value = workingArray[i];
  34257. var percent = value / this.BARGRAPHAMPLITUDE;
  34258. var height = this.DEBUGCANVASSIZE.height * percent;
  34259. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34260. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34261. var hue = i / this.getFrequencyBinCount() * 360;
  34262. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34263. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34264. }
  34265. }
  34266. }
  34267. };
  34268. Analyser.prototype.stopDebugCanvas = function () {
  34269. if (this._debugCanvas) {
  34270. this._scene.unregisterBeforeRender(this._registerFunc);
  34271. this._registerFunc = null;
  34272. document.body.removeChild(this._debugCanvas);
  34273. this._debugCanvas = null;
  34274. this._debugCanvasContext = null;
  34275. }
  34276. };
  34277. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34278. if (this._audioEngine.canUseWebAudio) {
  34279. inputAudioNode.connect(this._webAudioAnalyser);
  34280. this._webAudioAnalyser.connect(outputAudioNode);
  34281. }
  34282. };
  34283. Analyser.prototype.dispose = function () {
  34284. if (this._audioEngine.canUseWebAudio) {
  34285. this._webAudioAnalyser.disconnect();
  34286. }
  34287. };
  34288. return Analyser;
  34289. })();
  34290. BABYLON.Analyser = Analyser;
  34291. })(BABYLON || (BABYLON = {}));
  34292. var BABYLON;
  34293. (function (BABYLON) {
  34294. var AudioEngine = (function () {
  34295. function AudioEngine() {
  34296. this._audioContext = null;
  34297. this._audioContextInitialized = false;
  34298. this.canUseWebAudio = false;
  34299. this.WarnedWebAudioUnsupported = false;
  34300. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34301. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34302. this.canUseWebAudio = true;
  34303. }
  34304. }
  34305. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34306. get: function () {
  34307. if (!this._audioContextInitialized) {
  34308. this._initializeAudioContext();
  34309. }
  34310. return this._audioContext;
  34311. },
  34312. enumerable: true,
  34313. configurable: true
  34314. });
  34315. AudioEngine.prototype._initializeAudioContext = function () {
  34316. try {
  34317. if (this.canUseWebAudio) {
  34318. this._audioContext = new AudioContext();
  34319. // create a global volume gain node
  34320. this.masterGain = this._audioContext.createGain();
  34321. this.masterGain.gain.value = 1;
  34322. this.masterGain.connect(this._audioContext.destination);
  34323. this._audioContextInitialized = true;
  34324. }
  34325. }
  34326. catch (e) {
  34327. this.canUseWebAudio = false;
  34328. BABYLON.Tools.Error("Web Audio: " + e.message);
  34329. }
  34330. };
  34331. AudioEngine.prototype.dispose = function () {
  34332. if (this.canUseWebAudio && this._audioContextInitialized) {
  34333. if (this._connectedAnalyser) {
  34334. this._connectedAnalyser.stopDebugCanvas();
  34335. this._connectedAnalyser.dispose();
  34336. this.masterGain.disconnect();
  34337. this.masterGain.connect(this._audioContext.destination);
  34338. this._connectedAnalyser = null;
  34339. }
  34340. this.masterGain.gain.value = 1;
  34341. }
  34342. this.WarnedWebAudioUnsupported = false;
  34343. };
  34344. AudioEngine.prototype.getGlobalVolume = function () {
  34345. if (this.canUseWebAudio && this._audioContextInitialized) {
  34346. return this.masterGain.gain.value;
  34347. }
  34348. else {
  34349. return -1;
  34350. }
  34351. };
  34352. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34353. if (this.canUseWebAudio && this._audioContextInitialized) {
  34354. this.masterGain.gain.value = newVolume;
  34355. }
  34356. };
  34357. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34358. if (this._connectedAnalyser) {
  34359. this._connectedAnalyser.stopDebugCanvas();
  34360. }
  34361. if (this.canUseWebAudio && this._audioContextInitialized) {
  34362. this._connectedAnalyser = analyser;
  34363. this.masterGain.disconnect();
  34364. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34365. }
  34366. };
  34367. return AudioEngine;
  34368. })();
  34369. BABYLON.AudioEngine = AudioEngine;
  34370. })(BABYLON || (BABYLON = {}));
  34371. var BABYLON;
  34372. (function (BABYLON) {
  34373. var Sound = (function () {
  34374. /**
  34375. * Create a sound and attach it to a scene
  34376. * @param name Name of your sound
  34377. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34378. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34379. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34380. */
  34381. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34382. var _this = this;
  34383. this.autoplay = false;
  34384. this.loop = false;
  34385. this.useCustomAttenuation = false;
  34386. this.spatialSound = false;
  34387. this.refDistance = 1;
  34388. this.rolloffFactor = 1;
  34389. this.maxDistance = 100;
  34390. this.distanceModel = "linear";
  34391. this._panningModel = "equalpower";
  34392. this._playbackRate = 1;
  34393. this._streaming = false;
  34394. this._startTime = 0;
  34395. this._startOffset = 0;
  34396. this._position = BABYLON.Vector3.Zero();
  34397. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34398. this._volume = 1;
  34399. this._isLoaded = false;
  34400. this._isReadyToPlay = false;
  34401. this.isPlaying = false;
  34402. this.isPaused = false;
  34403. this._isDirectional = false;
  34404. // Used if you'd like to create a directional sound.
  34405. // If not set, the sound will be omnidirectional
  34406. this._coneInnerAngle = 360;
  34407. this._coneOuterAngle = 360;
  34408. this._coneOuterGain = 0;
  34409. this._isOutputConnected = false;
  34410. this.name = name;
  34411. this._scene = scene;
  34412. this._readyToPlayCallback = readyToPlayCallback;
  34413. // Default custom attenuation function is a linear attenuation
  34414. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34415. if (currentDistance < maxDistance) {
  34416. return currentVolume * (1 - currentDistance / maxDistance);
  34417. }
  34418. else {
  34419. return 0;
  34420. }
  34421. };
  34422. if (options) {
  34423. this.autoplay = options.autoplay || false;
  34424. this.loop = options.loop || false;
  34425. // if volume === 0, we need another way to check this option
  34426. if (options.volume !== undefined) {
  34427. this._volume = options.volume;
  34428. }
  34429. this.spatialSound = options.spatialSound || false;
  34430. this.maxDistance = options.maxDistance || 100;
  34431. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34432. this.rolloffFactor = options.rolloffFactor || 1;
  34433. this.refDistance = options.refDistance || 1;
  34434. this.distanceModel = options.distanceModel || "linear";
  34435. this._playbackRate = options.playbackRate || 1;
  34436. this._streaming = options.streaming || false;
  34437. }
  34438. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34439. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34440. this._soundGain.gain.value = this._volume;
  34441. this._inputAudioNode = this._soundGain;
  34442. this._ouputAudioNode = this._soundGain;
  34443. if (this.spatialSound) {
  34444. this._createSpatialParameters();
  34445. }
  34446. this._scene.mainSoundTrack.AddSound(this);
  34447. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34448. if (urlOrArrayBuffer) {
  34449. // If it's an URL
  34450. if (typeof (urlOrArrayBuffer) === "string") {
  34451. // Loading sound using XHR2
  34452. if (!this._streaming) {
  34453. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  34454. }
  34455. else {
  34456. this._htmlAudioElement = new Audio();
  34457. this._htmlAudioElement.src = urlOrArrayBuffer;
  34458. this._htmlAudioElement.controls = false;
  34459. this._htmlAudioElement.loop = this.loop;
  34460. this._htmlAudioElement.crossOrigin = "anonymous";
  34461. this._isReadyToPlay = true;
  34462. document.body.appendChild(this._htmlAudioElement);
  34463. // Simulating a ready to play event for consistent behavior with non streamed audio source
  34464. if (this._readyToPlayCallback) {
  34465. window.setTimeout(function () {
  34466. _this._readyToPlayCallback();
  34467. }, 1000);
  34468. }
  34469. if (this.autoplay) {
  34470. this.play();
  34471. }
  34472. }
  34473. }
  34474. else {
  34475. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34476. if (urlOrArrayBuffer.byteLength > 0) {
  34477. this._soundLoaded(urlOrArrayBuffer);
  34478. }
  34479. }
  34480. else {
  34481. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34482. }
  34483. }
  34484. }
  34485. }
  34486. else {
  34487. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34488. this._scene.mainSoundTrack.AddSound(this);
  34489. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34490. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34491. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34492. }
  34493. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34494. if (this._readyToPlayCallback) {
  34495. window.setTimeout(function () {
  34496. _this._readyToPlayCallback();
  34497. }, 1000);
  34498. }
  34499. }
  34500. }
  34501. Sound.prototype.dispose = function () {
  34502. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34503. if (this.isPlaying) {
  34504. this.stop();
  34505. }
  34506. this._isReadyToPlay = false;
  34507. if (this.soundTrackId === -1) {
  34508. this._scene.mainSoundTrack.RemoveSound(this);
  34509. }
  34510. else {
  34511. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34512. }
  34513. if (this._soundGain) {
  34514. this._soundGain.disconnect();
  34515. this._soundGain = null;
  34516. }
  34517. if (this._soundPanner) {
  34518. this._soundPanner.disconnect();
  34519. this._soundPanner = null;
  34520. }
  34521. if (this._soundSource) {
  34522. this._soundSource.disconnect();
  34523. this._soundSource = null;
  34524. }
  34525. this._audioBuffer = null;
  34526. if (this._htmlAudioElement) {
  34527. this._htmlAudioElement.pause();
  34528. this._htmlAudioElement.src = "";
  34529. document.body.removeChild(this._htmlAudioElement);
  34530. }
  34531. if (this._connectedMesh) {
  34532. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34533. this._connectedMesh = null;
  34534. }
  34535. }
  34536. };
  34537. Sound.prototype._soundLoaded = function (audioData) {
  34538. var _this = this;
  34539. this._isLoaded = true;
  34540. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34541. _this._audioBuffer = buffer;
  34542. _this._isReadyToPlay = true;
  34543. if (_this.autoplay) {
  34544. _this.play();
  34545. }
  34546. if (_this._readyToPlayCallback) {
  34547. _this._readyToPlayCallback();
  34548. }
  34549. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34550. };
  34551. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34552. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34553. this._audioBuffer = audioBuffer;
  34554. this._isReadyToPlay = true;
  34555. }
  34556. };
  34557. Sound.prototype.updateOptions = function (options) {
  34558. if (options) {
  34559. this.loop = options.loop || this.loop;
  34560. this.maxDistance = options.maxDistance || this.maxDistance;
  34561. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34562. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34563. this.refDistance = options.refDistance || this.refDistance;
  34564. this.distanceModel = options.distanceModel || this.distanceModel;
  34565. this._playbackRate = options.playbackRate || this._playbackRate;
  34566. this._updateSpatialParameters();
  34567. if (this.isPlaying) {
  34568. if (this._streaming) {
  34569. this._htmlAudioElement.playbackRate = this._playbackRate;
  34570. }
  34571. else {
  34572. this._soundSource.playbackRate.value = this._playbackRate;
  34573. }
  34574. }
  34575. }
  34576. };
  34577. Sound.prototype._createSpatialParameters = function () {
  34578. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34579. if (this._scene.headphone) {
  34580. this._panningModel = "HRTF";
  34581. }
  34582. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34583. this._updateSpatialParameters();
  34584. this._soundPanner.connect(this._ouputAudioNode);
  34585. this._inputAudioNode = this._soundPanner;
  34586. }
  34587. };
  34588. Sound.prototype._updateSpatialParameters = function () {
  34589. if (this.spatialSound) {
  34590. if (this.useCustomAttenuation) {
  34591. // Tricks to disable in a way embedded Web Audio attenuation
  34592. this._soundPanner.distanceModel = "linear";
  34593. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34594. this._soundPanner.refDistance = 1;
  34595. this._soundPanner.rolloffFactor = 1;
  34596. this._soundPanner.panningModel = this._panningModel;
  34597. }
  34598. else {
  34599. this._soundPanner.distanceModel = this.distanceModel;
  34600. this._soundPanner.maxDistance = this.maxDistance;
  34601. this._soundPanner.refDistance = this.refDistance;
  34602. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34603. this._soundPanner.panningModel = this._panningModel;
  34604. }
  34605. }
  34606. };
  34607. Sound.prototype.switchPanningModelToHRTF = function () {
  34608. this._panningModel = "HRTF";
  34609. this._switchPanningModel();
  34610. };
  34611. Sound.prototype.switchPanningModelToEqualPower = function () {
  34612. this._panningModel = "equalpower";
  34613. this._switchPanningModel();
  34614. };
  34615. Sound.prototype._switchPanningModel = function () {
  34616. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34617. this._soundPanner.panningModel = this._panningModel;
  34618. }
  34619. };
  34620. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34621. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34622. if (this._isOutputConnected) {
  34623. this._ouputAudioNode.disconnect();
  34624. }
  34625. this._ouputAudioNode.connect(soundTrackAudioNode);
  34626. this._isOutputConnected = true;
  34627. }
  34628. };
  34629. /**
  34630. * Transform this sound into a directional source
  34631. * @param coneInnerAngle Size of the inner cone in degree
  34632. * @param coneOuterAngle Size of the outer cone in degree
  34633. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34634. */
  34635. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34636. if (coneOuterAngle < coneInnerAngle) {
  34637. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34638. return;
  34639. }
  34640. this._coneInnerAngle = coneInnerAngle;
  34641. this._coneOuterAngle = coneOuterAngle;
  34642. this._coneOuterGain = coneOuterGain;
  34643. this._isDirectional = true;
  34644. if (this.isPlaying && this.loop) {
  34645. this.stop();
  34646. this.play();
  34647. }
  34648. };
  34649. Sound.prototype.setPosition = function (newPosition) {
  34650. this._position = newPosition;
  34651. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34652. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34653. }
  34654. };
  34655. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34656. this._localDirection = newLocalDirection;
  34657. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34658. this._updateDirection();
  34659. }
  34660. };
  34661. Sound.prototype._updateDirection = function () {
  34662. var mat = this._connectedMesh.getWorldMatrix();
  34663. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34664. direction.normalize();
  34665. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34666. };
  34667. Sound.prototype.updateDistanceFromListener = function () {
  34668. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34669. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34670. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34671. }
  34672. };
  34673. Sound.prototype.setAttenuationFunction = function (callback) {
  34674. this._customAttenuationFunction = callback;
  34675. };
  34676. /**
  34677. * Play the sound
  34678. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34679. */
  34680. Sound.prototype.play = function (time) {
  34681. var _this = this;
  34682. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34683. try {
  34684. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34685. if (!this._soundSource || !this._streamingSource) {
  34686. if (this.spatialSound) {
  34687. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34688. if (this._isDirectional) {
  34689. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34690. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34691. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34692. if (this._connectedMesh) {
  34693. this._updateDirection();
  34694. }
  34695. else {
  34696. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34697. }
  34698. }
  34699. }
  34700. }
  34701. if (this._streaming) {
  34702. if (!this._streamingSource) {
  34703. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34704. this._htmlAudioElement.onended = function () { _this._onended(); };
  34705. this._htmlAudioElement.playbackRate = this._playbackRate;
  34706. }
  34707. this._streamingSource.disconnect();
  34708. this._streamingSource.connect(this._inputAudioNode);
  34709. this._htmlAudioElement.play();
  34710. }
  34711. else {
  34712. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34713. this._soundSource.buffer = this._audioBuffer;
  34714. this._soundSource.connect(this._inputAudioNode);
  34715. this._soundSource.loop = this.loop;
  34716. this._soundSource.playbackRate.value = this._playbackRate;
  34717. this._soundSource.onended = function () { _this._onended(); };
  34718. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34719. }
  34720. this._startTime = startTime;
  34721. this.isPlaying = true;
  34722. this.isPaused = false;
  34723. }
  34724. catch (ex) {
  34725. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34726. }
  34727. }
  34728. };
  34729. Sound.prototype._onended = function () {
  34730. this.isPlaying = false;
  34731. if (this.onended) {
  34732. this.onended();
  34733. }
  34734. };
  34735. /**
  34736. * Stop the sound
  34737. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34738. */
  34739. Sound.prototype.stop = function (time) {
  34740. if (this.isPlaying) {
  34741. if (this._streaming) {
  34742. this._htmlAudioElement.pause();
  34743. // Test needed for Firefox or it will generate an Invalid State Error
  34744. if (this._htmlAudioElement.currentTime > 0) {
  34745. this._htmlAudioElement.currentTime = 0;
  34746. }
  34747. }
  34748. else {
  34749. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34750. this._soundSource.stop(stopTime);
  34751. }
  34752. this.isPlaying = false;
  34753. }
  34754. };
  34755. Sound.prototype.pause = function () {
  34756. if (this.isPlaying) {
  34757. if (this._streaming) {
  34758. this._htmlAudioElement.pause();
  34759. }
  34760. else {
  34761. this.stop(0);
  34762. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34763. }
  34764. this.isPaused = true;
  34765. }
  34766. };
  34767. Sound.prototype.setVolume = function (newVolume, time) {
  34768. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34769. if (time) {
  34770. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34771. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34772. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34773. }
  34774. else {
  34775. this._soundGain.gain.value = newVolume;
  34776. }
  34777. }
  34778. this._volume = newVolume;
  34779. };
  34780. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34781. this._playbackRate = newPlaybackRate;
  34782. if (this.isPlaying) {
  34783. if (this._streaming) {
  34784. this._htmlAudioElement.playbackRate = this._playbackRate;
  34785. }
  34786. else {
  34787. this._soundSource.playbackRate.value = this._playbackRate;
  34788. }
  34789. }
  34790. };
  34791. Sound.prototype.getVolume = function () {
  34792. return this._volume;
  34793. };
  34794. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34795. var _this = this;
  34796. if (this._connectedMesh) {
  34797. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34798. this._registerFunc = null;
  34799. }
  34800. this._connectedMesh = meshToConnectTo;
  34801. if (!this.spatialSound) {
  34802. this.spatialSound = true;
  34803. this._createSpatialParameters();
  34804. if (this.isPlaying && this.loop) {
  34805. this.stop();
  34806. this.play();
  34807. }
  34808. }
  34809. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34810. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34811. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34812. };
  34813. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34814. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34815. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34816. this._updateDirection();
  34817. }
  34818. };
  34819. Sound.prototype.clone = function () {
  34820. var _this = this;
  34821. if (!this._streaming) {
  34822. var setBufferAndRun = function () {
  34823. if (_this._isReadyToPlay) {
  34824. clonedSound._audioBuffer = _this.getAudioBuffer();
  34825. clonedSound._isReadyToPlay = true;
  34826. if (clonedSound.autoplay) {
  34827. clonedSound.play();
  34828. }
  34829. }
  34830. else {
  34831. window.setTimeout(setBufferAndRun, 300);
  34832. }
  34833. };
  34834. var currentOptions = {
  34835. autoplay: this.autoplay, loop: this.loop,
  34836. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34837. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34838. refDistance: this.refDistance, distanceModel: this.distanceModel
  34839. };
  34840. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34841. if (this.useCustomAttenuation) {
  34842. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34843. }
  34844. clonedSound.setPosition(this._position);
  34845. clonedSound.setPlaybackRate(this._playbackRate);
  34846. setBufferAndRun();
  34847. return clonedSound;
  34848. }
  34849. else {
  34850. return null;
  34851. }
  34852. };
  34853. Sound.prototype.getAudioBuffer = function () {
  34854. return this._audioBuffer;
  34855. };
  34856. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34857. var soundName = parsedSound.name;
  34858. var soundUrl;
  34859. if (parsedSound.url) {
  34860. soundUrl = rootUrl + parsedSound.url;
  34861. }
  34862. else {
  34863. soundUrl = rootUrl + soundName;
  34864. }
  34865. var options = {
  34866. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34867. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34868. rolloffFactor: parsedSound.rolloffFactor,
  34869. refDistance: parsedSound.refDistance,
  34870. distanceModel: parsedSound.distanceModel,
  34871. playbackRate: parsedSound.playbackRate
  34872. };
  34873. var newSound;
  34874. if (!sourceSound) {
  34875. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34876. scene._addPendingData(newSound);
  34877. }
  34878. else {
  34879. var setBufferAndRun = function () {
  34880. if (sourceSound._isReadyToPlay) {
  34881. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34882. newSound._isReadyToPlay = true;
  34883. if (newSound.autoplay) {
  34884. newSound.play();
  34885. }
  34886. }
  34887. else {
  34888. window.setTimeout(setBufferAndRun, 300);
  34889. }
  34890. };
  34891. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34892. setBufferAndRun();
  34893. }
  34894. if (parsedSound.position) {
  34895. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34896. newSound.setPosition(soundPosition);
  34897. }
  34898. if (parsedSound.isDirectional) {
  34899. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34900. if (parsedSound.localDirectionToMesh) {
  34901. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34902. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34903. }
  34904. }
  34905. if (parsedSound.connectedMeshId) {
  34906. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34907. if (connectedMesh) {
  34908. newSound.attachToMesh(connectedMesh);
  34909. }
  34910. }
  34911. return newSound;
  34912. };
  34913. return Sound;
  34914. })();
  34915. BABYLON.Sound = Sound;
  34916. })(BABYLON || (BABYLON = {}));
  34917. var BABYLON;
  34918. (function (BABYLON) {
  34919. var SoundTrack = (function () {
  34920. function SoundTrack(scene, options) {
  34921. this.id = -1;
  34922. this._isMainTrack = false;
  34923. this._isInitialized = false;
  34924. this._scene = scene;
  34925. this.soundCollection = new Array();
  34926. this._options = options;
  34927. if (!this._isMainTrack) {
  34928. this._scene.soundTracks.push(this);
  34929. this.id = this._scene.soundTracks.length - 1;
  34930. }
  34931. }
  34932. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34933. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34934. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34935. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34936. if (this._options) {
  34937. if (this._options.volume) {
  34938. this._outputAudioNode.gain.value = this._options.volume;
  34939. }
  34940. if (this._options.mainTrack) {
  34941. this._isMainTrack = this._options.mainTrack;
  34942. }
  34943. }
  34944. this._isInitialized = true;
  34945. }
  34946. };
  34947. SoundTrack.prototype.dispose = function () {
  34948. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34949. if (this._connectedAnalyser) {
  34950. this._connectedAnalyser.stopDebugCanvas();
  34951. }
  34952. while (this.soundCollection.length) {
  34953. this.soundCollection[0].dispose();
  34954. }
  34955. if (this._outputAudioNode) {
  34956. this._outputAudioNode.disconnect();
  34957. }
  34958. this._outputAudioNode = null;
  34959. }
  34960. };
  34961. SoundTrack.prototype.AddSound = function (sound) {
  34962. if (!this._isInitialized) {
  34963. this._initializeSoundTrackAudioGraph();
  34964. }
  34965. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34966. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34967. }
  34968. if (sound.soundTrackId) {
  34969. if (sound.soundTrackId === -1) {
  34970. this._scene.mainSoundTrack.RemoveSound(sound);
  34971. }
  34972. else {
  34973. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34974. }
  34975. }
  34976. this.soundCollection.push(sound);
  34977. sound.soundTrackId = this.id;
  34978. };
  34979. SoundTrack.prototype.RemoveSound = function (sound) {
  34980. var index = this.soundCollection.indexOf(sound);
  34981. if (index !== -1) {
  34982. this.soundCollection.splice(index, 1);
  34983. }
  34984. };
  34985. SoundTrack.prototype.setVolume = function (newVolume) {
  34986. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34987. this._outputAudioNode.gain.value = newVolume;
  34988. }
  34989. };
  34990. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34991. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34992. for (var i = 0; i < this.soundCollection.length; i++) {
  34993. this.soundCollection[i].switchPanningModelToHRTF();
  34994. }
  34995. }
  34996. };
  34997. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34998. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34999. for (var i = 0; i < this.soundCollection.length; i++) {
  35000. this.soundCollection[i].switchPanningModelToEqualPower();
  35001. }
  35002. }
  35003. };
  35004. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35005. if (this._connectedAnalyser) {
  35006. this._connectedAnalyser.stopDebugCanvas();
  35007. }
  35008. this._connectedAnalyser = analyser;
  35009. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35010. this._outputAudioNode.disconnect();
  35011. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35012. }
  35013. };
  35014. return SoundTrack;
  35015. })();
  35016. BABYLON.SoundTrack = SoundTrack;
  35017. })(BABYLON || (BABYLON = {}));
  35018. var BABYLON;
  35019. (function (BABYLON) {
  35020. var DepthRenderer = (function () {
  35021. function DepthRenderer(scene, type) {
  35022. var _this = this;
  35023. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35024. this._viewMatrix = BABYLON.Matrix.Zero();
  35025. this._projectionMatrix = BABYLON.Matrix.Zero();
  35026. this._transformMatrix = BABYLON.Matrix.Zero();
  35027. this._worldViewProjection = BABYLON.Matrix.Zero();
  35028. this._scene = scene;
  35029. var engine = scene.getEngine();
  35030. // Render target
  35031. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35032. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35033. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35034. this._depthMap.refreshRate = 1;
  35035. this._depthMap.renderParticles = false;
  35036. this._depthMap.renderList = null;
  35037. // set default depth value to 1.0 (far away)
  35038. this._depthMap.onClear = function (engine) {
  35039. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35040. };
  35041. // Custom render function
  35042. var renderSubMesh = function (subMesh) {
  35043. var mesh = subMesh.getRenderingMesh();
  35044. var scene = _this._scene;
  35045. var engine = scene.getEngine();
  35046. // Culling
  35047. engine.setState(subMesh.getMaterial().backFaceCulling);
  35048. // Managing instances
  35049. var batch = mesh._getInstancesRenderList(subMesh._id);
  35050. if (batch.mustReturn) {
  35051. return;
  35052. }
  35053. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35054. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35055. engine.enableEffect(_this._effect);
  35056. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35057. var material = subMesh.getMaterial();
  35058. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35059. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35060. // Alpha test
  35061. if (material && material.needAlphaTesting()) {
  35062. var alphaTexture = material.getAlphaTestTexture();
  35063. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35064. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35065. }
  35066. // Bones
  35067. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35068. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35069. }
  35070. // Draw
  35071. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35072. }
  35073. };
  35074. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35075. var index;
  35076. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35077. renderSubMesh(opaqueSubMeshes.data[index]);
  35078. }
  35079. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35080. renderSubMesh(alphaTestSubMeshes.data[index]);
  35081. }
  35082. };
  35083. }
  35084. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35085. var defines = [];
  35086. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35087. var mesh = subMesh.getMesh();
  35088. var scene = mesh.getScene();
  35089. var material = subMesh.getMaterial();
  35090. // Alpha test
  35091. if (material && material.needAlphaTesting()) {
  35092. defines.push("#define ALPHATEST");
  35093. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35094. attribs.push(BABYLON.VertexBuffer.UVKind);
  35095. defines.push("#define UV1");
  35096. }
  35097. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35098. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35099. defines.push("#define UV2");
  35100. }
  35101. }
  35102. // Bones
  35103. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35104. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35105. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35106. if (mesh.numBoneInfluencers > 4) {
  35107. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35108. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35109. }
  35110. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35111. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35112. }
  35113. else {
  35114. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35115. }
  35116. // Instances
  35117. if (useInstances) {
  35118. defines.push("#define INSTANCES");
  35119. attribs.push("world0");
  35120. attribs.push("world1");
  35121. attribs.push("world2");
  35122. attribs.push("world3");
  35123. }
  35124. // Get correct effect
  35125. var join = defines.join("\n");
  35126. if (this._cachedDefines !== join) {
  35127. this._cachedDefines = join;
  35128. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35129. }
  35130. return this._effect.isReady();
  35131. };
  35132. DepthRenderer.prototype.getDepthMap = function () {
  35133. return this._depthMap;
  35134. };
  35135. // Methods
  35136. DepthRenderer.prototype.dispose = function () {
  35137. this._depthMap.dispose();
  35138. };
  35139. return DepthRenderer;
  35140. })();
  35141. BABYLON.DepthRenderer = DepthRenderer;
  35142. })(BABYLON || (BABYLON = {}));
  35143. var BABYLON;
  35144. (function (BABYLON) {
  35145. var SSAORenderingPipeline = (function (_super) {
  35146. __extends(SSAORenderingPipeline, _super);
  35147. /**
  35148. * @constructor
  35149. * @param {string} name - The rendering pipeline name
  35150. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35151. * @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 }
  35152. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35153. */
  35154. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35155. var _this = this;
  35156. _super.call(this, scene.getEngine(), name);
  35157. // Members
  35158. /**
  35159. * The PassPostProcess id in the pipeline that contains the original scene color
  35160. * @type {string}
  35161. */
  35162. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35163. /**
  35164. * The SSAO PostProcess id in the pipeline
  35165. * @type {string}
  35166. */
  35167. this.SSAORenderEffect = "SSAORenderEffect";
  35168. /**
  35169. * The horizontal blur PostProcess id in the pipeline
  35170. * @type {string}
  35171. */
  35172. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35173. /**
  35174. * The vertical blur PostProcess id in the pipeline
  35175. * @type {string}
  35176. */
  35177. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35178. /**
  35179. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35180. * @type {string}
  35181. */
  35182. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35183. /**
  35184. * The output strength of the SSAO post-process. Default value is 1.0.
  35185. * @type {number}
  35186. */
  35187. this.totalStrength = 1.0;
  35188. /**
  35189. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35190. * @type {number}
  35191. */
  35192. this.radius = 0.0001;
  35193. /**
  35194. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35195. * Must not be equal to fallOff and superior to fallOff.
  35196. * Default value is 0.975
  35197. * @type {number}
  35198. */
  35199. this.area = 0.0075;
  35200. /**
  35201. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35202. * Must not be equal to area and inferior to area.
  35203. * Default value is 0.0
  35204. * @type {number}
  35205. */
  35206. this.fallOff = 0.000001;
  35207. /**
  35208. * The base color of the SSAO post-process
  35209. * The final result is "base + ssao" between [0, 1]
  35210. * @type {number}
  35211. */
  35212. this.base = 0.5;
  35213. this._firstUpdate = true;
  35214. this._scene = scene;
  35215. // Set up assets
  35216. this._createRandomTexture();
  35217. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35218. var ssaoRatio = ratio.ssaoRatio || ratio;
  35219. var combineRatio = ratio.combineRatio || ratio;
  35220. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35221. this._createSSAOPostProcess(ssaoRatio);
  35222. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35223. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35224. this._createSSAOCombinePostProcess(combineRatio);
  35225. // Set up pipeline
  35226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35227. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35231. // Finish
  35232. scene.postProcessRenderPipelineManager.addPipeline(this);
  35233. if (cameras)
  35234. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35235. }
  35236. // Public Methods
  35237. /**
  35238. * Returns the horizontal blur PostProcess
  35239. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35240. */
  35241. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35242. return this._blurHPostProcess;
  35243. };
  35244. /**
  35245. * Returns the vertical blur PostProcess
  35246. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35247. */
  35248. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35249. return this._blurVPostProcess;
  35250. };
  35251. /**
  35252. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35253. */
  35254. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35255. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35256. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35257. this._originalColorPostProcess = undefined;
  35258. this._ssaoPostProcess = undefined;
  35259. this._blurHPostProcess = undefined;
  35260. this._blurVPostProcess = undefined;
  35261. this._ssaoCombinePostProcess = undefined;
  35262. this._randomTexture.dispose();
  35263. if (disableDepthRender)
  35264. this._scene.disableDepthRenderer();
  35265. };
  35266. // Private Methods
  35267. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35268. var _this = this;
  35269. var numSamples = 16;
  35270. var sampleSphere = [
  35271. 0.5381, 0.1856, -0.4319,
  35272. 0.1379, 0.2486, 0.4430,
  35273. 0.3371, 0.5679, -0.0057,
  35274. -0.6999, -0.0451, -0.0019,
  35275. 0.0689, -0.1598, -0.8547,
  35276. 0.0560, 0.0069, -0.1843,
  35277. -0.0146, 0.1402, 0.0762,
  35278. 0.0100, -0.1924, -0.0344,
  35279. -0.3577, -0.5301, -0.4358,
  35280. -0.3169, 0.1063, 0.0158,
  35281. 0.0103, -0.5869, 0.0046,
  35282. -0.0897, -0.4940, 0.3287,
  35283. 0.7119, -0.0154, -0.0918,
  35284. -0.0533, 0.0596, -0.5411,
  35285. 0.0352, -0.0631, 0.5460,
  35286. -0.4776, 0.2847, -0.0271
  35287. ];
  35288. var samplesFactor = 1.0 / numSamples;
  35289. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35290. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35291. "area", "fallOff", "base"
  35292. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35293. this._ssaoPostProcess.onApply = function (effect) {
  35294. if (_this._firstUpdate) {
  35295. effect.setArray3("sampleSphere", sampleSphere);
  35296. effect.setFloat("samplesFactor", samplesFactor);
  35297. effect.setFloat("randTextureTiles", 4.0);
  35298. _this._firstUpdate = false;
  35299. }
  35300. effect.setFloat("totalStrength", _this.totalStrength);
  35301. effect.setFloat("radius", _this.radius);
  35302. effect.setFloat("area", _this.area);
  35303. effect.setFloat("fallOff", _this.fallOff);
  35304. effect.setFloat("base", _this.base);
  35305. effect.setTexture("textureSampler", _this._depthTexture);
  35306. effect.setTexture("randomSampler", _this._randomTexture);
  35307. };
  35308. };
  35309. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35310. var _this = this;
  35311. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35312. this._ssaoCombinePostProcess.onApply = function (effect) {
  35313. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35314. };
  35315. };
  35316. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35317. var size = 512;
  35318. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35319. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35320. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35321. var context = this._randomTexture.getContext();
  35322. var rand = function (min, max) {
  35323. return Math.random() * (max - min) + min;
  35324. };
  35325. var randVector = BABYLON.Vector3.Zero();
  35326. for (var x = 0; x < size; x++) {
  35327. for (var y = 0; y < size; y++) {
  35328. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35329. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35330. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35331. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35332. context.fillRect(x, y, 1, 1);
  35333. }
  35334. }
  35335. this._randomTexture.update(false);
  35336. };
  35337. return SSAORenderingPipeline;
  35338. })(BABYLON.PostProcessRenderPipeline);
  35339. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35340. })(BABYLON || (BABYLON = {}));
  35341. var BABYLON;
  35342. (function (BABYLON) {
  35343. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35344. var VolumetricLightScatteringPostProcess = (function (_super) {
  35345. __extends(VolumetricLightScatteringPostProcess, _super);
  35346. /**
  35347. * @constructor
  35348. * @param {string} name - The post-process name
  35349. * @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)
  35350. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35351. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35352. * @param {number} samples - The post-process quality, default 100
  35353. * @param {number} samplingMode - The post-process filtering mode
  35354. * @param {BABYLON.Engine} engine - The babylon engine
  35355. * @param {boolean} reusable - If the post-process is reusable
  35356. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35357. */
  35358. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35359. var _this = this;
  35360. if (samples === void 0) { samples = 100; }
  35361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35362. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35363. this._screenCoordinates = BABYLON.Vector2.Zero();
  35364. /**
  35365. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35366. * @type {boolean}
  35367. */
  35368. this.useCustomMeshPosition = false;
  35369. /**
  35370. * If the post-process should inverse the light scattering direction
  35371. * @type {boolean}
  35372. */
  35373. this.invert = true;
  35374. /**
  35375. * Set to true to use the diffuseColor instead of the diffuseTexture
  35376. * @type {boolean}
  35377. */
  35378. this.useDiffuseColor = false;
  35379. /**
  35380. * Array containing the excluded meshes not rendered in the internal pass
  35381. */
  35382. this.excludedMeshes = new Array();
  35383. /**
  35384. * Controls the overall intensity of the post-process
  35385. * @type {number}
  35386. */
  35387. this.exposure = 0.3;
  35388. /**
  35389. * Dissipates each sample's contribution in range [0, 1]
  35390. * @type {number}
  35391. */
  35392. this.decay = 0.96815;
  35393. /**
  35394. * Controls the overall intensity of each sample
  35395. * @type {number}
  35396. */
  35397. this.weight = 0.58767;
  35398. /**
  35399. * Controls the density of each sample
  35400. * @type {number}
  35401. */
  35402. this.density = 0.926;
  35403. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35404. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35405. // Configure mesh
  35406. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35407. // Configure
  35408. this._createPass(scene, ratio.passRatio || ratio);
  35409. this.onActivate = function (camera) {
  35410. if (!_this.isSupported) {
  35411. _this.dispose(camera);
  35412. }
  35413. _this.onActivate = null;
  35414. };
  35415. this.onApply = function (effect) {
  35416. _this._updateMeshScreenCoordinates(scene);
  35417. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35418. effect.setFloat("exposure", _this.exposure);
  35419. effect.setFloat("decay", _this.decay);
  35420. effect.setFloat("weight", _this.weight);
  35421. effect.setFloat("density", _this.density);
  35422. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35423. };
  35424. }
  35425. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35426. var mesh = subMesh.getMesh();
  35427. var defines = [];
  35428. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35429. var material = subMesh.getMaterial();
  35430. var needUV = false;
  35431. // Render this.mesh as default
  35432. if (mesh === this.mesh) {
  35433. if (this.useDiffuseColor) {
  35434. defines.push("#define DIFFUSE_COLOR_RENDER");
  35435. }
  35436. else if (material) {
  35437. if (material.diffuseTexture !== undefined) {
  35438. defines.push("#define BASIC_RENDER");
  35439. }
  35440. else {
  35441. defines.push("#define DIFFUSE_COLOR_RENDER");
  35442. }
  35443. }
  35444. defines.push("#define NEED_UV");
  35445. needUV = true;
  35446. }
  35447. // Alpha test
  35448. if (material) {
  35449. if (material.needAlphaTesting()) {
  35450. defines.push("#define ALPHATEST");
  35451. }
  35452. if (material.opacityTexture !== undefined) {
  35453. defines.push("#define OPACITY");
  35454. if (material.opacityTexture.getAlphaFromRGB) {
  35455. defines.push("#define OPACITYRGB");
  35456. }
  35457. if (!needUV) {
  35458. defines.push("#define NEED_UV");
  35459. }
  35460. }
  35461. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35462. attribs.push(BABYLON.VertexBuffer.UVKind);
  35463. defines.push("#define UV1");
  35464. }
  35465. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35466. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35467. defines.push("#define UV2");
  35468. }
  35469. }
  35470. // Bones
  35471. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35472. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35473. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35474. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35475. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35476. }
  35477. else {
  35478. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35479. }
  35480. // Instances
  35481. if (useInstances) {
  35482. defines.push("#define INSTANCES");
  35483. attribs.push("world0");
  35484. attribs.push("world1");
  35485. attribs.push("world2");
  35486. attribs.push("world3");
  35487. }
  35488. // Get correct effect
  35489. var join = defines.join("\n");
  35490. if (this._cachedDefines !== join) {
  35491. this._cachedDefines = join;
  35492. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35493. }
  35494. return this._volumetricLightScatteringPass.isReady();
  35495. };
  35496. /**
  35497. * Sets the new light position for light scattering effect
  35498. * @param {BABYLON.Vector3} The new custom light position
  35499. */
  35500. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35501. this._customMeshPosition = position;
  35502. };
  35503. /**
  35504. * Returns the light position for light scattering effect
  35505. * @return {BABYLON.Vector3} The custom light position
  35506. */
  35507. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35508. return this._customMeshPosition;
  35509. };
  35510. /**
  35511. * Disposes the internal assets and detaches the post-process from the camera
  35512. */
  35513. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35514. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35515. if (rttIndex !== -1) {
  35516. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35517. }
  35518. this._volumetricLightScatteringRTT.dispose();
  35519. _super.prototype.dispose.call(this, camera);
  35520. };
  35521. /**
  35522. * Returns the render target texture used by the post-process
  35523. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35524. */
  35525. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35526. return this._volumetricLightScatteringRTT;
  35527. };
  35528. // Private methods
  35529. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35530. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35531. return true;
  35532. }
  35533. return false;
  35534. };
  35535. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35536. var _this = this;
  35537. var engine = scene.getEngine();
  35538. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35539. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35540. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35541. this._volumetricLightScatteringRTT.renderList = null;
  35542. this._volumetricLightScatteringRTT.renderParticles = false;
  35543. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35544. // Custom render function for submeshes
  35545. var renderSubMesh = function (subMesh) {
  35546. var mesh = subMesh.getRenderingMesh();
  35547. if (_this._meshExcluded(mesh)) {
  35548. return;
  35549. }
  35550. var scene = mesh.getScene();
  35551. var engine = scene.getEngine();
  35552. // Culling
  35553. engine.setState(subMesh.getMaterial().backFaceCulling);
  35554. // Managing instances
  35555. var batch = mesh._getInstancesRenderList(subMesh._id);
  35556. if (batch.mustReturn) {
  35557. return;
  35558. }
  35559. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35560. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35561. engine.enableEffect(_this._volumetricLightScatteringPass);
  35562. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35563. var material = subMesh.getMaterial();
  35564. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35565. // Alpha test
  35566. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35567. var alphaTexture = material.getAlphaTestTexture();
  35568. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35569. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35570. }
  35571. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35572. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35573. if (alphaTexture) {
  35574. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35575. }
  35576. }
  35577. if (material.opacityTexture !== undefined) {
  35578. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35579. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35580. }
  35581. }
  35582. // Bones
  35583. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35584. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35585. }
  35586. // Draw
  35587. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35588. }
  35589. };
  35590. // Render target texture callbacks
  35591. var savedSceneClearColor;
  35592. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35593. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35594. savedSceneClearColor = scene.clearColor;
  35595. scene.clearColor = sceneClearColor;
  35596. };
  35597. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35598. scene.clearColor = savedSceneClearColor;
  35599. };
  35600. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35601. var engine = scene.getEngine();
  35602. var index;
  35603. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35604. renderSubMesh(opaqueSubMeshes.data[index]);
  35605. }
  35606. engine.setAlphaTesting(true);
  35607. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35608. renderSubMesh(alphaTestSubMeshes.data[index]);
  35609. }
  35610. engine.setAlphaTesting(false);
  35611. if (transparentSubMeshes.length) {
  35612. // Sort sub meshes
  35613. for (index = 0; index < transparentSubMeshes.length; index++) {
  35614. var submesh = transparentSubMeshes.data[index];
  35615. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35616. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35617. }
  35618. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35619. sortedArray.sort(function (a, b) {
  35620. // Alpha index first
  35621. if (a._alphaIndex > b._alphaIndex) {
  35622. return 1;
  35623. }
  35624. if (a._alphaIndex < b._alphaIndex) {
  35625. return -1;
  35626. }
  35627. // Then distance to camera
  35628. if (a._distanceToCamera < b._distanceToCamera) {
  35629. return 1;
  35630. }
  35631. if (a._distanceToCamera > b._distanceToCamera) {
  35632. return -1;
  35633. }
  35634. return 0;
  35635. });
  35636. // Render sub meshes
  35637. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35638. for (index = 0; index < sortedArray.length; index++) {
  35639. renderSubMesh(sortedArray[index]);
  35640. }
  35641. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35642. }
  35643. };
  35644. };
  35645. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35646. var transform = scene.getTransformMatrix();
  35647. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35648. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35649. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35650. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35651. if (this.invert)
  35652. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35653. };
  35654. // Static methods
  35655. /**
  35656. * Creates a default mesh for the Volumeric Light Scattering post-process
  35657. * @param {string} The mesh name
  35658. * @param {BABYLON.Scene} The scene where to create the mesh
  35659. * @return {BABYLON.Mesh} the default mesh
  35660. */
  35661. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35662. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35663. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35664. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35665. return mesh;
  35666. };
  35667. return VolumetricLightScatteringPostProcess;
  35668. })(BABYLON.PostProcess);
  35669. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35670. })(BABYLON || (BABYLON = {}));
  35671. // BABYLON.JS Chromatic Aberration GLSL Shader
  35672. // Author: Olivier Guyot
  35673. // Separates very slightly R, G and B colors on the edges of the screen
  35674. // Inspired by Francois Tarlier & Martins Upitis
  35675. var BABYLON;
  35676. (function (BABYLON) {
  35677. var LensRenderingPipeline = (function (_super) {
  35678. __extends(LensRenderingPipeline, _super);
  35679. /**
  35680. * @constructor
  35681. *
  35682. * Effect parameters are as follow:
  35683. * {
  35684. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35685. * edge_blur: number; // from 0 to x (1 for realism)
  35686. * distortion: number; // from 0 to x (1 for realism)
  35687. * grain_amount: number; // from 0 to 1
  35688. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35689. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35690. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35691. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35692. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35693. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35694. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35695. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35696. * }
  35697. * Note: if an effect parameter is unset, effect is disabled
  35698. *
  35699. * @param {string} name - The rendering pipeline name
  35700. * @param {object} parameters - An object containing all parameters (see above)
  35701. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35702. * @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)
  35703. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35704. */
  35705. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35706. var _this = this;
  35707. if (ratio === void 0) { ratio = 1.0; }
  35708. _super.call(this, scene.getEngine(), name);
  35709. // Lens effects can be of the following:
  35710. // - chromatic aberration (slight shift of RGB colors)
  35711. // - blur on the edge of the lens
  35712. // - lens distortion
  35713. // - depth-of-field blur & highlights enhancing
  35714. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35715. // - grain effect (noise or custom texture)
  35716. // Two additional texture samplers are needed:
  35717. // - depth map (for depth-of-field)
  35718. // - grain texture
  35719. /**
  35720. * The chromatic aberration PostProcess id in the pipeline
  35721. * @type {string}
  35722. */
  35723. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35724. /**
  35725. * The highlights enhancing PostProcess id in the pipeline
  35726. * @type {string}
  35727. */
  35728. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35729. /**
  35730. * The depth-of-field PostProcess id in the pipeline
  35731. * @type {string}
  35732. */
  35733. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35734. this._scene = scene;
  35735. // Fetch texture samplers
  35736. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35737. if (parameters.grain_texture) {
  35738. this._grainTexture = parameters.grain_texture;
  35739. }
  35740. else {
  35741. this._createGrainTexture();
  35742. }
  35743. // save parameters
  35744. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35745. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35746. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35747. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35748. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35749. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35750. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35751. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35752. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35753. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35754. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35755. // Create effects
  35756. this._createChromaticAberrationPostProcess(ratio);
  35757. this._createHighlightsPostProcess(ratio);
  35758. this._createDepthOfFieldPostProcess(ratio / 4);
  35759. // Set up pipeline
  35760. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35761. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35763. if (this._highlightsGain === -1) {
  35764. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35765. }
  35766. // Finish
  35767. scene.postProcessRenderPipelineManager.addPipeline(this);
  35768. if (cameras) {
  35769. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35770. }
  35771. }
  35772. // public methods (self explanatory)
  35773. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35774. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35775. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35776. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35777. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35778. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35779. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35780. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35781. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35782. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35783. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35784. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35785. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35786. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35787. };
  35788. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35789. this._highlightsPostProcess.updateEffect();
  35790. };
  35791. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35792. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35793. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35794. this._highlightsGain = amount;
  35795. };
  35796. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35797. if (this._highlightsGain === -1) {
  35798. this._highlightsGain = 1.0;
  35799. }
  35800. this._highlightsThreshold = amount;
  35801. };
  35802. LensRenderingPipeline.prototype.disableHighlights = function () {
  35803. this._highlightsGain = -1;
  35804. };
  35805. /**
  35806. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35807. */
  35808. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35809. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35810. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35811. this._chromaticAberrationPostProcess = undefined;
  35812. this._highlightsPostProcess = undefined;
  35813. this._depthOfFieldPostProcess = undefined;
  35814. this._grainTexture.dispose();
  35815. if (disableDepthRender)
  35816. this._scene.disableDepthRenderer();
  35817. };
  35818. // colors shifting and distortion
  35819. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35820. var _this = this;
  35821. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35822. [], // samplers
  35823. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35824. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35825. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35826. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35827. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35828. };
  35829. };
  35830. // highlights enhancing
  35831. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35832. var _this = this;
  35833. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35834. [], // samplers
  35835. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35836. this._highlightsPostProcess.onApply = function (effect) {
  35837. effect.setFloat('gain', _this._highlightsGain);
  35838. effect.setFloat('threshold', _this._highlightsThreshold);
  35839. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35840. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35841. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35842. };
  35843. };
  35844. // colors shifting and distortion
  35845. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35846. var _this = this;
  35847. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35848. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35849. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35850. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35851. this._depthOfFieldPostProcess.onApply = function (effect) {
  35852. effect.setTexture("depthSampler", _this._depthTexture);
  35853. effect.setTexture("grainSampler", _this._grainTexture);
  35854. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35855. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35856. effect.setFloat('grain_amount', _this._grainAmount);
  35857. effect.setBool('blur_noise', _this._blurNoise);
  35858. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35859. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35860. effect.setFloat('distortion', _this._distortion);
  35861. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35862. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35863. effect.setFloat('aperture', _this._dofAperture);
  35864. effect.setFloat('darken', _this._dofDarken);
  35865. effect.setFloat('edge_blur', _this._edgeBlur);
  35866. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35867. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35868. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35869. };
  35870. };
  35871. // creates a black and white random noise texture, 512x512
  35872. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35873. var size = 512;
  35874. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35875. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35876. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35877. var context = this._grainTexture.getContext();
  35878. var rand = function (min, max) {
  35879. return Math.random() * (max - min) + min;
  35880. };
  35881. var value;
  35882. for (var x = 0; x < size; x++) {
  35883. for (var y = 0; y < size; y++) {
  35884. value = Math.floor(rand(0.42, 0.58) * 255);
  35885. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35886. context.fillRect(x, y, 1, 1);
  35887. }
  35888. }
  35889. this._grainTexture.update(false);
  35890. };
  35891. return LensRenderingPipeline;
  35892. })(BABYLON.PostProcessRenderPipeline);
  35893. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35894. })(BABYLON || (BABYLON = {}));
  35895. //
  35896. // This post-process allows the modification of rendered colors by using
  35897. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35898. //
  35899. // The object needs to be provided an url to a texture containing the color
  35900. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35901. // Use an image editing software to tweak the LUT to match your needs.
  35902. //
  35903. // For an example of a color LUT, see here:
  35904. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35905. // For explanations on color grading, see here:
  35906. // http://udn.epicgames.com/Three/ColorGrading.html
  35907. //
  35908. var BABYLON;
  35909. (function (BABYLON) {
  35910. var ColorCorrectionPostProcess = (function (_super) {
  35911. __extends(ColorCorrectionPostProcess, _super);
  35912. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35913. var _this = this;
  35914. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35915. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35916. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35917. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35918. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35919. this.onApply = function (effect) {
  35920. effect.setTexture("colorTable", _this._colorTableTexture);
  35921. };
  35922. }
  35923. return ColorCorrectionPostProcess;
  35924. })(BABYLON.PostProcess);
  35925. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35926. })(BABYLON || (BABYLON = {}));
  35927. var BABYLON;
  35928. (function (BABYLON) {
  35929. var AnaglyphFreeCamera = (function (_super) {
  35930. __extends(AnaglyphFreeCamera, _super);
  35931. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35932. _super.call(this, name, position, scene);
  35933. this.interaxialDistance = interaxialDistance;
  35934. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35935. }
  35936. return AnaglyphFreeCamera;
  35937. })(BABYLON.FreeCamera);
  35938. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35939. var AnaglyphArcRotateCamera = (function (_super) {
  35940. __extends(AnaglyphArcRotateCamera, _super);
  35941. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35942. _super.call(this, name, alpha, beta, radius, target, scene);
  35943. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35944. }
  35945. return AnaglyphArcRotateCamera;
  35946. })(BABYLON.ArcRotateCamera);
  35947. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35948. var AnaglyphGamepadCamera = (function (_super) {
  35949. __extends(AnaglyphGamepadCamera, _super);
  35950. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35951. _super.call(this, name, position, scene);
  35952. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35953. }
  35954. return AnaglyphGamepadCamera;
  35955. })(BABYLON.GamepadCamera);
  35956. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35957. var StereoscopicFreeCamera = (function (_super) {
  35958. __extends(StereoscopicFreeCamera, _super);
  35959. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35960. _super.call(this, name, position, scene);
  35961. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35962. }
  35963. return StereoscopicFreeCamera;
  35964. })(BABYLON.FreeCamera);
  35965. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35966. var StereoscopicArcRotateCamera = (function (_super) {
  35967. __extends(StereoscopicArcRotateCamera, _super);
  35968. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35969. _super.call(this, name, alpha, beta, radius, target, scene);
  35970. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35971. }
  35972. return StereoscopicArcRotateCamera;
  35973. })(BABYLON.ArcRotateCamera);
  35974. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35975. var StereoscopicGamepadCamera = (function (_super) {
  35976. __extends(StereoscopicGamepadCamera, _super);
  35977. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35978. _super.call(this, name, position, scene);
  35979. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35980. }
  35981. return StereoscopicGamepadCamera;
  35982. })(BABYLON.GamepadCamera);
  35983. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35984. })(BABYLON || (BABYLON = {}));
  35985. var BABYLON;
  35986. (function (BABYLON) {
  35987. var HDRRenderingPipeline = (function (_super) {
  35988. __extends(HDRRenderingPipeline, _super);
  35989. /**
  35990. * @constructor
  35991. * @param {string} name - The rendering pipeline name
  35992. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35993. * @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)
  35994. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35995. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35996. */
  35997. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35998. var _this = this;
  35999. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36000. _super.call(this, scene.getEngine(), name);
  36001. /**
  36002. * Public members
  36003. */
  36004. // Gaussian Blur
  36005. /**
  36006. * Gaussian blur coefficient
  36007. * @type {number}
  36008. */
  36009. this.gaussCoeff = 0.3;
  36010. /**
  36011. * Gaussian blur mean
  36012. * @type {number}
  36013. */
  36014. this.gaussMean = 1.0;
  36015. /**
  36016. * Gaussian blur standard deviation
  36017. * @type {number}
  36018. */
  36019. this.gaussStandDev = 0.8;
  36020. /**
  36021. * Gaussian blur multiplier. Multiplies the blur effect
  36022. * @type {number}
  36023. */
  36024. this.gaussMultiplier = 4.0;
  36025. // HDR
  36026. /**
  36027. * Exposure, controls the overall intensity of the pipeline
  36028. * @type {number}
  36029. */
  36030. this.exposure = 1.0;
  36031. /**
  36032. * Minimum luminance that the post-process can output. Luminance is >= 0
  36033. * @type {number}
  36034. */
  36035. this.minimumLuminance = 1.0;
  36036. /**
  36037. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36038. * @type {number}
  36039. */
  36040. this.maximumLuminance = 1e20;
  36041. /**
  36042. * Increase rate for luminance: eye adaptation speed to dark
  36043. * @type {number}
  36044. */
  36045. this.luminanceIncreaserate = 0.5;
  36046. /**
  36047. * Decrease rate for luminance: eye adaptation speed to bright
  36048. * @type {number}
  36049. */
  36050. this.luminanceDecreaseRate = 0.5;
  36051. // Bright pass
  36052. /**
  36053. * Minimum luminance needed to compute HDR
  36054. * @type {number}
  36055. */
  36056. this.brightThreshold = 0.8;
  36057. this._needUpdate = true;
  36058. this._scene = scene;
  36059. // Bright pass
  36060. this._createBrightPassPostProcess(scene, ratio);
  36061. // Down sample X4
  36062. this._createDownSampleX4PostProcess(scene, ratio);
  36063. // Create gaussian blur post-processes
  36064. this._createGaussianBlurPostProcess(scene, ratio);
  36065. // Texture adder
  36066. this._createTextureAdderPostProcess(scene, ratio);
  36067. // Luminance generator
  36068. this._createLuminanceGeneratorPostProcess(scene);
  36069. // HDR
  36070. this._createHDRPostProcess(scene, ratio);
  36071. // Pass postprocess
  36072. if (originalPostProcess === null) {
  36073. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36074. }
  36075. else {
  36076. this._originalPostProcess = originalPostProcess;
  36077. }
  36078. // Configure pipeline
  36079. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36085. var addDownSamplerPostProcess = function (id) {
  36086. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36087. };
  36088. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36089. addDownSamplerPostProcess(i);
  36090. }
  36091. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36092. // Finish
  36093. scene.postProcessRenderPipelineManager.addPipeline(this);
  36094. if (cameras !== null) {
  36095. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36096. }
  36097. this.update();
  36098. }
  36099. /**
  36100. * Tells the pipeline to update its post-processes
  36101. */
  36102. HDRRenderingPipeline.prototype.update = function () {
  36103. this._needUpdate = true;
  36104. };
  36105. /**
  36106. * Returns the current calculated luminance
  36107. */
  36108. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36109. return this._hdrCurrentLuminance;
  36110. };
  36111. /**
  36112. * Returns the currently drawn luminance
  36113. */
  36114. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36115. return this._hdrOutputLuminance;
  36116. };
  36117. /**
  36118. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36119. */
  36120. HDRRenderingPipeline.prototype.dispose = function () {
  36121. this._originalPostProcess = undefined;
  36122. this._brightPassPostProcess = undefined;
  36123. this._downSampleX4PostProcess = undefined;
  36124. this._guassianBlurHPostProcess = undefined;
  36125. this._guassianBlurVPostProcess = undefined;
  36126. this._textureAdderPostProcess = undefined;
  36127. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36128. this._downSamplePostProcesses[i] = undefined;
  36129. }
  36130. this._hdrPostProcess = undefined;
  36131. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36132. };
  36133. /**
  36134. * Creates the HDR post-process and computes the luminance adaptation
  36135. */
  36136. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36137. var _this = this;
  36138. var hdrLastLuminance = 0.0;
  36139. this._hdrOutputLuminance = -1.0;
  36140. this._hdrCurrentLuminance = 1.0;
  36141. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36142. this._hdrPostProcess.onApply = function (effect) {
  36143. if (_this._hdrOutputLuminance < 0.0) {
  36144. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36145. }
  36146. else {
  36147. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36148. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36149. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36150. }
  36151. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36152. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36153. }
  36154. else {
  36155. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36156. }
  36157. }
  36158. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36159. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36160. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36161. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36162. effect.setFloat("exposure", _this.exposure);
  36163. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36164. _this._needUpdate = false;
  36165. };
  36166. };
  36167. /**
  36168. * Texture Adder post-process
  36169. */
  36170. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36171. var _this = this;
  36172. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36173. this._textureAdderPostProcess.onApply = function (effect) {
  36174. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36175. };
  36176. };
  36177. /**
  36178. * Down sample X4 post-process
  36179. */
  36180. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36181. var _this = this;
  36182. var downSampleX4Offsets = new Array(32);
  36183. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36184. this._downSampleX4PostProcess.onApply = function (effect) {
  36185. if (_this._needUpdate) {
  36186. var id = 0;
  36187. for (var i = -2; i < 2; i++) {
  36188. for (var j = -2; j < 2; j++) {
  36189. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36190. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36191. id += 2;
  36192. }
  36193. }
  36194. }
  36195. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36196. };
  36197. };
  36198. /**
  36199. * Bright pass post-process
  36200. */
  36201. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36202. var _this = this;
  36203. var brightOffsets = new Array(8);
  36204. var brightPassCallback = function (effect) {
  36205. if (_this._needUpdate) {
  36206. var sU = (1.0 / _this._brightPassPostProcess.width);
  36207. var sV = (1.0 / _this._brightPassPostProcess.height);
  36208. brightOffsets[0] = -0.5 * sU;
  36209. brightOffsets[1] = 0.5 * sV;
  36210. brightOffsets[2] = 0.5 * sU;
  36211. brightOffsets[3] = 0.5 * sV;
  36212. brightOffsets[4] = -0.5 * sU;
  36213. brightOffsets[5] = -0.5 * sV;
  36214. brightOffsets[6] = 0.5 * sU;
  36215. brightOffsets[7] = -0.5 * sV;
  36216. }
  36217. effect.setArray2("dsOffsets", brightOffsets);
  36218. effect.setFloat("brightThreshold", _this.brightThreshold);
  36219. };
  36220. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36221. this._brightPassPostProcess.onApply = brightPassCallback;
  36222. };
  36223. /**
  36224. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36225. */
  36226. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36227. var _this = this;
  36228. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36229. var luminanceOffsets = new Array(8);
  36230. var downSampleOffsets = new Array(18);
  36231. var halfDestPixelSize;
  36232. this._downSamplePostProcesses = new Array(lumSteps);
  36233. // Utils for luminance
  36234. var luminanceUpdateSourceOffsets = function (width, height) {
  36235. var sU = (1.0 / width);
  36236. var sV = (1.0 / height);
  36237. luminanceOffsets[0] = -0.5 * sU;
  36238. luminanceOffsets[1] = 0.5 * sV;
  36239. luminanceOffsets[2] = 0.5 * sU;
  36240. luminanceOffsets[3] = 0.5 * sV;
  36241. luminanceOffsets[4] = -0.5 * sU;
  36242. luminanceOffsets[5] = -0.5 * sV;
  36243. luminanceOffsets[6] = 0.5 * sU;
  36244. luminanceOffsets[7] = -0.5 * sV;
  36245. };
  36246. var luminanceUpdateDestOffsets = function (width, height) {
  36247. var id = 0;
  36248. for (var x = -1; x < 2; x++) {
  36249. for (var y = -1; y < 2; y++) {
  36250. downSampleOffsets[id] = (x) / width;
  36251. downSampleOffsets[id + 1] = (y) / height;
  36252. id += 2;
  36253. }
  36254. }
  36255. };
  36256. // Luminance callback
  36257. var luminanceCallback = function (effect) {
  36258. if (_this._needUpdate) {
  36259. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36260. }
  36261. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36262. effect.setArray2("lumOffsets", luminanceOffsets);
  36263. };
  36264. // Down sample callbacks
  36265. var downSampleCallback = function (indice) {
  36266. var i = indice;
  36267. return function (effect) {
  36268. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36269. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36270. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36271. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36272. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36273. effect.setArray2("dsOffsets", downSampleOffsets);
  36274. };
  36275. };
  36276. var downSampleAfterRenderCallback = function (effect) {
  36277. // Unpack result
  36278. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36279. 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);
  36280. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36281. };
  36282. // Create luminance post-process
  36283. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36284. 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);
  36285. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36286. // Create down sample post-processes
  36287. for (var i = lumSteps - 2; i >= 0; i--) {
  36288. var length = Math.pow(3, i);
  36289. ratio = { width: length, height: length };
  36290. var defines = "#define DOWN_SAMPLE\n";
  36291. if (i === 0) {
  36292. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36293. }
  36294. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36295. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36296. if (i === 0) {
  36297. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36298. }
  36299. }
  36300. };
  36301. /**
  36302. * Gaussian blur post-processes. Horizontal and Vertical
  36303. */
  36304. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36305. var _this = this;
  36306. var blurOffsetsW = new Array(9);
  36307. var blurOffsetsH = new Array(9);
  36308. var blurWeights = new Array(9);
  36309. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36310. // Utils for gaussian blur
  36311. var calculateBlurOffsets = function (height) {
  36312. var lastOutputDimensions = {
  36313. width: scene.getEngine().getRenderWidth(),
  36314. height: scene.getEngine().getRenderHeight()
  36315. };
  36316. for (var i = 0; i < 9; i++) {
  36317. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36318. if (height) {
  36319. blurOffsetsH[i] = value;
  36320. }
  36321. else {
  36322. blurOffsetsW[i] = value;
  36323. }
  36324. }
  36325. };
  36326. var calculateWeights = function () {
  36327. var x = 0.0;
  36328. for (var i = 0; i < 9; i++) {
  36329. x = (i - 4.0) / 4.0;
  36330. 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));
  36331. }
  36332. };
  36333. // Callback
  36334. var gaussianBlurCallback = function (height) {
  36335. return function (effect) {
  36336. if (_this._needUpdate) {
  36337. calculateWeights();
  36338. calculateBlurOffsets(height);
  36339. }
  36340. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36341. effect.setArray("blurWeights", blurWeights);
  36342. effect.setFloat("multiplier", _this.gaussMultiplier);
  36343. };
  36344. };
  36345. // Create horizontal gaussian blur post-processes
  36346. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36347. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36348. // Create vertical gaussian blur post-process
  36349. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36350. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36351. };
  36352. // Luminance generator
  36353. HDRRenderingPipeline.LUM_STEPS = 6;
  36354. return HDRRenderingPipeline;
  36355. })(BABYLON.PostProcessRenderPipeline);
  36356. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36357. })(BABYLON || (BABYLON = {}));
  36358. var BABYLON;
  36359. (function (BABYLON) {
  36360. var FaceAdjacencies = (function () {
  36361. function FaceAdjacencies() {
  36362. this.edges = new Array();
  36363. this.edgesConnectedCount = 0;
  36364. }
  36365. return FaceAdjacencies;
  36366. })();
  36367. var EdgesRenderer = (function () {
  36368. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36369. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36370. if (epsilon === void 0) { epsilon = 0.95; }
  36371. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36372. this.edgesWidthScalerForOrthographic = 1000.0;
  36373. this.edgesWidthScalerForPerspective = 50.0;
  36374. this._linesPositions = new Array();
  36375. this._linesNormals = new Array();
  36376. this._linesIndices = new Array();
  36377. this._buffers = new Array();
  36378. this._checkVerticesInsteadOfIndices = false;
  36379. this._source = source;
  36380. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36381. this._epsilon = epsilon;
  36382. this._prepareRessources();
  36383. this._generateEdgesLines();
  36384. }
  36385. EdgesRenderer.prototype._prepareRessources = function () {
  36386. if (this._lineShader) {
  36387. return;
  36388. }
  36389. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36390. attributes: ["position", "normal"],
  36391. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36392. });
  36393. this._lineShader.disableDepthWrite = true;
  36394. this._lineShader.backFaceCulling = false;
  36395. };
  36396. EdgesRenderer.prototype.dispose = function () {
  36397. this._vb0.dispose();
  36398. this._vb1.dispose();
  36399. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36400. this._lineShader.dispose();
  36401. };
  36402. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36403. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36404. return 0;
  36405. }
  36406. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36407. return 1;
  36408. }
  36409. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36410. return 2;
  36411. }
  36412. return -1;
  36413. };
  36414. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36415. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36416. return 0;
  36417. }
  36418. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36419. return 1;
  36420. }
  36421. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36422. return 2;
  36423. }
  36424. return -1;
  36425. };
  36426. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36427. var needToCreateLine;
  36428. if (edge === undefined) {
  36429. needToCreateLine = true;
  36430. }
  36431. else {
  36432. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36433. needToCreateLine = dotProduct < this._epsilon;
  36434. }
  36435. if (needToCreateLine) {
  36436. var offset = this._linesPositions.length / 3;
  36437. var normal = p0.subtract(p1);
  36438. normal.normalize();
  36439. // Positions
  36440. this._linesPositions.push(p0.x);
  36441. this._linesPositions.push(p0.y);
  36442. this._linesPositions.push(p0.z);
  36443. this._linesPositions.push(p0.x);
  36444. this._linesPositions.push(p0.y);
  36445. this._linesPositions.push(p0.z);
  36446. this._linesPositions.push(p1.x);
  36447. this._linesPositions.push(p1.y);
  36448. this._linesPositions.push(p1.z);
  36449. this._linesPositions.push(p1.x);
  36450. this._linesPositions.push(p1.y);
  36451. this._linesPositions.push(p1.z);
  36452. // Normals
  36453. this._linesNormals.push(p1.x);
  36454. this._linesNormals.push(p1.y);
  36455. this._linesNormals.push(p1.z);
  36456. this._linesNormals.push(-1);
  36457. this._linesNormals.push(p1.x);
  36458. this._linesNormals.push(p1.y);
  36459. this._linesNormals.push(p1.z);
  36460. this._linesNormals.push(1);
  36461. this._linesNormals.push(p0.x);
  36462. this._linesNormals.push(p0.y);
  36463. this._linesNormals.push(p0.z);
  36464. this._linesNormals.push(-1);
  36465. this._linesNormals.push(p0.x);
  36466. this._linesNormals.push(p0.y);
  36467. this._linesNormals.push(p0.z);
  36468. this._linesNormals.push(1);
  36469. // Indices
  36470. this._linesIndices.push(offset);
  36471. this._linesIndices.push(offset + 1);
  36472. this._linesIndices.push(offset + 2);
  36473. this._linesIndices.push(offset);
  36474. this._linesIndices.push(offset + 2);
  36475. this._linesIndices.push(offset + 3);
  36476. }
  36477. };
  36478. EdgesRenderer.prototype._generateEdgesLines = function () {
  36479. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36480. var indices = this._source.getIndices();
  36481. // First let's find adjacencies
  36482. var adjacencies = new Array();
  36483. var faceNormals = new Array();
  36484. var index;
  36485. var faceAdjacencies;
  36486. // Prepare faces
  36487. for (index = 0; index < indices.length; index += 3) {
  36488. faceAdjacencies = new FaceAdjacencies();
  36489. var p0Index = indices[index];
  36490. var p1Index = indices[index + 1];
  36491. var p2Index = indices[index + 2];
  36492. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36493. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36494. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36495. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36496. faceNormal.normalize();
  36497. faceNormals.push(faceNormal);
  36498. adjacencies.push(faceAdjacencies);
  36499. }
  36500. // Scan
  36501. for (index = 0; index < adjacencies.length; index++) {
  36502. faceAdjacencies = adjacencies[index];
  36503. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36504. var otherFaceAdjacencies = adjacencies[otherIndex];
  36505. if (faceAdjacencies.edgesConnectedCount === 3) {
  36506. break;
  36507. }
  36508. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36509. continue;
  36510. }
  36511. var otherP0 = indices[otherIndex * 3];
  36512. var otherP1 = indices[otherIndex * 3 + 1];
  36513. var otherP2 = indices[otherIndex * 3 + 2];
  36514. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36515. var otherEdgeIndex;
  36516. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36517. continue;
  36518. }
  36519. switch (edgeIndex) {
  36520. case 0:
  36521. if (this._checkVerticesInsteadOfIndices) {
  36522. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36523. }
  36524. else {
  36525. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36526. }
  36527. break;
  36528. case 1:
  36529. if (this._checkVerticesInsteadOfIndices) {
  36530. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36531. }
  36532. else {
  36533. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36534. }
  36535. break;
  36536. case 2:
  36537. if (this._checkVerticesInsteadOfIndices) {
  36538. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36539. }
  36540. else {
  36541. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36542. }
  36543. break;
  36544. }
  36545. if (otherEdgeIndex === -1) {
  36546. continue;
  36547. }
  36548. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36549. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36550. faceAdjacencies.edgesConnectedCount++;
  36551. otherFaceAdjacencies.edgesConnectedCount++;
  36552. if (faceAdjacencies.edgesConnectedCount === 3) {
  36553. break;
  36554. }
  36555. }
  36556. }
  36557. }
  36558. // Create lines
  36559. for (index = 0; index < adjacencies.length; index++) {
  36560. // 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
  36561. var current = adjacencies[index];
  36562. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36563. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36564. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36565. }
  36566. // Merge into a single mesh
  36567. var engine = this._source.getScene().getEngine();
  36568. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36569. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36570. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36571. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36572. this._ib = engine.createIndexBuffer(this._linesIndices);
  36573. this._indicesCount = this._linesIndices.length;
  36574. };
  36575. EdgesRenderer.prototype.render = function () {
  36576. if (!this._lineShader.isReady()) {
  36577. return;
  36578. }
  36579. var scene = this._source.getScene();
  36580. var engine = scene.getEngine();
  36581. this._lineShader._preBind();
  36582. // VBOs
  36583. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36584. scene.resetCachedMaterial();
  36585. this._lineShader.setColor4("color", this._source.edgesColor);
  36586. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36587. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36588. }
  36589. else {
  36590. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36591. }
  36592. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36593. this._lineShader.bind(this._source.getWorldMatrix());
  36594. // Draw order
  36595. engine.draw(true, 0, this._indicesCount);
  36596. this._lineShader.unbind();
  36597. engine.setDepthWrite(true);
  36598. };
  36599. return EdgesRenderer;
  36600. })();
  36601. BABYLON.EdgesRenderer = EdgesRenderer;
  36602. })(BABYLON || (BABYLON = {}));
  36603. var BABYLON;
  36604. (function (BABYLON) {
  36605. (function (TonemappingOperator) {
  36606. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36607. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36608. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36609. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36610. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36611. var TonemappingOperator = BABYLON.TonemappingOperator;
  36612. ;
  36613. var TonemapPostProcess = (function (_super) {
  36614. __extends(TonemapPostProcess, _super);
  36615. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36616. var _this = this;
  36617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36618. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36619. this._operator = operator;
  36620. this._exposureAdjustment = exposureAdjustment;
  36621. var params = ["_ExposureAdjustment"];
  36622. var defines = "#define ";
  36623. if (operator === TonemappingOperator.Hable)
  36624. defines += "HABLE_TONEMAPPING";
  36625. else if (operator === TonemappingOperator.Reinhard)
  36626. defines += "REINHARD_TONEMAPPING";
  36627. else if (operator === TonemappingOperator.HejiDawson)
  36628. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36629. else if (operator === TonemappingOperator.Photographic)
  36630. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36631. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36632. this.onApply = function (effect) {
  36633. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  36634. };
  36635. }
  36636. return TonemapPostProcess;
  36637. })(BABYLON.PostProcess);
  36638. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36639. })(BABYLON || (BABYLON = {}));
  36640. var BABYLON;
  36641. (function (BABYLON) {
  36642. var ReflectionProbe = (function () {
  36643. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36644. var _this = this;
  36645. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36646. this.name = name;
  36647. this._viewMatrix = BABYLON.Matrix.Identity();
  36648. this._target = BABYLON.Vector3.Zero();
  36649. this._add = BABYLON.Vector3.Zero();
  36650. this.position = BABYLON.Vector3.Zero();
  36651. this._scene = scene;
  36652. this._scene.reflectionProbes.push(this);
  36653. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36654. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36655. switch (faceIndex) {
  36656. case 0:
  36657. _this._add.copyFromFloats(1, 0, 0);
  36658. break;
  36659. case 1:
  36660. _this._add.copyFromFloats(-1, 0, 0);
  36661. break;
  36662. case 2:
  36663. _this._add.copyFromFloats(0, -1, 0);
  36664. break;
  36665. case 3:
  36666. _this._add.copyFromFloats(0, 1, 0);
  36667. break;
  36668. case 4:
  36669. _this._add.copyFromFloats(0, 0, 1);
  36670. break;
  36671. case 5:
  36672. _this._add.copyFromFloats(0, 0, -1);
  36673. break;
  36674. }
  36675. if (_this._attachedMesh) {
  36676. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36677. }
  36678. _this.position.addToRef(_this._add, _this._target);
  36679. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36680. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36681. };
  36682. this._renderTargetTexture.onAfterUnbind = function () {
  36683. scene.updateTransformMatrix(true);
  36684. };
  36685. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36686. }
  36687. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36688. get: function () {
  36689. return this._renderTargetTexture.refreshRate;
  36690. },
  36691. set: function (value) {
  36692. this._renderTargetTexture.refreshRate = value;
  36693. },
  36694. enumerable: true,
  36695. configurable: true
  36696. });
  36697. ReflectionProbe.prototype.getScene = function () {
  36698. return this._scene;
  36699. };
  36700. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36701. get: function () {
  36702. return this._renderTargetTexture;
  36703. },
  36704. enumerable: true,
  36705. configurable: true
  36706. });
  36707. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36708. get: function () {
  36709. return this._renderTargetTexture.renderList;
  36710. },
  36711. enumerable: true,
  36712. configurable: true
  36713. });
  36714. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36715. this._attachedMesh = mesh;
  36716. };
  36717. ReflectionProbe.prototype.dispose = function () {
  36718. var index = this._scene.reflectionProbes.indexOf(this);
  36719. if (index !== -1) {
  36720. // Remove from the scene if found
  36721. this._scene.reflectionProbes.splice(index, 1);
  36722. }
  36723. if (this._renderTargetTexture) {
  36724. this._renderTargetTexture.dispose();
  36725. this._renderTargetTexture = null;
  36726. }
  36727. };
  36728. return ReflectionProbe;
  36729. })();
  36730. BABYLON.ReflectionProbe = ReflectionProbe;
  36731. })(BABYLON || (BABYLON = {}));
  36732. var BABYLON;
  36733. (function (BABYLON) {
  36734. var SolidParticle = (function () {
  36735. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36736. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36737. this.position = BABYLON.Vector3.Zero(); // position
  36738. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36739. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36740. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36741. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36742. this.alive = true; // alive
  36743. this.idx = particleIndex;
  36744. this._pos = positionIndex;
  36745. this._model = model;
  36746. this.shapeId = shapeId;
  36747. this.idxInShape = idxInShape;
  36748. }
  36749. return SolidParticle;
  36750. })();
  36751. BABYLON.SolidParticle = SolidParticle;
  36752. var ModelShape = (function () {
  36753. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36754. this.shapeID = id;
  36755. this._shape = shape;
  36756. this._shapeUV = shapeUV;
  36757. this._positionFunction = posFunction;
  36758. this._vertexFunction = vtxFunction;
  36759. }
  36760. return ModelShape;
  36761. })();
  36762. BABYLON.ModelShape = ModelShape;
  36763. })(BABYLON || (BABYLON = {}));
  36764. var BABYLON;
  36765. (function (BABYLON) {
  36766. /**
  36767. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36768. */
  36769. var SolidParticleSystem = (function () {
  36770. /**
  36771. * Creates a SPS (Solid Particle System) object.
  36772. * @param name the SPS name, this will be the underlying mesh name
  36773. * @param updatable (default true) if the SPS must be updatable or immutable
  36774. * @param isPickable (default false) if the solid particles must be pickable
  36775. */
  36776. function SolidParticleSystem(name, scene, options) {
  36777. // public members
  36778. this.particles = new Array();
  36779. this.nbParticles = 0;
  36780. this.billboard = false;
  36781. this.counter = 0;
  36782. this.vars = {};
  36783. this._positions = new Array();
  36784. this._indices = new Array();
  36785. this._normals = new Array();
  36786. this._colors = new Array();
  36787. this._uvs = new Array();
  36788. this._index = 0; // indices index
  36789. this._updatable = true;
  36790. this._pickable = false;
  36791. this._alwaysVisible = false;
  36792. this._shapeCounter = 0;
  36793. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36794. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36795. this._computeParticleColor = true;
  36796. this._computeParticleTexture = true;
  36797. this._computeParticleRotation = true;
  36798. this._computeParticleVertex = false;
  36799. this._cam_axisZ = BABYLON.Vector3.Zero();
  36800. this._cam_axisY = BABYLON.Vector3.Zero();
  36801. this._cam_axisX = BABYLON.Vector3.Zero();
  36802. this._axisX = BABYLON.Axis.X;
  36803. this._axisY = BABYLON.Axis.Y;
  36804. this._axisZ = BABYLON.Axis.Z;
  36805. this._fakeCamPos = BABYLON.Vector3.Zero();
  36806. this._rotMatrix = new BABYLON.Matrix();
  36807. this._invertMatrix = new BABYLON.Matrix();
  36808. this._rotated = BABYLON.Vector3.Zero();
  36809. this._quaternion = new BABYLON.Quaternion();
  36810. this._vertex = BABYLON.Vector3.Zero();
  36811. this._normal = BABYLON.Vector3.Zero();
  36812. this._yaw = 0.0;
  36813. this._pitch = 0.0;
  36814. this._roll = 0.0;
  36815. this._halfroll = 0.0;
  36816. this._halfpitch = 0.0;
  36817. this._halfyaw = 0.0;
  36818. this._sinRoll = 0.0;
  36819. this._cosRoll = 0.0;
  36820. this._sinPitch = 0.0;
  36821. this._cosPitch = 0.0;
  36822. this._sinYaw = 0.0;
  36823. this._cosYaw = 0.0;
  36824. this._w = 0.0;
  36825. this.name = name;
  36826. this._scene = scene;
  36827. this._camera = scene.activeCamera;
  36828. this._pickable = options ? options.isPickable : false;
  36829. if (options && options.updatable) {
  36830. this._updatable = options.updatable;
  36831. }
  36832. else {
  36833. this._updatable = true;
  36834. }
  36835. if (this._pickable) {
  36836. this.pickedParticles = [];
  36837. }
  36838. }
  36839. /**
  36840. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36841. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36842. */
  36843. SolidParticleSystem.prototype.buildMesh = function () {
  36844. if (this.nbParticles === 0) {
  36845. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36846. this.addShape(triangle, 1);
  36847. triangle.dispose();
  36848. }
  36849. this._positions32 = new Float32Array(this._positions);
  36850. this._uvs32 = new Float32Array(this._uvs);
  36851. this._colors32 = new Float32Array(this._colors);
  36852. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36853. this._normals32 = new Float32Array(this._normals);
  36854. this._fixedNormal32 = new Float32Array(this._normals);
  36855. var vertexData = new BABYLON.VertexData();
  36856. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36857. vertexData.indices = this._indices;
  36858. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36859. if (this._uvs32) {
  36860. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36861. ;
  36862. }
  36863. if (this._colors32) {
  36864. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36865. }
  36866. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36867. vertexData.applyToMesh(mesh, this._updatable);
  36868. this.mesh = mesh;
  36869. this.mesh.isPickable = this._pickable;
  36870. // free memory
  36871. this._positions = null;
  36872. this._normals = null;
  36873. this._uvs = null;
  36874. this._colors = null;
  36875. if (!this._updatable) {
  36876. this.particles.length = 0;
  36877. }
  36878. return mesh;
  36879. };
  36880. //reset copy
  36881. SolidParticleSystem.prototype._resetCopy = function () {
  36882. this._copy.position.x = 0;
  36883. this._copy.position.y = 0;
  36884. this._copy.position.z = 0;
  36885. this._copy.rotation.x = 0;
  36886. this._copy.rotation.y = 0;
  36887. this._copy.rotation.z = 0;
  36888. this._copy.quaternion = null;
  36889. this._copy.scale.x = 1;
  36890. this._copy.scale.y = 1;
  36891. this._copy.scale.z = 1;
  36892. this._copy.uvs.x = 0;
  36893. this._copy.uvs.y = 0;
  36894. this._copy.uvs.z = 1;
  36895. this._copy.uvs.w = 1;
  36896. this._copy.color = null;
  36897. };
  36898. // _meshBuilder : inserts the shape model in the global SPS mesh
  36899. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36900. var i;
  36901. var u = 0;
  36902. var c = 0;
  36903. this._resetCopy();
  36904. if (options && options.positionFunction) {
  36905. options.positionFunction(this._copy, idx, idxInShape);
  36906. }
  36907. if (this._copy.quaternion) {
  36908. this._quaternion.x = this._copy.quaternion.x;
  36909. this._quaternion.y = this._copy.quaternion.y;
  36910. this._quaternion.z = this._copy.quaternion.z;
  36911. this._quaternion.w = this._copy.quaternion.w;
  36912. }
  36913. else {
  36914. this._yaw = this._copy.rotation.y;
  36915. this._pitch = this._copy.rotation.x;
  36916. this._roll = this._copy.rotation.z;
  36917. this._quaternionRotationYPR();
  36918. }
  36919. this._quaternionToRotationMatrix();
  36920. for (i = 0; i < shape.length; i++) {
  36921. this._vertex.x = shape[i].x;
  36922. this._vertex.y = shape[i].y;
  36923. this._vertex.z = shape[i].z;
  36924. if (options && options.vertexFunction) {
  36925. options.vertexFunction(this._copy, this._vertex, i);
  36926. }
  36927. this._vertex.x *= this._copy.scale.x;
  36928. this._vertex.y *= this._copy.scale.y;
  36929. this._vertex.z *= this._copy.scale.z;
  36930. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36931. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36932. if (meshUV) {
  36933. 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);
  36934. u += 2;
  36935. }
  36936. if (this._copy.color) {
  36937. this._color = this._copy.color;
  36938. }
  36939. else if (meshCol && meshCol[c]) {
  36940. this._color.r = meshCol[c];
  36941. this._color.g = meshCol[c + 1];
  36942. this._color.b = meshCol[c + 2];
  36943. this._color.a = meshCol[c + 3];
  36944. }
  36945. else {
  36946. this._color.r = 1;
  36947. this._color.g = 1;
  36948. this._color.b = 1;
  36949. this._color.a = 1;
  36950. }
  36951. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36952. c += 4;
  36953. }
  36954. for (i = 0; i < meshInd.length; i++) {
  36955. indices.push(p + meshInd[i]);
  36956. }
  36957. if (this._pickable) {
  36958. var nbfaces = meshInd.length / 3;
  36959. for (i = 0; i < nbfaces; i++) {
  36960. this.pickedParticles.push({ idx: idx, faceId: i });
  36961. }
  36962. }
  36963. };
  36964. // returns a shape array from positions array
  36965. SolidParticleSystem.prototype._posToShape = function (positions) {
  36966. var shape = [];
  36967. for (var i = 0; i < positions.length; i += 3) {
  36968. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36969. }
  36970. return shape;
  36971. };
  36972. // returns a shapeUV array from a Vector4 uvs
  36973. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36974. var shapeUV = [];
  36975. if (uvs) {
  36976. for (var i = 0; i < uvs.length; i++)
  36977. shapeUV.push(uvs[i]);
  36978. }
  36979. return shapeUV;
  36980. };
  36981. // adds a new particle object in the particles array
  36982. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36983. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36984. };
  36985. /**
  36986. * Adds some particles to the SPS from the model shape.
  36987. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  36988. * @param mesh any Mesh object that will be used as a model for the solid particles.
  36989. * @param nb the number of particles to be created from this model
  36990. * @param positionFunction an optional javascript function to called for each particle on SPS creation
  36991. * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  36992. */
  36993. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36994. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36995. var meshInd = mesh.getIndices();
  36996. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36997. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36998. var shape = this._posToShape(meshPos);
  36999. var shapeUV = this._uvsToShapeUV(meshUV);
  37000. var posfunc = options ? options.positionFunction : null;
  37001. var vtxfunc = options ? options.vertexFunction : null;
  37002. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37003. // particles
  37004. var idx = this.nbParticles;
  37005. for (var i = 0; i < nb; i++) {
  37006. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37007. if (this._updatable) {
  37008. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37009. }
  37010. this._index += shape.length;
  37011. idx++;
  37012. }
  37013. this.nbParticles += nb;
  37014. this._shapeCounter++;
  37015. return this._shapeCounter;
  37016. };
  37017. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37018. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37019. this._resetCopy();
  37020. if (particle._model._positionFunction) {
  37021. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37022. }
  37023. if (this._copy.quaternion) {
  37024. this._quaternion.x = this._copy.quaternion.x;
  37025. this._quaternion.y = this._copy.quaternion.y;
  37026. this._quaternion.z = this._copy.quaternion.z;
  37027. this._quaternion.w = this._copy.quaternion.w;
  37028. }
  37029. else {
  37030. this._yaw = this._copy.rotation.y;
  37031. this._pitch = this._copy.rotation.x;
  37032. this._roll = this._copy.rotation.z;
  37033. this._quaternionRotationYPR();
  37034. }
  37035. this._quaternionToRotationMatrix();
  37036. this._shape = particle._model._shape;
  37037. for (var pt = 0; pt < this._shape.length; pt++) {
  37038. this._vertex.x = this._shape[pt].x;
  37039. this._vertex.y = this._shape[pt].y;
  37040. this._vertex.z = this._shape[pt].z;
  37041. if (particle._model._vertexFunction) {
  37042. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37043. }
  37044. this._vertex.x *= this._copy.scale.x;
  37045. this._vertex.y *= this._copy.scale.y;
  37046. this._vertex.z *= this._copy.scale.z;
  37047. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37048. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37049. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37050. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37051. }
  37052. particle.position.x = 0;
  37053. particle.position.y = 0;
  37054. particle.position.z = 0;
  37055. particle.rotation.x = 0;
  37056. particle.rotation.y = 0;
  37057. particle.rotation.z = 0;
  37058. particle.quaternion = null;
  37059. particle.scale.x = 1;
  37060. particle.scale.y = 1;
  37061. particle.scale.z = 1;
  37062. };
  37063. /**
  37064. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37065. */
  37066. SolidParticleSystem.prototype.rebuildMesh = function () {
  37067. for (var p = 0; p < this.particles.length; p++) {
  37068. this._rebuildParticle(this.particles[p]);
  37069. }
  37070. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37071. };
  37072. /**
  37073. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37074. * This method calls updateParticle() for each particles of the SPS.
  37075. * For an animated SPS, it is usually called within the render loop.
  37076. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37077. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37078. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37079. */
  37080. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37081. if (start === void 0) { start = 0; }
  37082. if (end === void 0) { end = this.nbParticles - 1; }
  37083. if (update === void 0) { update = true; }
  37084. if (!this._updatable) {
  37085. return;
  37086. }
  37087. // custom beforeUpdate
  37088. this.beforeUpdateParticles(start, end, update);
  37089. this._cam_axisX.x = 1;
  37090. this._cam_axisX.y = 0;
  37091. this._cam_axisX.z = 0;
  37092. this._cam_axisY.x = 0;
  37093. this._cam_axisY.y = 1;
  37094. this._cam_axisY.z = 0;
  37095. this._cam_axisZ.x = 0;
  37096. this._cam_axisZ.y = 0;
  37097. this._cam_axisZ.z = 1;
  37098. // if the particles will always face the camera
  37099. if (this.billboard) {
  37100. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37101. this._yaw = this.mesh.rotation.y;
  37102. this._pitch = this.mesh.rotation.x;
  37103. this._roll = this.mesh.rotation.z;
  37104. this._quaternionRotationYPR();
  37105. this._quaternionToRotationMatrix();
  37106. this._rotMatrix.invertToRef(this._invertMatrix);
  37107. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37108. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37109. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37110. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37111. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37112. this._cam_axisY.normalize();
  37113. this._cam_axisX.normalize();
  37114. this._cam_axisZ.normalize();
  37115. }
  37116. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37117. var idx = 0;
  37118. var index = 0;
  37119. var colidx = 0;
  37120. var colorIndex = 0;
  37121. var uvidx = 0;
  37122. var uvIndex = 0;
  37123. // particle loop
  37124. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37125. for (var p = start; p <= end; p++) {
  37126. this._particle = this.particles[p];
  37127. this._shape = this._particle._model._shape;
  37128. this._shapeUV = this._particle._model._shapeUV;
  37129. // call to custom user function to update the particle properties
  37130. this.updateParticle(this._particle);
  37131. // particle rotation matrix
  37132. if (this.billboard) {
  37133. this._particle.rotation.x = 0.0;
  37134. this._particle.rotation.y = 0.0;
  37135. }
  37136. if (this._computeParticleRotation) {
  37137. if (this._particle.quaternion) {
  37138. this._quaternion.x = this._particle.quaternion.x;
  37139. this._quaternion.y = this._particle.quaternion.y;
  37140. this._quaternion.z = this._particle.quaternion.z;
  37141. this._quaternion.w = this._particle.quaternion.w;
  37142. }
  37143. else {
  37144. this._yaw = this._particle.rotation.y;
  37145. this._pitch = this._particle.rotation.x;
  37146. this._roll = this._particle.rotation.z;
  37147. this._quaternionRotationYPR();
  37148. }
  37149. this._quaternionToRotationMatrix();
  37150. }
  37151. for (var pt = 0; pt < this._shape.length; pt++) {
  37152. idx = index + pt * 3;
  37153. colidx = colorIndex + pt * 4;
  37154. uvidx = uvIndex + pt * 2;
  37155. this._vertex.x = this._shape[pt].x;
  37156. this._vertex.y = this._shape[pt].y;
  37157. this._vertex.z = this._shape[pt].z;
  37158. if (this._computeParticleVertex) {
  37159. this.updateParticleVertex(this._particle, this._vertex, pt);
  37160. }
  37161. // positions
  37162. this._vertex.x *= this._particle.scale.x;
  37163. this._vertex.y *= this._particle.scale.y;
  37164. this._vertex.z *= this._particle.scale.z;
  37165. 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];
  37166. 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;
  37167. 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;
  37168. 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;
  37169. 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;
  37170. 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;
  37171. 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;
  37172. // normals : if the particles can't be morphed then just rotate the normals
  37173. if (!this._computeParticleVertex && !this.billboard) {
  37174. this._normal.x = this._fixedNormal32[idx];
  37175. this._normal.y = this._fixedNormal32[idx + 1];
  37176. this._normal.z = this._fixedNormal32[idx + 2];
  37177. 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];
  37178. 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;
  37179. 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;
  37180. 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;
  37181. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37182. 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;
  37183. 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;
  37184. }
  37185. if (this._computeParticleColor) {
  37186. this._colors32[colidx] = this._particle.color.r;
  37187. this._colors32[colidx + 1] = this._particle.color.g;
  37188. this._colors32[colidx + 2] = this._particle.color.b;
  37189. this._colors32[colidx + 3] = this._particle.color.a;
  37190. }
  37191. if (this._computeParticleTexture) {
  37192. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37193. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37194. }
  37195. }
  37196. index = idx + 3;
  37197. colorIndex = colidx + 4;
  37198. uvIndex = uvidx + 2;
  37199. }
  37200. if (update) {
  37201. if (this._computeParticleColor) {
  37202. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37203. }
  37204. if (this._computeParticleTexture) {
  37205. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37206. }
  37207. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37208. if (!this.mesh.areNormalsFrozen) {
  37209. if (this._computeParticleVertex || this.billboard) {
  37210. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37211. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37212. for (var i = 0; i < this._normals32.length; i++) {
  37213. this._fixedNormal32[i] = this._normals32[i];
  37214. }
  37215. }
  37216. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37217. }
  37218. }
  37219. this.afterUpdateParticles(start, end, update);
  37220. };
  37221. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37222. this._halfroll = this._roll * 0.5;
  37223. this._halfpitch = this._pitch * 0.5;
  37224. this._halfyaw = this._yaw * 0.5;
  37225. this._sinRoll = Math.sin(this._halfroll);
  37226. this._cosRoll = Math.cos(this._halfroll);
  37227. this._sinPitch = Math.sin(this._halfpitch);
  37228. this._cosPitch = Math.cos(this._halfpitch);
  37229. this._sinYaw = Math.sin(this._halfyaw);
  37230. this._cosYaw = Math.cos(this._halfyaw);
  37231. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37232. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37233. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37234. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37235. };
  37236. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37237. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37238. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37239. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37240. this._rotMatrix.m[3] = 0;
  37241. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37242. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37243. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37244. this._rotMatrix.m[7] = 0;
  37245. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37246. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37247. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37248. this._rotMatrix.m[11] = 0;
  37249. this._rotMatrix.m[12] = 0;
  37250. this._rotMatrix.m[13] = 0;
  37251. this._rotMatrix.m[14] = 0;
  37252. this._rotMatrix.m[15] = 1.0;
  37253. };
  37254. /**
  37255. * Disposes the SPS
  37256. */
  37257. SolidParticleSystem.prototype.dispose = function () {
  37258. this.mesh.dispose();
  37259. this.vars = null;
  37260. // drop references to internal big arrays for the GC
  37261. this._positions = null;
  37262. this._indices = null;
  37263. this._normals = null;
  37264. this._uvs = null;
  37265. this._colors = null;
  37266. this._positions32 = null;
  37267. this._normals32 = null;
  37268. this._fixedNormal32 = null;
  37269. this._uvs32 = null;
  37270. this._colors32 = null;
  37271. this.pickedParticles = null;
  37272. };
  37273. /**
  37274. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37275. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37276. */
  37277. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37278. this.mesh.refreshBoundingInfo();
  37279. };
  37280. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37281. // getter and setter
  37282. /**
  37283. * True if the SPS is set as always visible
  37284. */
  37285. get: function () {
  37286. return this._alwaysVisible;
  37287. },
  37288. /**
  37289. * Sets the SPS as always visible or not
  37290. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37291. */
  37292. set: function (val) {
  37293. this._alwaysVisible = val;
  37294. this.mesh.alwaysSelectAsActiveMesh = val;
  37295. },
  37296. enumerable: true,
  37297. configurable: true
  37298. });
  37299. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37300. // getters
  37301. get: function () {
  37302. return this._computeParticleRotation;
  37303. },
  37304. // Optimizer setters
  37305. /**
  37306. * Tells to setParticle() to compute the particle rotations or not.
  37307. * Default value : true. The SPS is faster when it's set to false.
  37308. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37309. */
  37310. set: function (val) {
  37311. this._computeParticleRotation = val;
  37312. },
  37313. enumerable: true,
  37314. configurable: true
  37315. });
  37316. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37317. get: function () {
  37318. return this._computeParticleColor;
  37319. },
  37320. /**
  37321. * Tells to setParticle() to compute the particle colors or not.
  37322. * Default value : true. The SPS is faster when it's set to false.
  37323. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37324. */
  37325. set: function (val) {
  37326. this._computeParticleColor = val;
  37327. },
  37328. enumerable: true,
  37329. configurable: true
  37330. });
  37331. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37332. get: function () {
  37333. return this._computeParticleTexture;
  37334. },
  37335. /**
  37336. * Tells to setParticle() to compute the particle textures or not.
  37337. * Default value : true. The SPS is faster when it's set to false.
  37338. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37339. */
  37340. set: function (val) {
  37341. this._computeParticleTexture = val;
  37342. },
  37343. enumerable: true,
  37344. configurable: true
  37345. });
  37346. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37347. get: function () {
  37348. return this._computeParticleVertex;
  37349. },
  37350. /**
  37351. * Tells to setParticle() to call the vertex function for each vertex of each particle, or not.
  37352. * Default value : false. The SPS is faster when it's set to false.
  37353. * Note : the particle custom vertex positions aren't stored values.
  37354. */
  37355. set: function (val) {
  37356. this._computeParticleVertex = val;
  37357. },
  37358. enumerable: true,
  37359. configurable: true
  37360. });
  37361. // =======================================================================
  37362. // Particle behavior logic
  37363. // these following methods may be overwritten by the user to fit his needs
  37364. /**
  37365. * This function does nothing. It may be overwritten to set all the particles first values.
  37366. * The SPS doesn't call this function, you may have to call it by your own.
  37367. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37368. */
  37369. SolidParticleSystem.prototype.initParticles = function () {
  37370. };
  37371. /**
  37372. * This function does nothing. It may be overwritten to recycle a particle.
  37373. * The SPS doesn't call this function, you may have to call it by your own.
  37374. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37375. */
  37376. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37377. return particle;
  37378. };
  37379. /**
  37380. * Updates a particle : this function should be overwritten by the user.
  37381. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37382. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37383. * ex : just set a particle position or velocity and recycle conditions
  37384. */
  37385. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37386. return particle;
  37387. };
  37388. /**
  37389. * Updates a vertex of a particle : it can be overwritten by the user.
  37390. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37391. * @param particle the current particle
  37392. * @param vertex the current index of the current particle
  37393. * @param pt the index of the current vertex in the particle shape
  37394. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37395. * ex : just set a vertex particle position
  37396. */
  37397. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37398. return vertex;
  37399. };
  37400. /**
  37401. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37402. * This does nothing and may be overwritten by the user.
  37403. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37404. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37405. * @param update the boolean update value actually passed to setParticles()
  37406. */
  37407. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37408. };
  37409. /**
  37410. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37411. * This will be passed three parameters.
  37412. * This does nothing and may be overwritten by the user.
  37413. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37414. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37415. * @param update the boolean update value actually passed to setParticles()
  37416. */
  37417. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37418. };
  37419. return SolidParticleSystem;
  37420. })();
  37421. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37422. })(BABYLON || (BABYLON = {}));
  37423. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nuniform vec2 depthValues;\r\n\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\tdirectionToLight = normalize(directionToLight);\r\n\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  37424. 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){var i=1/2.2,n=2.2,r=function(){function r(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 r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.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},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.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},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.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},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.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},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.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)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=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=o;var s=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,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,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=s;var e=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 a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},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,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,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,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},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),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),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=f.X,u=f.Y,m=0,y=0,c=0,p=0,l=0,x=0,z=0,w=-1,v=0,g=M.Vector3[0],d=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)?p=1:(z=h.z/h.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=p,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,g),g.normalize(),i.Dot(h,g)<0&&(w=1),d=i.Dot(e,T),d=Math.min(1,Math.max(-1,d)),c=Math.acos(d)*w,i.Dot(T,a)<0&&(c=Math.PI+c,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];p=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?p=1:(z=T.z/T.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=p,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,g),g.normalize(),i.Dot(T,g)<0&&(w=1),d=i.Dot(h,R),d=Math.min(1,Math.max(-1,d)),y=Math.acos(d)*w,i.Dot(_,u)<0&&(y=Math.PI+y,v++),w=-1,i.CrossToRef(a,T,g),g.normalize(),i.Dot(g,u)<0&&(w=1),d=i.Dot(T,a),d=Math.min(1,Math.max(-1,d)),m=-Math.acos(d)*w,0>d&&2>v&&(m=Math.PI+m),s.x=y,s.y=m,s.z=c},i}();t.Vector3=e;var h=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=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=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],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,Z=s*x-a*p,I=s*l-h*p,E=s*f-e*p,L=h*c-a*y,q=e*c-a*m,S=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*Z+o*I)*b,t.m[10]=(i*P-n*Z+o*E)*b,t.m[14]=-(i*C-n*I+r*E)*b,t.m[3]=-(n*L-r*q+o*S)*b,t.m[7]=(i*L-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*S-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],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=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],P=t.m[10],C=t.m[11],Z=t.m[12],I=t.m[13],E=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*g+o*_+s*A+e*I,i[n+2]=r*d+o*M+s*P+e*E,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*g+a*_+u*A+m*I,i[n+6]=h*d+a*M+u*P+m*E,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*g+c*_+p*A+f*I,i[n+10]=y*d+c*M+p*P+f*E,i[n+11]=y*T+c*F+p*C+f*L,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*g+x*_+z*A+w*I,i[n+14]=l*d+x*M+z*P+w*E,i[n+15]=l*T+x*F+z*C+w*L,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,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=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=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*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 a.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,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,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]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,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;\n},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){a.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 o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return i.Compose(c,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,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.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,s,h,a,1,o)},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,y=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(y)},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 a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(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=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.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 e.Dot(n,i)+r},t}();t.Plane=m;var y=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=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(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=c;var p=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=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.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=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=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=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.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?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=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 e(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=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,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 s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}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.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=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]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.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 o;if(void 0===r||null===r){var s;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)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s: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;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.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=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.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.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[h.Zero(),h.Zero(),h.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  37425. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  37426. module.exports = BABYLON;
  37427. };