babylon.max.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. BABYLON.ToGammaSpace = 1 / 2.2;
  10. BABYLON.ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // SphericalHarmonics
  2926. var SphericalHarmonics = (function () {
  2927. function SphericalHarmonics() {
  2928. this.L00 = Vector3.Zero();
  2929. this.L1_1 = Vector3.Zero();
  2930. this.L10 = Vector3.Zero();
  2931. this.L11 = Vector3.Zero();
  2932. this.L2_2 = Vector3.Zero();
  2933. this.L2_1 = Vector3.Zero();
  2934. this.L20 = Vector3.Zero();
  2935. this.L21 = Vector3.Zero();
  2936. this.L22 = Vector3.Zero();
  2937. }
  2938. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2939. var colorVector = new Vector3(color.r, color.g, color.b);
  2940. var c = colorVector.scale(deltaSolidAngle);
  2941. this.L00 = this.L00.add(c.scale(0.282095));
  2942. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2943. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2944. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2945. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2946. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2947. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2948. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2949. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2950. };
  2951. SphericalHarmonics.prototype.scale = function (scale) {
  2952. this.L00 = this.L00.scale(scale);
  2953. this.L1_1 = this.L1_1.scale(scale);
  2954. this.L10 = this.L10.scale(scale);
  2955. this.L11 = this.L11.scale(scale);
  2956. this.L2_2 = this.L2_2.scale(scale);
  2957. this.L2_1 = this.L2_1.scale(scale);
  2958. this.L20 = this.L20.scale(scale);
  2959. this.L21 = this.L21.scale(scale);
  2960. this.L22 = this.L22.scale(scale);
  2961. };
  2962. return SphericalHarmonics;
  2963. })();
  2964. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2965. // SphericalPolynomial
  2966. var SphericalPolynomial = (function () {
  2967. function SphericalPolynomial() {
  2968. this.x = Vector3.Zero();
  2969. this.y = Vector3.Zero();
  2970. this.z = Vector3.Zero();
  2971. this.xx = Vector3.Zero();
  2972. this.yy = Vector3.Zero();
  2973. this.zz = Vector3.Zero();
  2974. this.xy = Vector3.Zero();
  2975. this.yz = Vector3.Zero();
  2976. this.zx = Vector3.Zero();
  2977. }
  2978. SphericalPolynomial.prototype.addAmbient = function (color) {
  2979. var colorVector = new Vector3(color.r, color.g, color.b);
  2980. this.xx = this.xx.add(colorVector);
  2981. this.yy = this.yy.add(colorVector);
  2982. this.zz = this.zz.add(colorVector);
  2983. };
  2984. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2985. var result = new SphericalPolynomial();
  2986. result.x = harmonics.L11.scale(1.02333);
  2987. result.y = harmonics.L1_1.scale(1.02333);
  2988. result.z = harmonics.L10.scale(1.02333);
  2989. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2990. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2991. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2992. result.yz = harmonics.L2_1.scale(0.858086);
  2993. result.zx = harmonics.L21.scale(0.858086);
  2994. result.xy = harmonics.L2_2.scale(0.858086);
  2995. return result;
  2996. };
  2997. return SphericalPolynomial;
  2998. })();
  2999. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3000. // Vertex formats
  3001. var PositionNormalVertex = (function () {
  3002. function PositionNormalVertex(position, normal) {
  3003. if (position === void 0) { position = Vector3.Zero(); }
  3004. if (normal === void 0) { normal = Vector3.Up(); }
  3005. this.position = position;
  3006. this.normal = normal;
  3007. }
  3008. PositionNormalVertex.prototype.clone = function () {
  3009. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3010. };
  3011. return PositionNormalVertex;
  3012. })();
  3013. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3014. var PositionNormalTextureVertex = (function () {
  3015. function PositionNormalTextureVertex(position, normal, uv) {
  3016. if (position === void 0) { position = Vector3.Zero(); }
  3017. if (normal === void 0) { normal = Vector3.Up(); }
  3018. if (uv === void 0) { uv = Vector2.Zero(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. this.uv = uv;
  3022. }
  3023. PositionNormalTextureVertex.prototype.clone = function () {
  3024. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3025. };
  3026. return PositionNormalTextureVertex;
  3027. })();
  3028. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3029. // Temporary pre-allocated objects for engine internal use
  3030. // usage in any internal function :
  3031. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3032. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3033. var Tmp = (function () {
  3034. function Tmp() {
  3035. }
  3036. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3037. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3038. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3039. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3040. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3041. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3042. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3043. Matrix.Zero(), Matrix.Zero(),
  3044. Matrix.Zero(), Matrix.Zero(),
  3045. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3046. return Tmp;
  3047. })();
  3048. BABYLON.Tmp = Tmp;
  3049. })(BABYLON || (BABYLON = {}));
  3050. var BABYLON;
  3051. (function (BABYLON) {
  3052. function generateSerializableMember(type, sourceName) {
  3053. return function (target, propertyKey) {
  3054. if (!target.__serializableMembers) {
  3055. target.__serializableMembers = {};
  3056. }
  3057. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3058. };
  3059. }
  3060. function serialize(sourceName) {
  3061. return generateSerializableMember(0, sourceName); // value member
  3062. }
  3063. BABYLON.serialize = serialize;
  3064. function serializeAsTexture(sourceName) {
  3065. return generateSerializableMember(1, sourceName); // texture member
  3066. }
  3067. BABYLON.serializeAsTexture = serializeAsTexture;
  3068. function serializeAsColor3(sourceName) {
  3069. return generateSerializableMember(2, sourceName); // color3 member
  3070. }
  3071. BABYLON.serializeAsColor3 = serializeAsColor3;
  3072. function serializeAsFresnelParameters(sourceName) {
  3073. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3074. }
  3075. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3076. function serializeAsVector2(sourceName) {
  3077. return generateSerializableMember(4, sourceName); // vector2 member
  3078. }
  3079. BABYLON.serializeAsVector2 = serializeAsVector2;
  3080. function serializeAsVector3(sourceName) {
  3081. return generateSerializableMember(5, sourceName); // vector3 member
  3082. }
  3083. BABYLON.serializeAsVector3 = serializeAsVector3;
  3084. function serializeAsMeshReference(sourceName) {
  3085. return generateSerializableMember(6, sourceName); // mesh reference member
  3086. }
  3087. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3088. var SerializationHelper = (function () {
  3089. function SerializationHelper() {
  3090. }
  3091. SerializationHelper.Serialize = function (entity, serializationObject) {
  3092. if (!serializationObject) {
  3093. serializationObject = {};
  3094. }
  3095. // Tags
  3096. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3097. // Properties
  3098. for (var property in entity.__serializableMembers) {
  3099. var propertyDescriptor = entity.__serializableMembers[property];
  3100. var targetPropertyName = propertyDescriptor.sourceName || property;
  3101. var propertyType = propertyDescriptor.type;
  3102. var sourceProperty = entity[property];
  3103. if (sourceProperty !== undefined && sourceProperty !== null) {
  3104. switch (propertyType) {
  3105. case 0:
  3106. serializationObject[targetPropertyName] = sourceProperty;
  3107. break;
  3108. case 1:
  3109. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3110. break;
  3111. case 2:
  3112. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3113. break;
  3114. case 3:
  3115. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3116. break;
  3117. case 4:
  3118. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3119. break;
  3120. case 5:
  3121. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3122. break;
  3123. case 6:
  3124. serializationObject[targetPropertyName] = sourceProperty.id;
  3125. break;
  3126. }
  3127. }
  3128. }
  3129. return serializationObject;
  3130. };
  3131. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3132. var destination = creationFunction();
  3133. // Tags
  3134. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3135. // Properties
  3136. for (var property in destination.__serializableMembers) {
  3137. var propertyDescriptor = destination.__serializableMembers[property];
  3138. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3139. var propertyType = propertyDescriptor.type;
  3140. if (sourceProperty !== undefined && sourceProperty !== null) {
  3141. switch (propertyType) {
  3142. case 0:
  3143. destination[property] = sourceProperty;
  3144. break;
  3145. case 1:
  3146. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3147. break;
  3148. case 2:
  3149. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3150. break;
  3151. case 3:
  3152. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3153. break;
  3154. case 4:
  3155. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3156. break;
  3157. case 5:
  3158. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3159. break;
  3160. case 6:
  3161. destination[property] = scene.getLastMeshByID(sourceProperty);
  3162. break;
  3163. }
  3164. }
  3165. }
  3166. return destination;
  3167. };
  3168. SerializationHelper.Clone = function (creationFunction, source) {
  3169. var destination = creationFunction();
  3170. // Tags
  3171. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3172. // Properties
  3173. for (var property in destination.__serializableMembers) {
  3174. var propertyDescriptor = destination.__serializableMembers[property];
  3175. var sourceProperty = source[property];
  3176. var propertyType = propertyDescriptor.type;
  3177. if (sourceProperty !== undefined && sourceProperty !== null) {
  3178. switch (propertyType) {
  3179. case 0: // Value
  3180. case 6:
  3181. destination[property] = sourceProperty;
  3182. break;
  3183. case 1: // Texture
  3184. case 2: // Color3
  3185. case 3: // FresnelParameters
  3186. case 4: // Vector2
  3187. case 5:
  3188. destination[property] = sourceProperty.clone();
  3189. break;
  3190. }
  3191. }
  3192. }
  3193. return destination;
  3194. };
  3195. return SerializationHelper;
  3196. })();
  3197. BABYLON.SerializationHelper = SerializationHelper;
  3198. })(BABYLON || (BABYLON = {}));
  3199. var BABYLON;
  3200. (function (BABYLON) {
  3201. var Database = (function () {
  3202. function Database(urlToScene, callbackManifestChecked) {
  3203. // Handling various flavors of prefixed version of IndexedDB
  3204. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3205. this.callbackManifestChecked = callbackManifestChecked;
  3206. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3207. this.db = null;
  3208. this.enableSceneOffline = false;
  3209. this.enableTexturesOffline = false;
  3210. this.manifestVersionFound = 0;
  3211. this.mustUpdateRessources = false;
  3212. this.hasReachedQuota = false;
  3213. if (!Database.IDBStorageEnabled) {
  3214. this.callbackManifestChecked(true);
  3215. }
  3216. else {
  3217. this.checkManifestFile();
  3218. }
  3219. }
  3220. Database.prototype.checkManifestFile = function () {
  3221. var _this = this;
  3222. function noManifestFile() {
  3223. that.enableSceneOffline = false;
  3224. that.enableTexturesOffline = false;
  3225. that.callbackManifestChecked(false);
  3226. }
  3227. var that = this;
  3228. var timeStampUsed = false;
  3229. var manifestURL = this.currentSceneUrl + ".manifest";
  3230. var xhr = new XMLHttpRequest();
  3231. if (navigator.onLine) {
  3232. // Adding a timestamp to by-pass browsers' cache
  3233. timeStampUsed = true;
  3234. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3235. }
  3236. xhr.open("GET", manifestURL, true);
  3237. xhr.addEventListener("load", function () {
  3238. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3239. try {
  3240. var manifestFile = JSON.parse(xhr.response);
  3241. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3242. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3243. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3244. _this.manifestVersionFound = manifestFile.version;
  3245. }
  3246. if (_this.callbackManifestChecked) {
  3247. _this.callbackManifestChecked(true);
  3248. }
  3249. }
  3250. catch (ex) {
  3251. noManifestFile();
  3252. }
  3253. }
  3254. else {
  3255. noManifestFile();
  3256. }
  3257. }, false);
  3258. xhr.addEventListener("error", function (event) {
  3259. if (timeStampUsed) {
  3260. timeStampUsed = false;
  3261. // Let's retry without the timeStamp
  3262. // It could fail when coupled with HTML5 Offline API
  3263. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3264. xhr.open("GET", retryManifestURL, true);
  3265. xhr.send();
  3266. }
  3267. else {
  3268. noManifestFile();
  3269. }
  3270. }, false);
  3271. try {
  3272. xhr.send();
  3273. }
  3274. catch (ex) {
  3275. BABYLON.Tools.Error("Error on XHR send request.");
  3276. that.callbackManifestChecked(false);
  3277. }
  3278. };
  3279. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3280. var _this = this;
  3281. function handleError() {
  3282. that.isSupported = false;
  3283. if (errorCallback)
  3284. errorCallback();
  3285. }
  3286. var that = this;
  3287. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3288. // Your browser doesn't support IndexedDB
  3289. this.isSupported = false;
  3290. if (errorCallback)
  3291. errorCallback();
  3292. }
  3293. else {
  3294. // If the DB hasn't been opened or created yet
  3295. if (!this.db) {
  3296. this.hasReachedQuota = false;
  3297. this.isSupported = true;
  3298. var request = this.idbFactory.open("babylonjs", 1);
  3299. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3300. request.onerror = function (event) {
  3301. handleError();
  3302. };
  3303. // executes when a version change transaction cannot complete due to other active transactions
  3304. request.onblocked = function (event) {
  3305. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3306. handleError();
  3307. };
  3308. // DB has been opened successfully
  3309. request.onsuccess = function (event) {
  3310. _this.db = request.result;
  3311. successCallback();
  3312. };
  3313. // Initialization of the DB. Creating Scenes & Textures stores
  3314. request.onupgradeneeded = function (event) {
  3315. _this.db = (event.target).result;
  3316. try {
  3317. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3318. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3319. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3323. handleError();
  3324. }
  3325. };
  3326. }
  3327. else {
  3328. if (successCallback)
  3329. successCallback();
  3330. }
  3331. }
  3332. };
  3333. Database.prototype.loadImageFromDB = function (url, image) {
  3334. var _this = this;
  3335. var completeURL = Database.ReturnFullUrlLocation(url);
  3336. var saveAndLoadImage = function () {
  3337. if (!_this.hasReachedQuota && _this.db !== null) {
  3338. // the texture is not yet in the DB, let's try to save it
  3339. _this._saveImageIntoDBAsync(completeURL, image);
  3340. }
  3341. else {
  3342. image.src = url;
  3343. }
  3344. };
  3345. if (!this.mustUpdateRessources) {
  3346. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3347. }
  3348. else {
  3349. saveAndLoadImage();
  3350. }
  3351. };
  3352. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3353. if (this.isSupported && this.db !== null) {
  3354. var texture;
  3355. var transaction = this.db.transaction(["textures"]);
  3356. transaction.onabort = function (event) {
  3357. image.src = url;
  3358. };
  3359. transaction.oncomplete = function (event) {
  3360. var blobTextureURL;
  3361. if (texture) {
  3362. var URL = window.URL || window.webkitURL;
  3363. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3364. image.onerror = function () {
  3365. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3366. image.src = url;
  3367. };
  3368. image.src = blobTextureURL;
  3369. }
  3370. else {
  3371. notInDBCallback();
  3372. }
  3373. };
  3374. var getRequest = transaction.objectStore("textures").get(url);
  3375. getRequest.onsuccess = function (event) {
  3376. texture = (event.target).result;
  3377. };
  3378. getRequest.onerror = function (event) {
  3379. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3380. image.src = url;
  3381. };
  3382. }
  3383. else {
  3384. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3385. image.src = url;
  3386. }
  3387. };
  3388. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3389. var _this = this;
  3390. if (this.isSupported) {
  3391. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3392. var generateBlobUrl = function () {
  3393. var blobTextureURL;
  3394. if (blob) {
  3395. var URL = window.URL || window.webkitURL;
  3396. try {
  3397. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3398. }
  3399. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3400. catch (ex) {
  3401. blobTextureURL = URL.createObjectURL(blob);
  3402. }
  3403. }
  3404. image.src = blobTextureURL;
  3405. };
  3406. if (Database.IsUASupportingBlobStorage) {
  3407. var xhr = new XMLHttpRequest(), blob;
  3408. xhr.open("GET", url, true);
  3409. xhr.responseType = "blob";
  3410. xhr.addEventListener("load", function () {
  3411. if (xhr.status === 200) {
  3412. // Blob as response (XHR2)
  3413. blob = xhr.response;
  3414. var transaction = _this.db.transaction(["textures"], "readwrite");
  3415. // the transaction could abort because of a QuotaExceededError error
  3416. transaction.onabort = function (event) {
  3417. try {
  3418. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3419. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3420. this.hasReachedQuota = true;
  3421. }
  3422. }
  3423. catch (ex) { }
  3424. generateBlobUrl();
  3425. };
  3426. transaction.oncomplete = function (event) {
  3427. generateBlobUrl();
  3428. };
  3429. var newTexture = { textureUrl: url, data: blob };
  3430. try {
  3431. // Put the blob into the dabase
  3432. var addRequest = transaction.objectStore("textures").put(newTexture);
  3433. addRequest.onsuccess = function (event) {
  3434. };
  3435. addRequest.onerror = function (event) {
  3436. generateBlobUrl();
  3437. };
  3438. }
  3439. catch (ex) {
  3440. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3441. if (ex.code === 25) {
  3442. Database.IsUASupportingBlobStorage = false;
  3443. }
  3444. image.src = url;
  3445. }
  3446. }
  3447. else {
  3448. image.src = url;
  3449. }
  3450. }, false);
  3451. xhr.addEventListener("error", function (event) {
  3452. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3453. image.src = url;
  3454. }, false);
  3455. xhr.send();
  3456. }
  3457. else {
  3458. image.src = url;
  3459. }
  3460. }
  3461. else {
  3462. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3463. image.src = url;
  3464. }
  3465. };
  3466. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3467. var _this = this;
  3468. var updateVersion = function (event) {
  3469. // the version is not yet in the DB or we need to update it
  3470. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3471. };
  3472. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3473. };
  3474. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3475. var _this = this;
  3476. if (this.isSupported) {
  3477. var version;
  3478. try {
  3479. var transaction = this.db.transaction(["versions"]);
  3480. transaction.oncomplete = function (event) {
  3481. if (version) {
  3482. // If the version in the JSON file is > than the version in DB
  3483. if (_this.manifestVersionFound > version.data) {
  3484. _this.mustUpdateRessources = true;
  3485. updateInDBCallback();
  3486. }
  3487. else {
  3488. callback(version.data);
  3489. }
  3490. }
  3491. else {
  3492. _this.mustUpdateRessources = true;
  3493. updateInDBCallback();
  3494. }
  3495. };
  3496. transaction.onabort = function (event) {
  3497. callback(-1);
  3498. };
  3499. var getRequest = transaction.objectStore("versions").get(url);
  3500. getRequest.onsuccess = function (event) {
  3501. version = (event.target).result;
  3502. };
  3503. getRequest.onerror = function (event) {
  3504. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3505. callback(-1);
  3506. };
  3507. }
  3508. catch (ex) {
  3509. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3510. callback(-1);
  3511. }
  3512. }
  3513. else {
  3514. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3515. callback(-1);
  3516. }
  3517. };
  3518. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3519. var _this = this;
  3520. if (this.isSupported && !this.hasReachedQuota) {
  3521. try {
  3522. // Open a transaction to the database
  3523. var transaction = this.db.transaction(["versions"], "readwrite");
  3524. // the transaction could abort because of a QuotaExceededError error
  3525. transaction.onabort = function (event) {
  3526. try {
  3527. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3528. _this.hasReachedQuota = true;
  3529. }
  3530. }
  3531. catch (ex) { }
  3532. callback(-1);
  3533. };
  3534. transaction.oncomplete = function (event) {
  3535. callback(_this.manifestVersionFound);
  3536. };
  3537. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3538. // Put the scene into the database
  3539. var addRequest = transaction.objectStore("versions").put(newVersion);
  3540. addRequest.onsuccess = function (event) {
  3541. };
  3542. addRequest.onerror = function (event) {
  3543. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3544. };
  3545. }
  3546. catch (ex) {
  3547. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3548. callback(-1);
  3549. }
  3550. }
  3551. else {
  3552. callback(-1);
  3553. }
  3554. };
  3555. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3556. var _this = this;
  3557. var completeUrl = Database.ReturnFullUrlLocation(url);
  3558. var saveAndLoadFile = function (event) {
  3559. // the scene is not yet in the DB, let's try to save it
  3560. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3561. };
  3562. this._checkVersionFromDB(completeUrl, function (version) {
  3563. if (version !== -1) {
  3564. if (!_this.mustUpdateRessources) {
  3565. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3566. }
  3567. else {
  3568. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3569. }
  3570. }
  3571. else {
  3572. errorCallback();
  3573. }
  3574. });
  3575. };
  3576. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3577. if (this.isSupported) {
  3578. var targetStore;
  3579. if (url.indexOf(".babylon") !== -1) {
  3580. targetStore = "scenes";
  3581. }
  3582. else {
  3583. targetStore = "textures";
  3584. }
  3585. var file;
  3586. var transaction = this.db.transaction([targetStore]);
  3587. transaction.oncomplete = function (event) {
  3588. if (file) {
  3589. callback(file.data);
  3590. }
  3591. else {
  3592. notInDBCallback();
  3593. }
  3594. };
  3595. transaction.onabort = function (event) {
  3596. notInDBCallback();
  3597. };
  3598. var getRequest = transaction.objectStore(targetStore).get(url);
  3599. getRequest.onsuccess = function (event) {
  3600. file = (event.target).result;
  3601. };
  3602. getRequest.onerror = function (event) {
  3603. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3604. notInDBCallback();
  3605. };
  3606. }
  3607. else {
  3608. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3609. callback();
  3610. }
  3611. };
  3612. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3613. var _this = this;
  3614. if (this.isSupported) {
  3615. var targetStore;
  3616. if (url.indexOf(".babylon") !== -1) {
  3617. targetStore = "scenes";
  3618. }
  3619. else {
  3620. targetStore = "textures";
  3621. }
  3622. // Create XHR
  3623. var xhr = new XMLHttpRequest(), fileData;
  3624. xhr.open("GET", url, true);
  3625. if (useArrayBuffer) {
  3626. xhr.responseType = "arraybuffer";
  3627. }
  3628. xhr.onprogress = progressCallback;
  3629. xhr.addEventListener("load", function () {
  3630. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3631. // Blob as response (XHR2)
  3632. //fileData = xhr.responseText;
  3633. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3634. if (!_this.hasReachedQuota) {
  3635. // Open a transaction to the database
  3636. var transaction = _this.db.transaction([targetStore], "readwrite");
  3637. // the transaction could abort because of a QuotaExceededError error
  3638. transaction.onabort = function (event) {
  3639. try {
  3640. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3641. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3642. this.hasReachedQuota = true;
  3643. }
  3644. }
  3645. catch (ex) { }
  3646. callback(fileData);
  3647. };
  3648. transaction.oncomplete = function (event) {
  3649. callback(fileData);
  3650. };
  3651. var newFile;
  3652. if (targetStore === "scenes") {
  3653. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3654. }
  3655. else {
  3656. newFile = { textureUrl: url, data: fileData };
  3657. }
  3658. try {
  3659. // Put the scene into the database
  3660. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3661. addRequest.onsuccess = function (event) {
  3662. };
  3663. addRequest.onerror = function (event) {
  3664. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3665. };
  3666. }
  3667. catch (ex) {
  3668. callback(fileData);
  3669. }
  3670. }
  3671. else {
  3672. callback(fileData);
  3673. }
  3674. }
  3675. else {
  3676. callback();
  3677. }
  3678. }, false);
  3679. xhr.addEventListener("error", function (event) {
  3680. BABYLON.Tools.Error("error on XHR request.");
  3681. callback();
  3682. }, false);
  3683. xhr.send();
  3684. }
  3685. else {
  3686. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3687. callback();
  3688. }
  3689. };
  3690. Database.IsUASupportingBlobStorage = true;
  3691. Database.IDBStorageEnabled = true;
  3692. Database.parseURL = function (url) {
  3693. var a = document.createElement('a');
  3694. a.href = url;
  3695. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3696. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3697. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3698. return absLocation;
  3699. };
  3700. Database.ReturnFullUrlLocation = function (url) {
  3701. if (url.indexOf("http:/") === -1) {
  3702. return (Database.parseURL(window.location.href) + url);
  3703. }
  3704. else {
  3705. return url;
  3706. }
  3707. };
  3708. return Database;
  3709. })();
  3710. BABYLON.Database = Database;
  3711. })(BABYLON || (BABYLON = {}));
  3712. var BABYLON;
  3713. (function (BABYLON) {
  3714. var Internals;
  3715. (function (Internals) {
  3716. /*
  3717. * Based on jsTGALoader - Javascript loader for TGA file
  3718. * By Vincent Thibault
  3719. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3720. */
  3721. var TGATools = (function () {
  3722. function TGATools() {
  3723. }
  3724. TGATools.GetTGAHeader = function (data) {
  3725. var offset = 0;
  3726. var header = {
  3727. id_length: data[offset++],
  3728. colormap_type: data[offset++],
  3729. image_type: data[offset++],
  3730. colormap_index: data[offset++] | data[offset++] << 8,
  3731. colormap_length: data[offset++] | data[offset++] << 8,
  3732. colormap_size: data[offset++],
  3733. origin: [
  3734. data[offset++] | data[offset++] << 8,
  3735. data[offset++] | data[offset++] << 8
  3736. ],
  3737. width: data[offset++] | data[offset++] << 8,
  3738. height: data[offset++] | data[offset++] << 8,
  3739. pixel_size: data[offset++],
  3740. flags: data[offset++]
  3741. };
  3742. return header;
  3743. };
  3744. TGATools.UploadContent = function (gl, data) {
  3745. // Not enough data to contain header ?
  3746. if (data.length < 19) {
  3747. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3748. return;
  3749. }
  3750. // Read Header
  3751. var offset = 18;
  3752. var header = TGATools.GetTGAHeader(data);
  3753. // Assume it's a valid Targa file.
  3754. if (header.id_length + offset > data.length) {
  3755. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3756. return;
  3757. }
  3758. // Skip not needed data
  3759. offset += header.id_length;
  3760. var use_rle = false;
  3761. var use_pal = false;
  3762. var use_rgb = false;
  3763. var use_grey = false;
  3764. // Get some informations.
  3765. switch (header.image_type) {
  3766. case TGATools._TYPE_RLE_INDEXED:
  3767. use_rle = true;
  3768. case TGATools._TYPE_INDEXED:
  3769. use_pal = true;
  3770. break;
  3771. case TGATools._TYPE_RLE_RGB:
  3772. use_rle = true;
  3773. case TGATools._TYPE_RGB:
  3774. use_rgb = true;
  3775. break;
  3776. case TGATools._TYPE_RLE_GREY:
  3777. use_rle = true;
  3778. case TGATools._TYPE_GREY:
  3779. use_grey = true;
  3780. break;
  3781. }
  3782. var pixel_data;
  3783. var numAlphaBits = header.flags & 0xf;
  3784. var pixel_size = header.pixel_size >> 3;
  3785. var pixel_total = header.width * header.height * pixel_size;
  3786. // Read palettes
  3787. var palettes;
  3788. if (use_pal) {
  3789. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3790. }
  3791. // Read LRE
  3792. if (use_rle) {
  3793. pixel_data = new Uint8Array(pixel_total);
  3794. var c, count, i;
  3795. var localOffset = 0;
  3796. var pixels = new Uint8Array(pixel_size);
  3797. while (offset < pixel_total && localOffset < pixel_total) {
  3798. c = data[offset++];
  3799. count = (c & 0x7f) + 1;
  3800. // RLE pixels
  3801. if (c & 0x80) {
  3802. // Bind pixel tmp array
  3803. for (i = 0; i < pixel_size; ++i) {
  3804. pixels[i] = data[offset++];
  3805. }
  3806. // Copy pixel array
  3807. for (i = 0; i < count; ++i) {
  3808. pixel_data.set(pixels, localOffset + i * pixel_size);
  3809. }
  3810. localOffset += pixel_size * count;
  3811. }
  3812. else {
  3813. count *= pixel_size;
  3814. for (i = 0; i < count; ++i) {
  3815. pixel_data[localOffset + i] = data[offset++];
  3816. }
  3817. localOffset += count;
  3818. }
  3819. }
  3820. }
  3821. else {
  3822. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3823. }
  3824. // Load to texture
  3825. var x_start, y_start, x_step, y_step, y_end, x_end;
  3826. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3827. default:
  3828. case TGATools._ORIGIN_UL:
  3829. x_start = 0;
  3830. x_step = 1;
  3831. x_end = header.width;
  3832. y_start = 0;
  3833. y_step = 1;
  3834. y_end = header.height;
  3835. break;
  3836. case TGATools._ORIGIN_BL:
  3837. x_start = 0;
  3838. x_step = 1;
  3839. x_end = header.width;
  3840. y_start = header.height - 1;
  3841. y_step = -1;
  3842. y_end = -1;
  3843. break;
  3844. case TGATools._ORIGIN_UR:
  3845. x_start = header.width - 1;
  3846. x_step = -1;
  3847. x_end = -1;
  3848. y_start = 0;
  3849. y_step = 1;
  3850. y_end = header.height;
  3851. break;
  3852. case TGATools._ORIGIN_BR:
  3853. x_start = header.width - 1;
  3854. x_step = -1;
  3855. x_end = -1;
  3856. y_start = header.height - 1;
  3857. y_step = -1;
  3858. y_end = -1;
  3859. break;
  3860. }
  3861. // Load the specify method
  3862. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3863. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3864. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3865. };
  3866. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3867. var image = pixel_data, colormap = palettes;
  3868. var width = header.width, height = header.height;
  3869. var color, i = 0, x, y;
  3870. var imageData = new Uint8Array(width * height * 4);
  3871. for (y = y_start; y !== y_end; y += y_step) {
  3872. for (x = x_start; x !== x_end; x += x_step, i++) {
  3873. color = image[i];
  3874. imageData[(x + width * y) * 4 + 3] = 255;
  3875. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3876. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3877. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3878. }
  3879. }
  3880. return imageData;
  3881. };
  3882. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3883. var image = pixel_data;
  3884. var width = header.width, height = header.height;
  3885. var color, i = 0, x, y;
  3886. var imageData = new Uint8Array(width * height * 4);
  3887. for (y = y_start; y !== y_end; y += y_step) {
  3888. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3889. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3890. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3891. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3892. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3893. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3894. }
  3895. }
  3896. return imageData;
  3897. };
  3898. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3899. var image = pixel_data;
  3900. var width = header.width, height = header.height;
  3901. var i = 0, x, y;
  3902. var imageData = new Uint8Array(width * height * 4);
  3903. for (y = y_start; y !== y_end; y += y_step) {
  3904. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3905. imageData[(x + width * y) * 4 + 3] = 255;
  3906. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3907. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3908. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3909. }
  3910. }
  3911. return imageData;
  3912. };
  3913. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3914. var image = pixel_data;
  3915. var width = header.width, height = header.height;
  3916. var i = 0, x, y;
  3917. var imageData = new Uint8Array(width * height * 4);
  3918. for (y = y_start; y !== y_end; y += y_step) {
  3919. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3920. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3921. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3922. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3923. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3924. }
  3925. }
  3926. return imageData;
  3927. };
  3928. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3929. var image = pixel_data;
  3930. var width = header.width, height = header.height;
  3931. var color, i = 0, x, y;
  3932. var imageData = new Uint8Array(width * height * 4);
  3933. for (y = y_start; y !== y_end; y += y_step) {
  3934. for (x = x_start; x !== x_end; x += x_step, i++) {
  3935. color = image[i];
  3936. imageData[(x + width * y) * 4 + 0] = color;
  3937. imageData[(x + width * y) * 4 + 1] = color;
  3938. imageData[(x + width * y) * 4 + 2] = color;
  3939. imageData[(x + width * y) * 4 + 3] = 255;
  3940. }
  3941. }
  3942. return imageData;
  3943. };
  3944. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3945. var image = pixel_data;
  3946. var width = header.width, height = header.height;
  3947. var i = 0, x, y;
  3948. var imageData = new Uint8Array(width * height * 4);
  3949. for (y = y_start; y !== y_end; y += y_step) {
  3950. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3951. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3952. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3953. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3954. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3955. }
  3956. }
  3957. return imageData;
  3958. };
  3959. TGATools._TYPE_NO_DATA = 0;
  3960. TGATools._TYPE_INDEXED = 1;
  3961. TGATools._TYPE_RGB = 2;
  3962. TGATools._TYPE_GREY = 3;
  3963. TGATools._TYPE_RLE_INDEXED = 9;
  3964. TGATools._TYPE_RLE_RGB = 10;
  3965. TGATools._TYPE_RLE_GREY = 11;
  3966. TGATools._ORIGIN_MASK = 0x30;
  3967. TGATools._ORIGIN_SHIFT = 0x04;
  3968. TGATools._ORIGIN_BL = 0x00;
  3969. TGATools._ORIGIN_BR = 0x01;
  3970. TGATools._ORIGIN_UL = 0x02;
  3971. TGATools._ORIGIN_UR = 0x03;
  3972. return TGATools;
  3973. })();
  3974. Internals.TGATools = TGATools;
  3975. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3976. })(BABYLON || (BABYLON = {}));
  3977. var BABYLON;
  3978. (function (BABYLON) {
  3979. var SmartArray = (function () {
  3980. function SmartArray(capacity) {
  3981. this.length = 0;
  3982. this._duplicateId = 0;
  3983. this.data = new Array(capacity);
  3984. this._id = SmartArray._GlobalId++;
  3985. }
  3986. SmartArray.prototype.push = function (value) {
  3987. this.data[this.length++] = value;
  3988. if (this.length > this.data.length) {
  3989. this.data.length *= 2;
  3990. }
  3991. if (!value.__smartArrayFlags) {
  3992. value.__smartArrayFlags = {};
  3993. }
  3994. value.__smartArrayFlags[this._id] = this._duplicateId;
  3995. };
  3996. SmartArray.prototype.pushNoDuplicate = function (value) {
  3997. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3998. return;
  3999. }
  4000. this.push(value);
  4001. };
  4002. SmartArray.prototype.sort = function (compareFn) {
  4003. this.data.sort(compareFn);
  4004. };
  4005. SmartArray.prototype.reset = function () {
  4006. this.length = 0;
  4007. this._duplicateId++;
  4008. };
  4009. SmartArray.prototype.concat = function (array) {
  4010. if (array.length === 0) {
  4011. return;
  4012. }
  4013. if (this.length + array.length > this.data.length) {
  4014. this.data.length = (this.length + array.length) * 2;
  4015. }
  4016. for (var index = 0; index < array.length; index++) {
  4017. this.data[this.length++] = (array.data || array)[index];
  4018. }
  4019. };
  4020. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4021. if (array.length === 0) {
  4022. return;
  4023. }
  4024. if (this.length + array.length > this.data.length) {
  4025. this.data.length = (this.length + array.length) * 2;
  4026. }
  4027. for (var index = 0; index < array.length; index++) {
  4028. var item = (array.data || array)[index];
  4029. this.pushNoDuplicate(item);
  4030. }
  4031. };
  4032. SmartArray.prototype.indexOf = function (value) {
  4033. var position = this.data.indexOf(value);
  4034. if (position >= this.length) {
  4035. return -1;
  4036. }
  4037. return position;
  4038. };
  4039. // Statics
  4040. SmartArray._GlobalId = 0;
  4041. return SmartArray;
  4042. })();
  4043. BABYLON.SmartArray = SmartArray;
  4044. })(BABYLON || (BABYLON = {}));
  4045. var BABYLON;
  4046. (function (BABYLON) {
  4047. var SmartCollection = (function () {
  4048. function SmartCollection(capacity) {
  4049. if (capacity === void 0) { capacity = 10; }
  4050. this.count = 0;
  4051. this._initialCapacity = capacity;
  4052. this.items = {};
  4053. this._keys = new Array(this._initialCapacity);
  4054. }
  4055. SmartCollection.prototype.add = function (key, item) {
  4056. if (this.items[key] != undefined) {
  4057. return -1;
  4058. }
  4059. this.items[key] = item;
  4060. //literal keys are always strings, but we keep source type of key in _keys array
  4061. this._keys[this.count++] = key;
  4062. if (this.count > this._keys.length) {
  4063. this._keys.length *= 2;
  4064. }
  4065. return this.count;
  4066. };
  4067. SmartCollection.prototype.remove = function (key) {
  4068. if (this.items[key] == undefined) {
  4069. return -1;
  4070. }
  4071. return this.removeItemOfIndex(this.indexOf(key));
  4072. };
  4073. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4074. if (index < this.count && index > -1) {
  4075. delete this.items[this._keys[index]];
  4076. //here, shifting by hand is better optimised than .splice
  4077. while (index < this.count) {
  4078. this._keys[index] = this._keys[index + 1];
  4079. index++;
  4080. }
  4081. }
  4082. else {
  4083. return -1;
  4084. }
  4085. return --this.count;
  4086. };
  4087. SmartCollection.prototype.indexOf = function (key) {
  4088. for (var i = 0; i !== this.count; i++) {
  4089. if (this._keys[i] === key) {
  4090. return i;
  4091. }
  4092. }
  4093. return -1;
  4094. };
  4095. SmartCollection.prototype.item = function (key) {
  4096. return this.items[key];
  4097. };
  4098. SmartCollection.prototype.getAllKeys = function () {
  4099. if (this.count > 0) {
  4100. var keys = new Array(this.count);
  4101. for (var i = 0; i < this.count; i++) {
  4102. keys[i] = this._keys[i];
  4103. }
  4104. return keys;
  4105. }
  4106. else {
  4107. return undefined;
  4108. }
  4109. };
  4110. SmartCollection.prototype.getKeyByIndex = function (index) {
  4111. if (index < this.count && index > -1) {
  4112. return this._keys[index];
  4113. }
  4114. else {
  4115. return undefined;
  4116. }
  4117. };
  4118. SmartCollection.prototype.getItemByIndex = function (index) {
  4119. if (index < this.count && index > -1) {
  4120. return this.items[this._keys[index]];
  4121. }
  4122. else {
  4123. return undefined;
  4124. }
  4125. };
  4126. SmartCollection.prototype.empty = function () {
  4127. if (this.count > 0) {
  4128. this.count = 0;
  4129. this.items = {};
  4130. this._keys = new Array(this._initialCapacity);
  4131. }
  4132. };
  4133. SmartCollection.prototype.forEach = function (block) {
  4134. var key;
  4135. for (key in this.items) {
  4136. if (this.items.hasOwnProperty(key)) {
  4137. block(this.items[key]);
  4138. }
  4139. }
  4140. };
  4141. return SmartCollection;
  4142. })();
  4143. BABYLON.SmartCollection = SmartCollection;
  4144. })(BABYLON || (BABYLON = {}));
  4145. var BABYLON;
  4146. (function (BABYLON) {
  4147. // Screenshots
  4148. var screenshotCanvas;
  4149. var cloneValue = function (source, destinationObject) {
  4150. if (!source)
  4151. return null;
  4152. if (source instanceof BABYLON.Mesh) {
  4153. return null;
  4154. }
  4155. if (source instanceof BABYLON.SubMesh) {
  4156. return source.clone(destinationObject);
  4157. }
  4158. else if (source.clone) {
  4159. return source.clone();
  4160. }
  4161. return null;
  4162. };
  4163. var Tools = (function () {
  4164. function Tools() {
  4165. }
  4166. Tools.Instantiate = function (className) {
  4167. var arr = className.split(".");
  4168. var fn = (window || this);
  4169. for (var i = 0, len = arr.length; i < len; i++) {
  4170. fn = fn[arr[i]];
  4171. }
  4172. if (typeof fn !== "function") {
  4173. return null;
  4174. }
  4175. return fn;
  4176. };
  4177. Tools.ToHex = function (i) {
  4178. var str = i.toString(16);
  4179. if (i <= 15) {
  4180. return ("0" + str).toUpperCase();
  4181. }
  4182. return str.toUpperCase();
  4183. };
  4184. Tools.SetImmediate = function (action) {
  4185. if (window.setImmediate) {
  4186. window.setImmediate(action);
  4187. }
  4188. else {
  4189. setTimeout(action, 1);
  4190. }
  4191. };
  4192. Tools.IsExponentOfTwo = function (value) {
  4193. var count = 1;
  4194. do {
  4195. count *= 2;
  4196. } while (count < value);
  4197. return count === value;
  4198. };
  4199. Tools.GetExponentOfTwo = function (value, max) {
  4200. var count = 1;
  4201. do {
  4202. count *= 2;
  4203. } while (count < value);
  4204. if (count > max)
  4205. count = max;
  4206. return count;
  4207. };
  4208. Tools.GetFilename = function (path) {
  4209. var index = path.lastIndexOf("/");
  4210. if (index < 0)
  4211. return path;
  4212. return path.substring(index + 1);
  4213. };
  4214. Tools.GetDOMTextContent = function (element) {
  4215. var result = "";
  4216. var child = element.firstChild;
  4217. while (child) {
  4218. if (child.nodeType === 3) {
  4219. result += child.textContent;
  4220. }
  4221. child = child.nextSibling;
  4222. }
  4223. return result;
  4224. };
  4225. Tools.ToDegrees = function (angle) {
  4226. return angle * 180 / Math.PI;
  4227. };
  4228. Tools.ToRadians = function (angle) {
  4229. return angle * Math.PI / 180;
  4230. };
  4231. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4232. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4233. var output = "";
  4234. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4235. var i = 0;
  4236. var bytes = new Uint8Array(buffer);
  4237. while (i < bytes.length) {
  4238. chr1 = bytes[i++];
  4239. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4240. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4241. enc1 = chr1 >> 2;
  4242. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4243. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4244. enc4 = chr3 & 63;
  4245. if (isNaN(chr2)) {
  4246. enc3 = enc4 = 64;
  4247. }
  4248. else if (isNaN(chr3)) {
  4249. enc4 = 64;
  4250. }
  4251. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4252. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4253. }
  4254. return "data:image/png;base64," + output;
  4255. };
  4256. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4257. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4258. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4259. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4260. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4261. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4262. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4263. }
  4264. return {
  4265. minimum: minimum,
  4266. maximum: maximum
  4267. };
  4268. };
  4269. Tools.ExtractMinAndMax = function (positions, start, count) {
  4270. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4271. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4272. for (var index = start; index < start + count; index++) {
  4273. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4274. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4275. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4276. }
  4277. return {
  4278. minimum: minimum,
  4279. maximum: maximum
  4280. };
  4281. };
  4282. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4283. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4284. return undefined;
  4285. return Array.isArray(obj) ? obj : [obj];
  4286. };
  4287. // Misc.
  4288. Tools.GetPointerPrefix = function () {
  4289. var eventPrefix = "pointer";
  4290. // Check if pointer events are supported
  4291. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4292. eventPrefix = "mouse";
  4293. }
  4294. return eventPrefix;
  4295. };
  4296. Tools.QueueNewFrame = function (func) {
  4297. if (window.requestAnimationFrame)
  4298. window.requestAnimationFrame(func);
  4299. else if (window.msRequestAnimationFrame)
  4300. window.msRequestAnimationFrame(func);
  4301. else if (window.webkitRequestAnimationFrame)
  4302. window.webkitRequestAnimationFrame(func);
  4303. else if (window.mozRequestAnimationFrame)
  4304. window.mozRequestAnimationFrame(func);
  4305. else if (window.oRequestAnimationFrame)
  4306. window.oRequestAnimationFrame(func);
  4307. else {
  4308. window.setTimeout(func, 16);
  4309. }
  4310. };
  4311. Tools.RequestFullscreen = function (element) {
  4312. if (element.requestFullscreen)
  4313. element.requestFullscreen();
  4314. else if (element.msRequestFullscreen)
  4315. element.msRequestFullscreen();
  4316. else if (element.webkitRequestFullscreen)
  4317. element.webkitRequestFullscreen();
  4318. else if (element.mozRequestFullScreen)
  4319. element.mozRequestFullScreen();
  4320. };
  4321. Tools.ExitFullscreen = function () {
  4322. if (document.exitFullscreen) {
  4323. document.exitFullscreen();
  4324. }
  4325. else if (document.mozCancelFullScreen) {
  4326. document.mozCancelFullScreen();
  4327. }
  4328. else if (document.webkitCancelFullScreen) {
  4329. document.webkitCancelFullScreen();
  4330. }
  4331. else if (document.msCancelFullScreen) {
  4332. document.msCancelFullScreen();
  4333. }
  4334. };
  4335. // External files
  4336. Tools.CleanUrl = function (url) {
  4337. url = url.replace(/#/mg, "%23");
  4338. return url;
  4339. };
  4340. Tools.LoadImage = function (url, onload, onerror, database) {
  4341. if (url instanceof ArrayBuffer) {
  4342. url = Tools.EncodeArrayBufferTobase64(url);
  4343. }
  4344. url = Tools.CleanUrl(url);
  4345. var img = new Image();
  4346. if (url.substr(0, 5) !== "data:") {
  4347. if (Tools.CorsBehavior) {
  4348. switch (typeof (Tools.CorsBehavior)) {
  4349. case "function":
  4350. var result = Tools.CorsBehavior(url);
  4351. if (result) {
  4352. img.crossOrigin = result;
  4353. }
  4354. break;
  4355. case "string":
  4356. default:
  4357. img.crossOrigin = Tools.CorsBehavior;
  4358. break;
  4359. }
  4360. }
  4361. }
  4362. img.onload = function () {
  4363. onload(img);
  4364. };
  4365. img.onerror = function (err) {
  4366. Tools.Error("Error while trying to load texture: " + url);
  4367. if (Tools.UseFallbackTexture) {
  4368. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4369. onload(img);
  4370. }
  4371. else {
  4372. onerror();
  4373. }
  4374. };
  4375. var noIndexedDB = function () {
  4376. img.src = url;
  4377. };
  4378. var loadFromIndexedDB = function () {
  4379. database.loadImageFromDB(url, img);
  4380. };
  4381. //ANY database to do!
  4382. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4383. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4384. }
  4385. else {
  4386. if (url.indexOf("file:") === -1) {
  4387. noIndexedDB();
  4388. }
  4389. else {
  4390. try {
  4391. var textureName = url.substring(5);
  4392. var blobURL;
  4393. try {
  4394. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4395. }
  4396. catch (ex) {
  4397. // Chrome doesn't support oneTimeOnly parameter
  4398. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4399. }
  4400. img.src = blobURL;
  4401. }
  4402. catch (e) {
  4403. img.src = null;
  4404. }
  4405. }
  4406. }
  4407. return img;
  4408. };
  4409. //ANY
  4410. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4411. url = Tools.CleanUrl(url);
  4412. var noIndexedDB = function () {
  4413. var request = new XMLHttpRequest();
  4414. var loadUrl = Tools.BaseUrl + url;
  4415. request.open('GET', loadUrl, true);
  4416. if (useArrayBuffer) {
  4417. request.responseType = "arraybuffer";
  4418. }
  4419. request.onprogress = progressCallBack;
  4420. request.onreadystatechange = function () {
  4421. if (request.readyState === 4) {
  4422. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4423. callback(!useArrayBuffer ? request.responseText : request.response);
  4424. }
  4425. else {
  4426. if (onError) {
  4427. onError();
  4428. }
  4429. else {
  4430. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4431. }
  4432. }
  4433. }
  4434. };
  4435. request.send(null);
  4436. };
  4437. var loadFromIndexedDB = function () {
  4438. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4439. };
  4440. if (url.indexOf("file:") !== -1) {
  4441. var fileName = url.substring(5);
  4442. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4443. }
  4444. else {
  4445. // Caching all files
  4446. if (database && database.enableSceneOffline) {
  4447. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4448. }
  4449. else {
  4450. noIndexedDB();
  4451. }
  4452. }
  4453. };
  4454. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4455. var reader = new FileReader();
  4456. reader.onload = function (e) {
  4457. //target doesn't have result from ts 1.3
  4458. callback(e.target['result']);
  4459. };
  4460. reader.onprogress = progressCallback;
  4461. reader.readAsDataURL(fileToLoad);
  4462. };
  4463. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4464. var reader = new FileReader();
  4465. reader.onerror = function (e) {
  4466. Tools.Log("Error while reading file: " + fileToLoad.name);
  4467. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4468. };
  4469. reader.onload = function (e) {
  4470. //target doesn't have result from ts 1.3
  4471. callback(e.target['result']);
  4472. };
  4473. reader.onprogress = progressCallBack;
  4474. if (!useArrayBuffer) {
  4475. // Asynchronous read
  4476. reader.readAsText(fileToLoad);
  4477. }
  4478. else {
  4479. reader.readAsArrayBuffer(fileToLoad);
  4480. }
  4481. };
  4482. //returns a downloadable url to a file content.
  4483. Tools.FileAsURL = function (content) {
  4484. var fileBlob = new Blob([content]);
  4485. var url = window.URL || window.webkitURL;
  4486. var link = url.createObjectURL(fileBlob);
  4487. return link;
  4488. };
  4489. // Misc.
  4490. Tools.Clamp = function (value, min, max) {
  4491. if (min === void 0) { min = 0; }
  4492. if (max === void 0) { max = 1; }
  4493. return Math.min(max, Math.max(min, value));
  4494. };
  4495. // Returns -1 when value is a negative number and
  4496. // +1 when value is a positive number.
  4497. Tools.Sign = function (value) {
  4498. value = +value; // convert to a number
  4499. if (value === 0 || isNaN(value))
  4500. return value;
  4501. return value > 0 ? 1 : -1;
  4502. };
  4503. Tools.Format = function (value, decimals) {
  4504. if (decimals === void 0) { decimals = 2; }
  4505. return value.toFixed(decimals);
  4506. };
  4507. Tools.CheckExtends = function (v, min, max) {
  4508. if (v.x < min.x)
  4509. min.x = v.x;
  4510. if (v.y < min.y)
  4511. min.y = v.y;
  4512. if (v.z < min.z)
  4513. min.z = v.z;
  4514. if (v.x > max.x)
  4515. max.x = v.x;
  4516. if (v.y > max.y)
  4517. max.y = v.y;
  4518. if (v.z > max.z)
  4519. max.z = v.z;
  4520. };
  4521. Tools.WithinEpsilon = function (a, b, epsilon) {
  4522. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4523. var num = a - b;
  4524. return -epsilon <= num && num <= epsilon;
  4525. };
  4526. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4527. for (var prop in source) {
  4528. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4529. continue;
  4530. }
  4531. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4532. continue;
  4533. }
  4534. var sourceValue = source[prop];
  4535. var typeOfSourceValue = typeof sourceValue;
  4536. if (typeOfSourceValue === "function") {
  4537. continue;
  4538. }
  4539. if (typeOfSourceValue === "object") {
  4540. if (sourceValue instanceof Array) {
  4541. destination[prop] = [];
  4542. if (sourceValue.length > 0) {
  4543. if (typeof sourceValue[0] == "object") {
  4544. for (var index = 0; index < sourceValue.length; index++) {
  4545. var clonedValue = cloneValue(sourceValue[index], destination);
  4546. if (destination[prop].indexOf(clonedValue) === -1) {
  4547. destination[prop].push(clonedValue);
  4548. }
  4549. }
  4550. }
  4551. else {
  4552. destination[prop] = sourceValue.slice(0);
  4553. }
  4554. }
  4555. }
  4556. else {
  4557. destination[prop] = cloneValue(sourceValue, destination);
  4558. }
  4559. }
  4560. else {
  4561. destination[prop] = sourceValue;
  4562. }
  4563. }
  4564. };
  4565. Tools.IsEmpty = function (obj) {
  4566. for (var i in obj) {
  4567. return false;
  4568. }
  4569. return true;
  4570. };
  4571. Tools.RegisterTopRootEvents = function (events) {
  4572. for (var index = 0; index < events.length; index++) {
  4573. var event = events[index];
  4574. window.addEventListener(event.name, event.handler, false);
  4575. try {
  4576. if (window.parent) {
  4577. window.parent.addEventListener(event.name, event.handler, false);
  4578. }
  4579. }
  4580. catch (e) {
  4581. }
  4582. }
  4583. };
  4584. Tools.UnregisterTopRootEvents = function (events) {
  4585. for (var index = 0; index < events.length; index++) {
  4586. var event = events[index];
  4587. window.removeEventListener(event.name, event.handler);
  4588. try {
  4589. if (window.parent) {
  4590. window.parent.removeEventListener(event.name, event.handler);
  4591. }
  4592. }
  4593. catch (e) {
  4594. }
  4595. }
  4596. };
  4597. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4598. // Read the contents of the framebuffer
  4599. var numberOfChannelsByLine = width * 4;
  4600. var halfHeight = height / 2;
  4601. //Reading datas from WebGL
  4602. var data = engine.readPixels(0, 0, width, height);
  4603. //To flip image on Y axis.
  4604. for (var i = 0; i < halfHeight; i++) {
  4605. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4606. var currentCell = j + i * numberOfChannelsByLine;
  4607. var targetLine = height - i - 1;
  4608. var targetCell = j + targetLine * numberOfChannelsByLine;
  4609. var temp = data[currentCell];
  4610. data[currentCell] = data[targetCell];
  4611. data[targetCell] = temp;
  4612. }
  4613. }
  4614. // Create a 2D canvas to store the result
  4615. if (!screenshotCanvas) {
  4616. screenshotCanvas = document.createElement('canvas');
  4617. }
  4618. screenshotCanvas.width = width;
  4619. screenshotCanvas.height = height;
  4620. var context = screenshotCanvas.getContext('2d');
  4621. // Copy the pixels to a 2D canvas
  4622. var imageData = context.createImageData(width, height);
  4623. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4624. var castData = imageData.data;
  4625. castData.set(data);
  4626. context.putImageData(imageData, 0, 0);
  4627. var base64Image = screenshotCanvas.toDataURL();
  4628. if (successCallback) {
  4629. successCallback(base64Image);
  4630. }
  4631. else {
  4632. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4633. if (("download" in document.createElement("a"))) {
  4634. var a = window.document.createElement("a");
  4635. a.href = base64Image;
  4636. var date = new Date();
  4637. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4638. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4639. window.document.body.appendChild(a);
  4640. a.addEventListener("click", function () {
  4641. a.parentElement.removeChild(a);
  4642. });
  4643. a.click();
  4644. }
  4645. else {
  4646. var newWindow = window.open("");
  4647. var img = newWindow.document.createElement("img");
  4648. img.src = base64Image;
  4649. newWindow.document.body.appendChild(img);
  4650. }
  4651. }
  4652. };
  4653. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4654. var width;
  4655. var height;
  4656. //If a precision value is specified
  4657. if (size.precision) {
  4658. width = Math.round(engine.getRenderWidth() * size.precision);
  4659. height = Math.round(width / engine.getAspectRatio(camera));
  4660. size = { width: width, height: height };
  4661. }
  4662. else if (size.width && size.height) {
  4663. width = size.width;
  4664. height = size.height;
  4665. }
  4666. else if (size.width && !size.height) {
  4667. width = size.width;
  4668. height = Math.round(width / engine.getAspectRatio(camera));
  4669. size = { width: width, height: height };
  4670. }
  4671. else if (size.height && !size.width) {
  4672. height = size.height;
  4673. width = Math.round(height * engine.getAspectRatio(camera));
  4674. size = { width: width, height: height };
  4675. }
  4676. else if (!isNaN(size)) {
  4677. height = size;
  4678. width = size;
  4679. }
  4680. else {
  4681. Tools.Error("Invalid 'size' parameter !");
  4682. return;
  4683. }
  4684. var scene = camera.getScene();
  4685. var previousCamera = null;
  4686. if (scene.activeCamera !== camera) {
  4687. previousCamera = scene.activeCamera;
  4688. scene.activeCamera = camera;
  4689. }
  4690. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4691. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4692. texture.renderList = scene.meshes;
  4693. texture.onAfterRender = function () {
  4694. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4695. };
  4696. scene.incrementRenderId();
  4697. texture.render(true);
  4698. texture.dispose();
  4699. if (previousCamera) {
  4700. scene.activeCamera = previousCamera;
  4701. }
  4702. camera.getProjectionMatrix(true); // Force cache refresh;
  4703. };
  4704. // XHR response validator for local file scenario
  4705. Tools.ValidateXHRData = function (xhr, dataType) {
  4706. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4707. if (dataType === void 0) { dataType = 7; }
  4708. try {
  4709. if (dataType & 1) {
  4710. if (xhr.responseText && xhr.responseText.length > 0) {
  4711. return true;
  4712. }
  4713. else if (dataType === 1) {
  4714. return false;
  4715. }
  4716. }
  4717. if (dataType & 2) {
  4718. // Check header width and height since there is no "TGA" magic number
  4719. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4720. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4721. return true;
  4722. }
  4723. else if (dataType === 2) {
  4724. return false;
  4725. }
  4726. }
  4727. if (dataType & 4) {
  4728. // Check for the "DDS" magic number
  4729. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4730. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4731. return true;
  4732. }
  4733. else {
  4734. return false;
  4735. }
  4736. }
  4737. }
  4738. catch (e) {
  4739. }
  4740. return false;
  4741. };
  4742. Object.defineProperty(Tools, "NoneLogLevel", {
  4743. get: function () {
  4744. return Tools._NoneLogLevel;
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Object.defineProperty(Tools, "MessageLogLevel", {
  4750. get: function () {
  4751. return Tools._MessageLogLevel;
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "WarningLogLevel", {
  4757. get: function () {
  4758. return Tools._WarningLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "ErrorLogLevel", {
  4764. get: function () {
  4765. return Tools._ErrorLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "AllLogLevel", {
  4771. get: function () {
  4772. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Tools._AddLogEntry = function (entry) {
  4778. Tools._LogCache = entry + Tools._LogCache;
  4779. if (Tools.OnNewCacheEntry) {
  4780. Tools.OnNewCacheEntry(entry);
  4781. }
  4782. };
  4783. Tools._FormatMessage = function (message) {
  4784. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4785. var date = new Date();
  4786. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4787. };
  4788. Tools._LogDisabled = function (message) {
  4789. // nothing to do
  4790. };
  4791. Tools._LogEnabled = function (message) {
  4792. var formattedMessage = Tools._FormatMessage(message);
  4793. console.log("BJS - " + formattedMessage);
  4794. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4795. Tools._AddLogEntry(entry);
  4796. };
  4797. Tools._WarnDisabled = function (message) {
  4798. // nothing to do
  4799. };
  4800. Tools._WarnEnabled = function (message) {
  4801. var formattedMessage = Tools._FormatMessage(message);
  4802. console.warn("BJS - " + formattedMessage);
  4803. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4804. Tools._AddLogEntry(entry);
  4805. };
  4806. Tools._ErrorDisabled = function (message) {
  4807. // nothing to do
  4808. };
  4809. Tools._ErrorEnabled = function (message) {
  4810. Tools.errorsCount++;
  4811. var formattedMessage = Tools._FormatMessage(message);
  4812. console.error("BJS - " + formattedMessage);
  4813. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4814. Tools._AddLogEntry(entry);
  4815. };
  4816. Object.defineProperty(Tools, "LogCache", {
  4817. get: function () {
  4818. return Tools._LogCache;
  4819. },
  4820. enumerable: true,
  4821. configurable: true
  4822. });
  4823. Tools.ClearLogCache = function () {
  4824. Tools._LogCache = "";
  4825. Tools.errorsCount = 0;
  4826. };
  4827. Object.defineProperty(Tools, "LogLevels", {
  4828. set: function (level) {
  4829. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4830. Tools.Log = Tools._LogEnabled;
  4831. }
  4832. else {
  4833. Tools.Log = Tools._LogDisabled;
  4834. }
  4835. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4836. Tools.Warn = Tools._WarnEnabled;
  4837. }
  4838. else {
  4839. Tools.Warn = Tools._WarnDisabled;
  4840. }
  4841. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4842. Tools.Error = Tools._ErrorEnabled;
  4843. }
  4844. else {
  4845. Tools.Error = Tools._ErrorDisabled;
  4846. }
  4847. },
  4848. enumerable: true,
  4849. configurable: true
  4850. });
  4851. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4852. get: function () {
  4853. return Tools._PerformanceNoneLogLevel;
  4854. },
  4855. enumerable: true,
  4856. configurable: true
  4857. });
  4858. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4859. get: function () {
  4860. return Tools._PerformanceUserMarkLogLevel;
  4861. },
  4862. enumerable: true,
  4863. configurable: true
  4864. });
  4865. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4866. get: function () {
  4867. return Tools._PerformanceConsoleLogLevel;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4873. set: function (level) {
  4874. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4875. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4876. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4877. return;
  4878. }
  4879. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4880. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4881. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4882. return;
  4883. }
  4884. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4885. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4886. },
  4887. enumerable: true,
  4888. configurable: true
  4889. });
  4890. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4891. };
  4892. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4893. };
  4894. Tools._StartUserMark = function (counterName, condition) {
  4895. if (condition === void 0) { condition = true; }
  4896. if (!condition || !Tools._performance.mark) {
  4897. return;
  4898. }
  4899. Tools._performance.mark(counterName + "-Begin");
  4900. };
  4901. Tools._EndUserMark = function (counterName, condition) {
  4902. if (condition === void 0) { condition = true; }
  4903. if (!condition || !Tools._performance.mark) {
  4904. return;
  4905. }
  4906. Tools._performance.mark(counterName + "-End");
  4907. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4908. };
  4909. Tools._StartPerformanceConsole = function (counterName, condition) {
  4910. if (condition === void 0) { condition = true; }
  4911. if (!condition) {
  4912. return;
  4913. }
  4914. Tools._StartUserMark(counterName, condition);
  4915. if (console.time) {
  4916. console.time(counterName);
  4917. }
  4918. };
  4919. Tools._EndPerformanceConsole = function (counterName, condition) {
  4920. if (condition === void 0) { condition = true; }
  4921. if (!condition) {
  4922. return;
  4923. }
  4924. Tools._EndUserMark(counterName, condition);
  4925. if (console.time) {
  4926. console.timeEnd(counterName);
  4927. }
  4928. };
  4929. Object.defineProperty(Tools, "Now", {
  4930. get: function () {
  4931. if (window.performance && window.performance.now) {
  4932. return window.performance.now();
  4933. }
  4934. return new Date().getTime();
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. Tools.BaseUrl = "";
  4940. Tools.CorsBehavior = "anonymous";
  4941. Tools.UseFallbackTexture = true;
  4942. // Logs
  4943. Tools._NoneLogLevel = 0;
  4944. Tools._MessageLogLevel = 1;
  4945. Tools._WarningLogLevel = 2;
  4946. Tools._ErrorLogLevel = 4;
  4947. Tools._LogCache = "";
  4948. Tools.errorsCount = 0;
  4949. Tools.Log = Tools._LogEnabled;
  4950. Tools.Warn = Tools._WarnEnabled;
  4951. Tools.Error = Tools._ErrorEnabled;
  4952. // Performances
  4953. Tools._PerformanceNoneLogLevel = 0;
  4954. Tools._PerformanceUserMarkLogLevel = 1;
  4955. Tools._PerformanceConsoleLogLevel = 2;
  4956. Tools._performance = window.performance;
  4957. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4958. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4959. return Tools;
  4960. })();
  4961. BABYLON.Tools = Tools;
  4962. /**
  4963. * An implementation of a loop for asynchronous functions.
  4964. */
  4965. var AsyncLoop = (function () {
  4966. /**
  4967. * Constroctor.
  4968. * @param iterations the number of iterations.
  4969. * @param _fn the function to run each iteration
  4970. * @param _successCallback the callback that will be called upon succesful execution
  4971. * @param offset starting offset.
  4972. */
  4973. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4974. if (offset === void 0) { offset = 0; }
  4975. this.iterations = iterations;
  4976. this._fn = _fn;
  4977. this._successCallback = _successCallback;
  4978. this.index = offset - 1;
  4979. this._done = false;
  4980. }
  4981. /**
  4982. * Execute the next iteration. Must be called after the last iteration was finished.
  4983. */
  4984. AsyncLoop.prototype.executeNext = function () {
  4985. if (!this._done) {
  4986. if (this.index + 1 < this.iterations) {
  4987. ++this.index;
  4988. this._fn(this);
  4989. }
  4990. else {
  4991. this.breakLoop();
  4992. }
  4993. }
  4994. };
  4995. /**
  4996. * Break the loop and run the success callback.
  4997. */
  4998. AsyncLoop.prototype.breakLoop = function () {
  4999. this._done = true;
  5000. this._successCallback();
  5001. };
  5002. /**
  5003. * Helper function
  5004. */
  5005. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5006. if (offset === void 0) { offset = 0; }
  5007. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5008. loop.executeNext();
  5009. return loop;
  5010. };
  5011. /**
  5012. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5013. * @param iterations total number of iterations
  5014. * @param syncedIterations number of synchronous iterations in each async iteration.
  5015. * @param fn the function to call each iteration.
  5016. * @param callback a success call back that will be called when iterating stops.
  5017. * @param breakFunction a break condition (optional)
  5018. * @param timeout timeout settings for the setTimeout function. default - 0.
  5019. * @constructor
  5020. */
  5021. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5022. if (timeout === void 0) { timeout = 0; }
  5023. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5024. if (breakFunction && breakFunction())
  5025. loop.breakLoop();
  5026. else {
  5027. setTimeout(function () {
  5028. for (var i = 0; i < syncedIterations; ++i) {
  5029. var iteration = (loop.index * syncedIterations) + i;
  5030. if (iteration >= iterations)
  5031. break;
  5032. fn(iteration);
  5033. if (breakFunction && breakFunction()) {
  5034. loop.breakLoop();
  5035. break;
  5036. }
  5037. }
  5038. loop.executeNext();
  5039. }, timeout);
  5040. }
  5041. }, callback);
  5042. };
  5043. return AsyncLoop;
  5044. })();
  5045. BABYLON.AsyncLoop = AsyncLoop;
  5046. })(BABYLON || (BABYLON = {}));
  5047. var BABYLON;
  5048. (function (BABYLON) {
  5049. var Internals;
  5050. (function (Internals) {
  5051. var _AlphaState = (function () {
  5052. function _AlphaState() {
  5053. this._isAlphaBlendDirty = false;
  5054. this._isBlendFunctionParametersDirty = false;
  5055. this._alphaBlend = false;
  5056. this._blendFunctionParameters = new Array(4);
  5057. }
  5058. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5059. get: function () {
  5060. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5061. },
  5062. enumerable: true,
  5063. configurable: true
  5064. });
  5065. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5066. get: function () {
  5067. return this._alphaBlend;
  5068. },
  5069. set: function (value) {
  5070. if (this._alphaBlend === value) {
  5071. return;
  5072. }
  5073. this._alphaBlend = value;
  5074. this._isAlphaBlendDirty = true;
  5075. },
  5076. enumerable: true,
  5077. configurable: true
  5078. });
  5079. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5080. if (this._blendFunctionParameters[0] === value0 &&
  5081. this._blendFunctionParameters[1] === value1 &&
  5082. this._blendFunctionParameters[2] === value2 &&
  5083. this._blendFunctionParameters[3] === value3) {
  5084. return;
  5085. }
  5086. this._blendFunctionParameters[0] = value0;
  5087. this._blendFunctionParameters[1] = value1;
  5088. this._blendFunctionParameters[2] = value2;
  5089. this._blendFunctionParameters[3] = value3;
  5090. this._isBlendFunctionParametersDirty = true;
  5091. };
  5092. _AlphaState.prototype.reset = function () {
  5093. this._alphaBlend = false;
  5094. this._blendFunctionParameters[0] = null;
  5095. this._blendFunctionParameters[1] = null;
  5096. this._blendFunctionParameters[2] = null;
  5097. this._blendFunctionParameters[3] = null;
  5098. this._isAlphaBlendDirty = true;
  5099. this._isBlendFunctionParametersDirty = false;
  5100. };
  5101. _AlphaState.prototype.apply = function (gl) {
  5102. if (!this.isDirty) {
  5103. return;
  5104. }
  5105. // Alpha blend
  5106. if (this._isAlphaBlendDirty) {
  5107. if (this._alphaBlend) {
  5108. gl.enable(gl.BLEND);
  5109. }
  5110. else {
  5111. gl.disable(gl.BLEND);
  5112. }
  5113. this._isAlphaBlendDirty = false;
  5114. }
  5115. // Alpha function
  5116. if (this._isBlendFunctionParametersDirty) {
  5117. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5118. this._isBlendFunctionParametersDirty = false;
  5119. }
  5120. };
  5121. return _AlphaState;
  5122. })();
  5123. Internals._AlphaState = _AlphaState;
  5124. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5125. })(BABYLON || (BABYLON = {}));
  5126. var BABYLON;
  5127. (function (BABYLON) {
  5128. var Internals;
  5129. (function (Internals) {
  5130. var _DepthCullingState = (function () {
  5131. function _DepthCullingState() {
  5132. this._isDepthTestDirty = false;
  5133. this._isDepthMaskDirty = false;
  5134. this._isDepthFuncDirty = false;
  5135. this._isCullFaceDirty = false;
  5136. this._isCullDirty = false;
  5137. this._isZOffsetDirty = false;
  5138. }
  5139. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5140. get: function () {
  5141. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5142. },
  5143. enumerable: true,
  5144. configurable: true
  5145. });
  5146. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5147. get: function () {
  5148. return this._zOffset;
  5149. },
  5150. set: function (value) {
  5151. if (this._zOffset === value) {
  5152. return;
  5153. }
  5154. this._zOffset = value;
  5155. this._isZOffsetDirty = true;
  5156. },
  5157. enumerable: true,
  5158. configurable: true
  5159. });
  5160. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5161. get: function () {
  5162. return this._cullFace;
  5163. },
  5164. set: function (value) {
  5165. if (this._cullFace === value) {
  5166. return;
  5167. }
  5168. this._cullFace = value;
  5169. this._isCullFaceDirty = true;
  5170. },
  5171. enumerable: true,
  5172. configurable: true
  5173. });
  5174. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5175. get: function () {
  5176. return this._cull;
  5177. },
  5178. set: function (value) {
  5179. if (this._cull === value) {
  5180. return;
  5181. }
  5182. this._cull = value;
  5183. this._isCullDirty = true;
  5184. },
  5185. enumerable: true,
  5186. configurable: true
  5187. });
  5188. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5189. get: function () {
  5190. return this._depthFunc;
  5191. },
  5192. set: function (value) {
  5193. if (this._depthFunc === value) {
  5194. return;
  5195. }
  5196. this._depthFunc = value;
  5197. this._isDepthFuncDirty = true;
  5198. },
  5199. enumerable: true,
  5200. configurable: true
  5201. });
  5202. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5203. get: function () {
  5204. return this._depthMask;
  5205. },
  5206. set: function (value) {
  5207. if (this._depthMask === value) {
  5208. return;
  5209. }
  5210. this._depthMask = value;
  5211. this._isDepthMaskDirty = true;
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5217. get: function () {
  5218. return this._depthTest;
  5219. },
  5220. set: function (value) {
  5221. if (this._depthTest === value) {
  5222. return;
  5223. }
  5224. this._depthTest = value;
  5225. this._isDepthTestDirty = true;
  5226. },
  5227. enumerable: true,
  5228. configurable: true
  5229. });
  5230. _DepthCullingState.prototype.reset = function () {
  5231. this._depthMask = true;
  5232. this._depthTest = true;
  5233. this._depthFunc = null;
  5234. this._cull = null;
  5235. this._cullFace = null;
  5236. this._zOffset = 0;
  5237. this._isDepthTestDirty = true;
  5238. this._isDepthMaskDirty = true;
  5239. this._isDepthFuncDirty = false;
  5240. this._isCullFaceDirty = false;
  5241. this._isCullDirty = false;
  5242. this._isZOffsetDirty = false;
  5243. };
  5244. _DepthCullingState.prototype.apply = function (gl) {
  5245. if (!this.isDirty) {
  5246. return;
  5247. }
  5248. // Cull
  5249. if (this._isCullDirty) {
  5250. if (this.cull) {
  5251. gl.enable(gl.CULL_FACE);
  5252. }
  5253. else {
  5254. gl.disable(gl.CULL_FACE);
  5255. }
  5256. this._isCullDirty = false;
  5257. }
  5258. // Cull face
  5259. if (this._isCullFaceDirty) {
  5260. gl.cullFace(this.cullFace);
  5261. this._isCullFaceDirty = false;
  5262. }
  5263. // Depth mask
  5264. if (this._isDepthMaskDirty) {
  5265. gl.depthMask(this.depthMask);
  5266. this._isDepthMaskDirty = false;
  5267. }
  5268. // Depth test
  5269. if (this._isDepthTestDirty) {
  5270. if (this.depthTest) {
  5271. gl.enable(gl.DEPTH_TEST);
  5272. }
  5273. else {
  5274. gl.disable(gl.DEPTH_TEST);
  5275. }
  5276. this._isDepthTestDirty = false;
  5277. }
  5278. // Depth func
  5279. if (this._isDepthFuncDirty) {
  5280. gl.depthFunc(this.depthFunc);
  5281. this._isDepthFuncDirty = false;
  5282. }
  5283. // zOffset
  5284. if (this._isZOffsetDirty) {
  5285. if (this.zOffset) {
  5286. gl.enable(gl.POLYGON_OFFSET_FILL);
  5287. gl.polygonOffset(this.zOffset, 0);
  5288. }
  5289. else {
  5290. gl.disable(gl.POLYGON_OFFSET_FILL);
  5291. }
  5292. this._isZOffsetDirty = false;
  5293. }
  5294. };
  5295. return _DepthCullingState;
  5296. })();
  5297. Internals._DepthCullingState = _DepthCullingState;
  5298. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5299. })(BABYLON || (BABYLON = {}));
  5300. var BABYLON;
  5301. (function (BABYLON) {
  5302. var compileShader = function (gl, source, type, defines) {
  5303. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5304. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5305. gl.compileShader(shader);
  5306. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5307. throw new Error(gl.getShaderInfoLog(shader));
  5308. }
  5309. return shader;
  5310. };
  5311. var getWebGLTextureType = function (gl, type) {
  5312. var textureType = gl.UNSIGNED_BYTE;
  5313. if (type === Engine.TEXTURETYPE_FLOAT)
  5314. textureType = gl.FLOAT;
  5315. return textureType;
  5316. };
  5317. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5318. var magFilter = gl.NEAREST;
  5319. var minFilter = gl.NEAREST;
  5320. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5321. magFilter = gl.LINEAR;
  5322. if (generateMipMaps) {
  5323. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5324. }
  5325. else {
  5326. minFilter = gl.LINEAR;
  5327. }
  5328. }
  5329. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5330. magFilter = gl.LINEAR;
  5331. if (generateMipMaps) {
  5332. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5333. }
  5334. else {
  5335. minFilter = gl.LINEAR;
  5336. }
  5337. }
  5338. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5339. magFilter = gl.NEAREST;
  5340. if (generateMipMaps) {
  5341. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5342. }
  5343. else {
  5344. minFilter = gl.NEAREST;
  5345. }
  5346. }
  5347. return {
  5348. min: minFilter,
  5349. mag: magFilter
  5350. };
  5351. };
  5352. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5354. var engine = scene.getEngine();
  5355. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5356. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5357. gl.bindTexture(gl.TEXTURE_2D, texture);
  5358. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5359. texture._baseWidth = width;
  5360. texture._baseHeight = height;
  5361. texture._width = potWidth;
  5362. texture._height = potHeight;
  5363. texture.isReady = true;
  5364. processFunction(potWidth, potHeight);
  5365. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5368. if (!noMipmap && !isCompressed) {
  5369. gl.generateMipmap(gl.TEXTURE_2D);
  5370. }
  5371. gl.bindTexture(gl.TEXTURE_2D, null);
  5372. engine.resetTextureCache();
  5373. scene._removePendingData(texture);
  5374. if (onLoad) {
  5375. onLoad();
  5376. }
  5377. };
  5378. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5379. var img;
  5380. var onload = function () {
  5381. loadedImages[index] = img;
  5382. loadedImages._internalCount++;
  5383. scene._removePendingData(img);
  5384. if (loadedImages._internalCount === 6) {
  5385. onfinish(loadedImages);
  5386. }
  5387. };
  5388. var onerror = function () {
  5389. scene._removePendingData(img);
  5390. };
  5391. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5392. scene._addPendingData(img);
  5393. };
  5394. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5395. var loadedImages = [];
  5396. loadedImages._internalCount = 0;
  5397. for (var index = 0; index < 6; index++) {
  5398. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5399. }
  5400. };
  5401. var EngineCapabilities = (function () {
  5402. function EngineCapabilities() {
  5403. }
  5404. return EngineCapabilities;
  5405. })();
  5406. BABYLON.EngineCapabilities = EngineCapabilities;
  5407. /**
  5408. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5409. */
  5410. var Engine = (function () {
  5411. /**
  5412. * @constructor
  5413. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5414. * @param {boolean} [antialias] - enable antialias
  5415. * @param options - further options to be sent to the getContext function
  5416. */
  5417. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5418. var _this = this;
  5419. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5420. // Public members
  5421. this.isFullscreen = false;
  5422. this.isPointerLock = false;
  5423. this.cullBackFaces = true;
  5424. this.renderEvenInBackground = true;
  5425. // To enable/disable IDB support and avoid XHR on .manifest
  5426. this.enableOfflineSupport = true;
  5427. this.scenes = new Array();
  5428. this._windowIsBackground = false;
  5429. this._webGLVersion = "1.0";
  5430. this._drawCalls = 0;
  5431. this._renderingQueueLaunched = false;
  5432. this._activeRenderLoops = [];
  5433. // FPS
  5434. this.fpsRange = 60;
  5435. this.previousFramesDuration = [];
  5436. this.fps = 60;
  5437. this.deltaTime = 0;
  5438. // States
  5439. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5440. this._alphaState = new BABYLON.Internals._AlphaState();
  5441. this._alphaMode = Engine.ALPHA_DISABLE;
  5442. // Cache
  5443. this._loadedTexturesCache = new Array();
  5444. this._maxTextureChannels = 16;
  5445. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5446. this._compiledEffects = {};
  5447. this._uintIndicesCurrentlySet = false;
  5448. this._renderingCanvas = canvas;
  5449. options = options || {};
  5450. options.antialias = antialias;
  5451. if (options.preserveDrawingBuffer === undefined) {
  5452. options.preserveDrawingBuffer = false;
  5453. }
  5454. // GL
  5455. //try {
  5456. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5457. // if (this._gl) {
  5458. // this._webGLVersion = "2.0";
  5459. // }
  5460. //} catch (e) {
  5461. // // Do nothing
  5462. //}
  5463. if (!this._gl) {
  5464. try {
  5465. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5466. }
  5467. catch (e) {
  5468. throw new Error("WebGL not supported");
  5469. }
  5470. }
  5471. if (!this._gl) {
  5472. throw new Error("WebGL not supported");
  5473. }
  5474. this._onBlur = function () {
  5475. _this._windowIsBackground = true;
  5476. };
  5477. this._onFocus = function () {
  5478. _this._windowIsBackground = false;
  5479. };
  5480. window.addEventListener("blur", this._onBlur);
  5481. window.addEventListener("focus", this._onFocus);
  5482. // Viewport
  5483. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5484. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5485. this.resize();
  5486. // Caps
  5487. this._caps = new EngineCapabilities();
  5488. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5489. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5490. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5491. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5492. // Infos
  5493. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5494. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5495. if (rendererInfo != null) {
  5496. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5497. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5498. }
  5499. if (!this._glVendor) {
  5500. this._glVendor = "Unknown vendor";
  5501. }
  5502. if (!this._glRenderer) {
  5503. this._glRenderer = "Unknown renderer";
  5504. }
  5505. // Extensions
  5506. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5507. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5508. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5509. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5510. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5511. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5512. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5513. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5514. this._caps.highPrecisionShaderSupported = true;
  5515. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5516. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5517. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5518. if (this._gl.getShaderPrecisionFormat) {
  5519. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5520. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5521. }
  5522. // Depth buffer
  5523. this.setDepthBuffer(true);
  5524. this.setDepthFunctionToLessOrEqual();
  5525. this.setDepthWrite(true);
  5526. // Fullscreen
  5527. this._onFullscreenChange = function () {
  5528. if (document.fullscreen !== undefined) {
  5529. _this.isFullscreen = document.fullscreen;
  5530. }
  5531. else if (document.mozFullScreen !== undefined) {
  5532. _this.isFullscreen = document.mozFullScreen;
  5533. }
  5534. else if (document.webkitIsFullScreen !== undefined) {
  5535. _this.isFullscreen = document.webkitIsFullScreen;
  5536. }
  5537. else if (document.msIsFullScreen !== undefined) {
  5538. _this.isFullscreen = document.msIsFullScreen;
  5539. }
  5540. // Pointer lock
  5541. if (_this.isFullscreen && _this._pointerLockRequested) {
  5542. canvas.requestPointerLock = canvas.requestPointerLock ||
  5543. canvas.msRequestPointerLock ||
  5544. canvas.mozRequestPointerLock ||
  5545. canvas.webkitRequestPointerLock;
  5546. if (canvas.requestPointerLock) {
  5547. canvas.requestPointerLock();
  5548. }
  5549. }
  5550. };
  5551. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5552. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5553. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5554. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5555. // Pointer lock
  5556. this._onPointerLockChange = function () {
  5557. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5558. document.webkitPointerLockElement === canvas ||
  5559. document.msPointerLockElement === canvas ||
  5560. document.pointerLockElement === canvas);
  5561. };
  5562. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5563. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5564. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5565. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5566. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5567. Engine.audioEngine = new BABYLON.AudioEngine();
  5568. }
  5569. //default loading screen
  5570. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5571. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5572. }
  5573. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5574. get: function () {
  5575. return Engine._ALPHA_DISABLE;
  5576. },
  5577. enumerable: true,
  5578. configurable: true
  5579. });
  5580. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5581. get: function () {
  5582. return Engine._ALPHA_ONEONE;
  5583. },
  5584. enumerable: true,
  5585. configurable: true
  5586. });
  5587. Object.defineProperty(Engine, "ALPHA_ADD", {
  5588. get: function () {
  5589. return Engine._ALPHA_ADD;
  5590. },
  5591. enumerable: true,
  5592. configurable: true
  5593. });
  5594. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5595. get: function () {
  5596. return Engine._ALPHA_COMBINE;
  5597. },
  5598. enumerable: true,
  5599. configurable: true
  5600. });
  5601. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5602. get: function () {
  5603. return Engine._ALPHA_SUBTRACT;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5609. get: function () {
  5610. return Engine._ALPHA_MULTIPLY;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5616. get: function () {
  5617. return Engine._ALPHA_MAXIMIZED;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5623. get: function () {
  5624. return Engine._DELAYLOADSTATE_NONE;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5630. get: function () {
  5631. return Engine._DELAYLOADSTATE_LOADED;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5637. get: function () {
  5638. return Engine._DELAYLOADSTATE_LOADING;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5644. get: function () {
  5645. return Engine._DELAYLOADSTATE_NOTLOADED;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5651. get: function () {
  5652. return Engine._TEXTUREFORMAT_ALPHA;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5658. get: function () {
  5659. return Engine._TEXTUREFORMAT_LUMINANCE;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5665. get: function () {
  5666. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5672. get: function () {
  5673. return Engine._TEXTUREFORMAT_RGB;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5679. get: function () {
  5680. return Engine._TEXTUREFORMAT_RGBA;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5686. get: function () {
  5687. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5693. get: function () {
  5694. return Engine._TEXTURETYPE_FLOAT;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(Engine, "Version", {
  5700. get: function () {
  5701. return "2.4.0-alpha";
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5707. get: function () {
  5708. return this._webGLVersion;
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Engine.prototype._prepareWorkingCanvas = function () {
  5714. if (this._workingCanvas) {
  5715. return;
  5716. }
  5717. this._workingCanvas = document.createElement("canvas");
  5718. this._workingContext = this._workingCanvas.getContext("2d");
  5719. };
  5720. Engine.prototype.resetTextureCache = function () {
  5721. for (var index = 0; index < this._maxTextureChannels; index++) {
  5722. this._activeTexturesCache[index] = null;
  5723. }
  5724. };
  5725. Engine.prototype.getGlInfo = function () {
  5726. return {
  5727. vendor: this._glVendor,
  5728. renderer: this._glRenderer,
  5729. version: this._glVersion
  5730. };
  5731. };
  5732. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5733. if (useScreen === void 0) { useScreen = false; }
  5734. var viewport = camera.viewport;
  5735. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5736. };
  5737. Engine.prototype.getRenderWidth = function (useScreen) {
  5738. if (useScreen === void 0) { useScreen = false; }
  5739. if (!useScreen && this._currentRenderTarget) {
  5740. return this._currentRenderTarget._width;
  5741. }
  5742. return this._renderingCanvas.width;
  5743. };
  5744. Engine.prototype.getRenderHeight = function (useScreen) {
  5745. if (useScreen === void 0) { useScreen = false; }
  5746. if (!useScreen && this._currentRenderTarget) {
  5747. return this._currentRenderTarget._height;
  5748. }
  5749. return this._renderingCanvas.height;
  5750. };
  5751. Engine.prototype.getRenderingCanvas = function () {
  5752. return this._renderingCanvas;
  5753. };
  5754. Engine.prototype.getRenderingCanvasClientRect = function () {
  5755. return this._renderingCanvas.getBoundingClientRect();
  5756. };
  5757. Engine.prototype.setHardwareScalingLevel = function (level) {
  5758. this._hardwareScalingLevel = level;
  5759. this.resize();
  5760. };
  5761. Engine.prototype.getHardwareScalingLevel = function () {
  5762. return this._hardwareScalingLevel;
  5763. };
  5764. Engine.prototype.getLoadedTexturesCache = function () {
  5765. return this._loadedTexturesCache;
  5766. };
  5767. Engine.prototype.getCaps = function () {
  5768. return this._caps;
  5769. };
  5770. Object.defineProperty(Engine.prototype, "drawCalls", {
  5771. get: function () {
  5772. return this._drawCalls;
  5773. },
  5774. enumerable: true,
  5775. configurable: true
  5776. });
  5777. // Methods
  5778. Engine.prototype.resetDrawCalls = function () {
  5779. this._drawCalls = 0;
  5780. };
  5781. Engine.prototype.setDepthFunctionToGreater = function () {
  5782. this._depthCullingState.depthFunc = this._gl.GREATER;
  5783. };
  5784. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5785. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5786. };
  5787. Engine.prototype.setDepthFunctionToLess = function () {
  5788. this._depthCullingState.depthFunc = this._gl.LESS;
  5789. };
  5790. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5791. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5792. };
  5793. /**
  5794. * stop executing a render loop function and remove it from the execution array
  5795. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5796. */
  5797. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5798. if (!renderFunction) {
  5799. this._activeRenderLoops = [];
  5800. return;
  5801. }
  5802. var index = this._activeRenderLoops.indexOf(renderFunction);
  5803. if (index >= 0) {
  5804. this._activeRenderLoops.splice(index, 1);
  5805. }
  5806. };
  5807. Engine.prototype._renderLoop = function () {
  5808. var shouldRender = true;
  5809. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5810. shouldRender = false;
  5811. }
  5812. if (shouldRender) {
  5813. // Start new frame
  5814. this.beginFrame();
  5815. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5816. var renderFunction = this._activeRenderLoops[index];
  5817. renderFunction();
  5818. }
  5819. // Present
  5820. this.endFrame();
  5821. }
  5822. if (this._activeRenderLoops.length > 0) {
  5823. // Register new frame
  5824. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5825. }
  5826. else {
  5827. this._renderingQueueLaunched = false;
  5828. }
  5829. };
  5830. /**
  5831. * Register and execute a render loop. The engine can have more than one render function.
  5832. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5833. * @example
  5834. * engine.runRenderLoop(function () {
  5835. * scene.render()
  5836. * })
  5837. */
  5838. Engine.prototype.runRenderLoop = function (renderFunction) {
  5839. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5840. return;
  5841. }
  5842. this._activeRenderLoops.push(renderFunction);
  5843. if (!this._renderingQueueLaunched) {
  5844. this._renderingQueueLaunched = true;
  5845. this._bindedRenderFunction = this._renderLoop.bind(this);
  5846. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5847. }
  5848. };
  5849. /**
  5850. * Toggle full screen mode.
  5851. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5852. */
  5853. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5854. if (this.isFullscreen) {
  5855. BABYLON.Tools.ExitFullscreen();
  5856. }
  5857. else {
  5858. this._pointerLockRequested = requestPointerLock;
  5859. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5860. }
  5861. };
  5862. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5863. this.applyStates();
  5864. if (backBuffer) {
  5865. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5866. }
  5867. if (depthStencil && this._depthCullingState.depthMask) {
  5868. this._gl.clearDepth(1.0);
  5869. }
  5870. var mode = 0;
  5871. if (backBuffer) {
  5872. mode |= this._gl.COLOR_BUFFER_BIT;
  5873. }
  5874. if (depthStencil && this._depthCullingState.depthMask) {
  5875. mode |= this._gl.DEPTH_BUFFER_BIT;
  5876. }
  5877. this._gl.clear(mode);
  5878. };
  5879. /**
  5880. * Set the WebGL's viewport
  5881. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5882. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5883. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5884. */
  5885. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5886. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5887. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5888. var x = viewport.x || 0;
  5889. var y = viewport.y || 0;
  5890. this._cachedViewport = viewport;
  5891. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5892. };
  5893. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5894. this._cachedViewport = null;
  5895. this._gl.viewport(x, y, width, height);
  5896. };
  5897. Engine.prototype.beginFrame = function () {
  5898. this._measureFps();
  5899. };
  5900. Engine.prototype.endFrame = function () {
  5901. //this.flushFramebuffer();
  5902. };
  5903. /**
  5904. * resize the view according to the canvas' size.
  5905. * @example
  5906. * window.addEventListener("resize", function () {
  5907. * engine.resize();
  5908. * });
  5909. */
  5910. Engine.prototype.resize = function () {
  5911. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5912. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5913. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5914. for (var index = 0; index < this.scenes.length; index++) {
  5915. var scene = this.scenes[index];
  5916. if (scene.debugLayer.isVisible()) {
  5917. scene.debugLayer._syncPositions();
  5918. }
  5919. }
  5920. };
  5921. /**
  5922. * force a specific size of the canvas
  5923. * @param {number} width - the new canvas' width
  5924. * @param {number} height - the new canvas' height
  5925. */
  5926. Engine.prototype.setSize = function (width, height) {
  5927. this._renderingCanvas.width = width;
  5928. this._renderingCanvas.height = height;
  5929. for (var index = 0; index < this.scenes.length; index++) {
  5930. var scene = this.scenes[index];
  5931. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5932. var cam = scene.cameras[camIndex];
  5933. cam._currentRenderId = 0;
  5934. }
  5935. }
  5936. };
  5937. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5938. this._currentRenderTarget = texture;
  5939. var gl = this._gl;
  5940. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5941. if (texture.isCube) {
  5942. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5943. }
  5944. else {
  5945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5946. }
  5947. this._gl.viewport(0, 0, texture._width, texture._height);
  5948. this.wipeCaches();
  5949. };
  5950. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5951. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5952. this._currentRenderTarget = null;
  5953. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5954. var gl = this._gl;
  5955. gl.bindTexture(gl.TEXTURE_2D, texture);
  5956. gl.generateMipmap(gl.TEXTURE_2D);
  5957. gl.bindTexture(gl.TEXTURE_2D, null);
  5958. }
  5959. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5960. };
  5961. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5962. if (texture.generateMipMaps) {
  5963. var gl = this._gl;
  5964. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5965. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5966. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5967. }
  5968. };
  5969. Engine.prototype.flushFramebuffer = function () {
  5970. this._gl.flush();
  5971. };
  5972. Engine.prototype.restoreDefaultFramebuffer = function () {
  5973. this._currentRenderTarget = null;
  5974. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5975. this.setViewport(this._cachedViewport);
  5976. this.wipeCaches();
  5977. };
  5978. // VBOs
  5979. Engine.prototype._resetVertexBufferBinding = function () {
  5980. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5981. this._cachedVertexBuffers = null;
  5982. };
  5983. Engine.prototype.createVertexBuffer = function (vertices) {
  5984. var vbo = this._gl.createBuffer();
  5985. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5986. if (vertices instanceof Float32Array) {
  5987. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5988. }
  5989. else {
  5990. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5991. }
  5992. this._resetVertexBufferBinding();
  5993. vbo.references = 1;
  5994. return vbo;
  5995. };
  5996. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5997. var vbo = this._gl.createBuffer();
  5998. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5999. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6000. this._resetVertexBufferBinding();
  6001. vbo.references = 1;
  6002. return vbo;
  6003. };
  6004. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6005. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6006. if (offset === undefined) {
  6007. offset = 0;
  6008. }
  6009. if (vertices instanceof Float32Array) {
  6010. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6011. }
  6012. else {
  6013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6014. }
  6015. this._resetVertexBufferBinding();
  6016. };
  6017. Engine.prototype._resetIndexBufferBinding = function () {
  6018. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6019. this._cachedIndexBuffer = null;
  6020. };
  6021. Engine.prototype.createIndexBuffer = function (indices) {
  6022. var vbo = this._gl.createBuffer();
  6023. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6024. // Check for 32 bits indices
  6025. var arrayBuffer;
  6026. var need32Bits = false;
  6027. if (this._caps.uintIndices) {
  6028. for (var index = 0; index < indices.length; index++) {
  6029. if (indices[index] > 65535) {
  6030. need32Bits = true;
  6031. break;
  6032. }
  6033. }
  6034. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6035. }
  6036. else {
  6037. arrayBuffer = new Uint16Array(indices);
  6038. }
  6039. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6040. this._resetIndexBufferBinding();
  6041. vbo.references = 1;
  6042. vbo.is32Bits = need32Bits;
  6043. return vbo;
  6044. };
  6045. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6046. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6047. this._cachedVertexBuffers = vertexBuffer;
  6048. this._cachedEffectForVertexBuffers = effect;
  6049. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6050. var offset = 0;
  6051. for (var index = 0; index < vertexDeclaration.length; index++) {
  6052. var order = effect.getAttributeLocation(index);
  6053. if (order >= 0) {
  6054. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6055. }
  6056. offset += vertexDeclaration[index] * 4;
  6057. }
  6058. }
  6059. if (this._cachedIndexBuffer !== indexBuffer) {
  6060. this._cachedIndexBuffer = indexBuffer;
  6061. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6062. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6063. }
  6064. };
  6065. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6066. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6067. this._cachedVertexBuffers = vertexBuffers;
  6068. this._cachedEffectForVertexBuffers = effect;
  6069. var attributes = effect.getAttributesNames();
  6070. for (var index = 0; index < attributes.length; index++) {
  6071. var order = effect.getAttributeLocation(index);
  6072. if (order >= 0) {
  6073. var vertexBuffer = vertexBuffers[attributes[index]];
  6074. if (!vertexBuffer) {
  6075. continue;
  6076. }
  6077. var stride = vertexBuffer.getStrideSize();
  6078. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6079. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6080. }
  6081. }
  6082. }
  6083. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6084. this._cachedIndexBuffer = indexBuffer;
  6085. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6086. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6087. }
  6088. };
  6089. Engine.prototype._releaseBuffer = function (buffer) {
  6090. buffer.references--;
  6091. if (buffer.references === 0) {
  6092. this._gl.deleteBuffer(buffer);
  6093. return true;
  6094. }
  6095. return false;
  6096. };
  6097. Engine.prototype.createInstancesBuffer = function (capacity) {
  6098. var buffer = this._gl.createBuffer();
  6099. buffer.capacity = capacity;
  6100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6101. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6102. return buffer;
  6103. };
  6104. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6105. this._gl.deleteBuffer(buffer);
  6106. };
  6107. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6108. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6109. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6110. for (var index = 0; index < 4; index++) {
  6111. var offsetLocation = offsetLocations[index];
  6112. this._gl.enableVertexAttribArray(offsetLocation);
  6113. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6114. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6115. }
  6116. };
  6117. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6118. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6119. for (var index = 0; index < 4; index++) {
  6120. var offsetLocation = offsetLocations[index];
  6121. this._gl.disableVertexAttribArray(offsetLocation);
  6122. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6123. }
  6124. };
  6125. Engine.prototype.applyStates = function () {
  6126. this._depthCullingState.apply(this._gl);
  6127. this._alphaState.apply(this._gl);
  6128. };
  6129. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6130. // Apply states
  6131. this.applyStates();
  6132. this._drawCalls++;
  6133. // Render
  6134. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6135. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6136. if (instancesCount) {
  6137. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6138. return;
  6139. }
  6140. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6141. };
  6142. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6143. // Apply states
  6144. this.applyStates();
  6145. this._drawCalls++;
  6146. if (instancesCount) {
  6147. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6148. return;
  6149. }
  6150. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6151. };
  6152. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6153. // Apply states
  6154. this.applyStates();
  6155. this._drawCalls++;
  6156. if (instancesCount) {
  6157. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6158. return;
  6159. }
  6160. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6161. };
  6162. // Shaders
  6163. Engine.prototype._releaseEffect = function (effect) {
  6164. if (this._compiledEffects[effect._key]) {
  6165. delete this._compiledEffects[effect._key];
  6166. if (effect.getProgram()) {
  6167. this._gl.deleteProgram(effect.getProgram());
  6168. }
  6169. }
  6170. };
  6171. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6172. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6173. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6174. var name = vertex + "+" + fragment + "@" + defines;
  6175. if (this._compiledEffects[name]) {
  6176. return this._compiledEffects[name];
  6177. }
  6178. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6179. effect._key = name;
  6180. this._compiledEffects[name] = effect;
  6181. return effect;
  6182. };
  6183. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6184. if (uniformsNames === void 0) { uniformsNames = []; }
  6185. if (samplers === void 0) { samplers = []; }
  6186. if (defines === void 0) { defines = ""; }
  6187. return this.createEffect({
  6188. vertex: "particles",
  6189. fragmentElement: fragmentName
  6190. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6191. };
  6192. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6193. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6194. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6195. var shaderProgram = this._gl.createProgram();
  6196. this._gl.attachShader(shaderProgram, vertexShader);
  6197. this._gl.attachShader(shaderProgram, fragmentShader);
  6198. this._gl.linkProgram(shaderProgram);
  6199. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6200. if (!linked) {
  6201. var error = this._gl.getProgramInfoLog(shaderProgram);
  6202. if (error) {
  6203. throw new Error(error);
  6204. }
  6205. }
  6206. this._gl.deleteShader(vertexShader);
  6207. this._gl.deleteShader(fragmentShader);
  6208. return shaderProgram;
  6209. };
  6210. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6211. var results = [];
  6212. for (var index = 0; index < uniformsNames.length; index++) {
  6213. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6214. }
  6215. return results;
  6216. };
  6217. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6218. var results = [];
  6219. for (var index = 0; index < attributesNames.length; index++) {
  6220. try {
  6221. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6222. }
  6223. catch (e) {
  6224. results.push(-1);
  6225. }
  6226. }
  6227. return results;
  6228. };
  6229. Engine.prototype.enableEffect = function (effect) {
  6230. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6231. if (effect && effect.onBind) {
  6232. effect.onBind(effect);
  6233. }
  6234. return;
  6235. }
  6236. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6237. // Use program
  6238. this._gl.useProgram(effect.getProgram());
  6239. for (var i in this._vertexAttribArrays) {
  6240. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6241. continue;
  6242. }
  6243. this._vertexAttribArrays[i] = false;
  6244. this._gl.disableVertexAttribArray(i);
  6245. }
  6246. var attributesCount = effect.getAttributesCount();
  6247. for (var index = 0; index < attributesCount; index++) {
  6248. // Attributes
  6249. var order = effect.getAttributeLocation(index);
  6250. if (order >= 0) {
  6251. this._vertexAttribArrays[order] = true;
  6252. this._gl.enableVertexAttribArray(order);
  6253. }
  6254. }
  6255. this._currentEffect = effect;
  6256. if (effect.onBind) {
  6257. effect.onBind(effect);
  6258. }
  6259. };
  6260. Engine.prototype.setArray = function (uniform, array) {
  6261. if (!uniform)
  6262. return;
  6263. this._gl.uniform1fv(uniform, array);
  6264. };
  6265. Engine.prototype.setArray2 = function (uniform, array) {
  6266. if (!uniform || array.length % 2 !== 0)
  6267. return;
  6268. this._gl.uniform2fv(uniform, array);
  6269. };
  6270. Engine.prototype.setArray3 = function (uniform, array) {
  6271. if (!uniform || array.length % 3 !== 0)
  6272. return;
  6273. this._gl.uniform3fv(uniform, array);
  6274. };
  6275. Engine.prototype.setArray4 = function (uniform, array) {
  6276. if (!uniform || array.length % 4 !== 0)
  6277. return;
  6278. this._gl.uniform4fv(uniform, array);
  6279. };
  6280. Engine.prototype.setMatrices = function (uniform, matrices) {
  6281. if (!uniform)
  6282. return;
  6283. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6284. };
  6285. Engine.prototype.setMatrix = function (uniform, matrix) {
  6286. if (!uniform)
  6287. return;
  6288. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6289. };
  6290. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6291. if (!uniform)
  6292. return;
  6293. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6294. };
  6295. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6296. if (!uniform)
  6297. return;
  6298. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6299. };
  6300. Engine.prototype.setFloat = function (uniform, value) {
  6301. if (!uniform)
  6302. return;
  6303. this._gl.uniform1f(uniform, value);
  6304. };
  6305. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6306. if (!uniform)
  6307. return;
  6308. this._gl.uniform2f(uniform, x, y);
  6309. };
  6310. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6311. if (!uniform)
  6312. return;
  6313. this._gl.uniform3f(uniform, x, y, z);
  6314. };
  6315. Engine.prototype.setBool = function (uniform, bool) {
  6316. if (!uniform)
  6317. return;
  6318. this._gl.uniform1i(uniform, bool);
  6319. };
  6320. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6321. if (!uniform)
  6322. return;
  6323. this._gl.uniform4f(uniform, x, y, z, w);
  6324. };
  6325. Engine.prototype.setColor3 = function (uniform, color3) {
  6326. if (!uniform)
  6327. return;
  6328. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6329. };
  6330. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6331. if (!uniform)
  6332. return;
  6333. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6334. };
  6335. // States
  6336. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6337. if (zOffset === void 0) { zOffset = 0; }
  6338. if (reverseSide === void 0) { reverseSide = false; }
  6339. // Culling
  6340. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6341. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6342. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6343. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6344. if (culling) {
  6345. this._depthCullingState.cullFace = cullFace;
  6346. this._depthCullingState.cull = true;
  6347. }
  6348. else {
  6349. this._depthCullingState.cull = false;
  6350. }
  6351. }
  6352. // Z offset
  6353. this._depthCullingState.zOffset = zOffset;
  6354. };
  6355. Engine.prototype.setDepthBuffer = function (enable) {
  6356. this._depthCullingState.depthTest = enable;
  6357. };
  6358. Engine.prototype.getDepthWrite = function () {
  6359. return this._depthCullingState.depthMask;
  6360. };
  6361. Engine.prototype.setDepthWrite = function (enable) {
  6362. this._depthCullingState.depthMask = enable;
  6363. };
  6364. Engine.prototype.setColorWrite = function (enable) {
  6365. this._gl.colorMask(enable, enable, enable, enable);
  6366. };
  6367. Engine.prototype.setAlphaMode = function (mode) {
  6368. if (this._alphaMode === mode) {
  6369. return;
  6370. }
  6371. switch (mode) {
  6372. case Engine.ALPHA_DISABLE:
  6373. this.setDepthWrite(true);
  6374. this._alphaState.alphaBlend = false;
  6375. break;
  6376. case Engine.ALPHA_COMBINE:
  6377. this.setDepthWrite(false);
  6378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6379. this._alphaState.alphaBlend = true;
  6380. break;
  6381. case Engine.ALPHA_ONEONE:
  6382. this.setDepthWrite(false);
  6383. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6384. this._alphaState.alphaBlend = true;
  6385. break;
  6386. case Engine.ALPHA_ADD:
  6387. this.setDepthWrite(false);
  6388. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6389. this._alphaState.alphaBlend = true;
  6390. break;
  6391. case Engine.ALPHA_SUBTRACT:
  6392. this.setDepthWrite(false);
  6393. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6394. this._alphaState.alphaBlend = true;
  6395. break;
  6396. case Engine.ALPHA_MULTIPLY:
  6397. this.setDepthWrite(false);
  6398. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6399. this._alphaState.alphaBlend = true;
  6400. break;
  6401. case Engine.ALPHA_MAXIMIZED:
  6402. this.setDepthWrite(false);
  6403. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6404. this._alphaState.alphaBlend = true;
  6405. break;
  6406. }
  6407. this._alphaMode = mode;
  6408. };
  6409. Engine.prototype.getAlphaMode = function () {
  6410. return this._alphaMode;
  6411. };
  6412. Engine.prototype.setAlphaTesting = function (enable) {
  6413. this._alphaTest = enable;
  6414. };
  6415. Engine.prototype.getAlphaTesting = function () {
  6416. return this._alphaTest;
  6417. };
  6418. // Textures
  6419. Engine.prototype.wipeCaches = function () {
  6420. this.resetTextureCache();
  6421. this._currentEffect = null;
  6422. this._depthCullingState.reset();
  6423. this._alphaState.reset();
  6424. this._cachedVertexBuffers = null;
  6425. this._cachedIndexBuffer = null;
  6426. this._cachedEffectForVertexBuffers = null;
  6427. };
  6428. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6429. var gl = this._gl;
  6430. gl.bindTexture(gl.TEXTURE_2D, texture);
  6431. var magFilter = gl.NEAREST;
  6432. var minFilter = gl.NEAREST;
  6433. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6434. magFilter = gl.LINEAR;
  6435. minFilter = gl.LINEAR;
  6436. }
  6437. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6438. magFilter = gl.LINEAR;
  6439. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6440. }
  6441. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6443. gl.bindTexture(gl.TEXTURE_2D, null);
  6444. texture.samplingMode = samplingMode;
  6445. };
  6446. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6447. var _this = this;
  6448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6449. if (onLoad === void 0) { onLoad = null; }
  6450. if (onError === void 0) { onError = null; }
  6451. if (buffer === void 0) { buffer = null; }
  6452. var texture = this._gl.createTexture();
  6453. var extension;
  6454. var fromData = false;
  6455. if (url.substr(0, 5) === "data:") {
  6456. fromData = true;
  6457. }
  6458. if (!fromData)
  6459. extension = url.substr(url.length - 4, 4).toLowerCase();
  6460. else {
  6461. var oldUrl = url;
  6462. fromData = oldUrl.split(':');
  6463. url = oldUrl;
  6464. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6465. }
  6466. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6467. var isTGA = (extension === ".tga");
  6468. scene._addPendingData(texture);
  6469. texture.url = url;
  6470. texture.noMipmap = noMipmap;
  6471. texture.references = 1;
  6472. texture.samplingMode = samplingMode;
  6473. this._loadedTexturesCache.push(texture);
  6474. var onerror = function () {
  6475. scene._removePendingData(texture);
  6476. if (onError) {
  6477. onError();
  6478. }
  6479. };
  6480. var callback;
  6481. if (isTGA) {
  6482. callback = function (arrayBuffer) {
  6483. var data = new Uint8Array(arrayBuffer);
  6484. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6485. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6486. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6487. }, onLoad, samplingMode);
  6488. };
  6489. if (!(fromData instanceof Array))
  6490. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6491. callback(arrayBuffer);
  6492. }, onerror, scene.database, true);
  6493. else
  6494. callback(buffer);
  6495. }
  6496. else if (isDDS) {
  6497. callback = function (data) {
  6498. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6499. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6500. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6501. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6502. }, onLoad, samplingMode);
  6503. };
  6504. if (!(fromData instanceof Array))
  6505. BABYLON.Tools.LoadFile(url, function (data) {
  6506. callback(data);
  6507. }, onerror, scene.database, true);
  6508. else
  6509. callback(buffer);
  6510. }
  6511. else {
  6512. var onload = function (img) {
  6513. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6514. var isPot = (img.width === potWidth && img.height === potHeight);
  6515. if (!isPot) {
  6516. _this._prepareWorkingCanvas();
  6517. _this._workingCanvas.width = potWidth;
  6518. _this._workingCanvas.height = potHeight;
  6519. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6520. _this._workingContext.imageSmoothingEnabled = false;
  6521. _this._workingContext.mozImageSmoothingEnabled = false;
  6522. _this._workingContext.oImageSmoothingEnabled = false;
  6523. _this._workingContext.webkitImageSmoothingEnabled = false;
  6524. _this._workingContext.msImageSmoothingEnabled = false;
  6525. }
  6526. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6527. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6528. _this._workingContext.imageSmoothingEnabled = true;
  6529. _this._workingContext.mozImageSmoothingEnabled = true;
  6530. _this._workingContext.oImageSmoothingEnabled = true;
  6531. _this._workingContext.webkitImageSmoothingEnabled = true;
  6532. _this._workingContext.msImageSmoothingEnabled = true;
  6533. }
  6534. }
  6535. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6536. }, onLoad, samplingMode);
  6537. };
  6538. if (!(fromData instanceof Array))
  6539. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6540. else
  6541. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6542. }
  6543. return texture;
  6544. };
  6545. Engine.prototype._getInternalFormat = function (format) {
  6546. var internalFormat = this._gl.RGBA;
  6547. switch (format) {
  6548. case Engine.TEXTUREFORMAT_ALPHA:
  6549. internalFormat = this._gl.ALPHA;
  6550. break;
  6551. case Engine.TEXTUREFORMAT_LUMINANCE:
  6552. internalFormat = this._gl.LUMINANCE;
  6553. break;
  6554. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6555. internalFormat = this._gl.LUMINANCE_ALPHA;
  6556. break;
  6557. case Engine.TEXTUREFORMAT_RGB:
  6558. internalFormat = this._gl.RGB;
  6559. break;
  6560. case Engine.TEXTUREFORMAT_RGBA:
  6561. internalFormat = this._gl.RGBA;
  6562. break;
  6563. }
  6564. return internalFormat;
  6565. };
  6566. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6567. if (compression === void 0) { compression = null; }
  6568. var internalFormat = this._getInternalFormat(format);
  6569. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6570. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6571. if (compression) {
  6572. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6573. }
  6574. else {
  6575. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6576. }
  6577. if (texture.generateMipMaps) {
  6578. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6579. }
  6580. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6581. this.resetTextureCache();
  6582. texture.isReady = true;
  6583. };
  6584. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6585. if (compression === void 0) { compression = null; }
  6586. var texture = this._gl.createTexture();
  6587. texture._baseWidth = width;
  6588. texture._baseHeight = height;
  6589. texture._width = width;
  6590. texture._height = height;
  6591. texture.references = 1;
  6592. this.updateRawTexture(texture, data, format, invertY, compression);
  6593. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6594. // Filters
  6595. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6596. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6598. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6599. texture.samplingMode = samplingMode;
  6600. this._loadedTexturesCache.push(texture);
  6601. return texture;
  6602. };
  6603. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6604. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6605. var texture = this._gl.createTexture();
  6606. texture._baseWidth = width;
  6607. texture._baseHeight = height;
  6608. if (forceExponantOfTwo) {
  6609. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6610. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6611. }
  6612. this.resetTextureCache();
  6613. texture._width = width;
  6614. texture._height = height;
  6615. texture.isReady = false;
  6616. texture.generateMipMaps = generateMipMaps;
  6617. texture.references = 1;
  6618. texture.samplingMode = samplingMode;
  6619. this.updateTextureSamplingMode(samplingMode, texture);
  6620. this._loadedTexturesCache.push(texture);
  6621. return texture;
  6622. };
  6623. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6624. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6625. if (texture.isCube) {
  6626. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6627. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6628. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6629. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6630. }
  6631. else {
  6632. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6633. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6634. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6635. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6636. }
  6637. };
  6638. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6639. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6640. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6641. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6642. if (texture.generateMipMaps) {
  6643. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6644. }
  6645. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6646. this.resetTextureCache();
  6647. texture.isReady = true;
  6648. };
  6649. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6650. if (texture._isDisabled) {
  6651. return;
  6652. }
  6653. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6654. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6655. try {
  6656. // Testing video texture support
  6657. if (this._videoTextureSupported === undefined) {
  6658. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6659. if (this._gl.getError() !== 0) {
  6660. this._videoTextureSupported = false;
  6661. }
  6662. else {
  6663. this._videoTextureSupported = true;
  6664. }
  6665. }
  6666. // Copy video through the current working canvas if video texture is not supported
  6667. if (!this._videoTextureSupported) {
  6668. if (!texture._workingCanvas) {
  6669. texture._workingCanvas = document.createElement("canvas");
  6670. texture._workingContext = texture._workingCanvas.getContext("2d");
  6671. texture._workingCanvas.width = texture._width;
  6672. texture._workingCanvas.height = texture._height;
  6673. }
  6674. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6675. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6676. }
  6677. else {
  6678. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6679. }
  6680. if (texture.generateMipMaps) {
  6681. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6682. }
  6683. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6684. this.resetTextureCache();
  6685. texture.isReady = true;
  6686. }
  6687. catch (ex) {
  6688. // Something unexpected
  6689. // Let's disable the texture
  6690. texture._isDisabled = true;
  6691. }
  6692. };
  6693. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6694. // old version had a "generateMipMaps" arg instead of options.
  6695. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6696. // in the same way, generateDepthBuffer is defaulted to true
  6697. var generateMipMaps = false;
  6698. var generateDepthBuffer = true;
  6699. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6700. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6701. if (options !== undefined) {
  6702. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6703. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6704. type = options.type === undefined ? type : options.type;
  6705. if (options.samplingMode !== undefined) {
  6706. samplingMode = options.samplingMode;
  6707. }
  6708. if (type === Engine.TEXTURETYPE_FLOAT) {
  6709. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6710. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6711. }
  6712. }
  6713. var gl = this._gl;
  6714. var texture = gl.createTexture();
  6715. gl.bindTexture(gl.TEXTURE_2D, texture);
  6716. var width = size.width || size;
  6717. var height = size.height || size;
  6718. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6719. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6720. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6721. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6722. }
  6723. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6725. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6727. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6728. var depthBuffer;
  6729. // Create the depth buffer
  6730. if (generateDepthBuffer) {
  6731. depthBuffer = gl.createRenderbuffer();
  6732. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6733. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6734. }
  6735. // Create the framebuffer
  6736. var framebuffer = gl.createFramebuffer();
  6737. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6738. if (generateDepthBuffer) {
  6739. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6740. }
  6741. if (generateMipMaps) {
  6742. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6743. }
  6744. // Unbind
  6745. gl.bindTexture(gl.TEXTURE_2D, null);
  6746. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6747. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6748. texture._framebuffer = framebuffer;
  6749. if (generateDepthBuffer) {
  6750. texture._depthBuffer = depthBuffer;
  6751. }
  6752. texture._width = width;
  6753. texture._height = height;
  6754. texture.isReady = true;
  6755. texture.generateMipMaps = generateMipMaps;
  6756. texture.references = 1;
  6757. texture.samplingMode = samplingMode;
  6758. this.resetTextureCache();
  6759. this._loadedTexturesCache.push(texture);
  6760. return texture;
  6761. };
  6762. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6763. var gl = this._gl;
  6764. var texture = gl.createTexture();
  6765. var generateMipMaps = true;
  6766. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6767. if (options !== undefined) {
  6768. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6769. if (options.samplingMode !== undefined) {
  6770. samplingMode = options.samplingMode;
  6771. }
  6772. }
  6773. texture.isCube = true;
  6774. texture.references = 1;
  6775. texture.generateMipMaps = generateMipMaps;
  6776. texture.references = 1;
  6777. texture.samplingMode = samplingMode;
  6778. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6779. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6780. for (var face = 0; face < 6; face++) {
  6781. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6782. }
  6783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6787. // Create the depth buffer
  6788. var depthBuffer = gl.createRenderbuffer();
  6789. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6790. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6791. // Create the framebuffer
  6792. var framebuffer = gl.createFramebuffer();
  6793. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6794. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6795. // Mipmaps
  6796. if (texture.generateMipMaps) {
  6797. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6798. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6799. }
  6800. // Unbind
  6801. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6802. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6803. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6804. texture._framebuffer = framebuffer;
  6805. texture._depthBuffer = depthBuffer;
  6806. this.resetTextureCache();
  6807. texture._width = size;
  6808. texture._height = size;
  6809. texture.isReady = true;
  6810. return texture;
  6811. };
  6812. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6813. var _this = this;
  6814. var gl = this._gl;
  6815. var texture = gl.createTexture();
  6816. texture.isCube = true;
  6817. texture.url = rootUrl;
  6818. texture.references = 1;
  6819. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6820. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6821. if (isDDS) {
  6822. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6823. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6824. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6825. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6826. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6827. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6828. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6829. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6830. }
  6831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6835. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6836. _this.resetTextureCache();
  6837. texture._width = info.width;
  6838. texture._height = info.height;
  6839. texture.isReady = true;
  6840. }, null, null, true);
  6841. }
  6842. else {
  6843. cascadeLoad(rootUrl, scene, function (imgs) {
  6844. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6845. var height = width;
  6846. _this._prepareWorkingCanvas();
  6847. _this._workingCanvas.width = width;
  6848. _this._workingCanvas.height = height;
  6849. var faces = [
  6850. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6851. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6852. ];
  6853. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6854. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6855. for (var index = 0; index < faces.length; index++) {
  6856. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6857. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6858. }
  6859. if (!noMipmap) {
  6860. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6861. }
  6862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6866. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6867. _this.resetTextureCache();
  6868. texture._width = width;
  6869. texture._height = height;
  6870. texture.isReady = true;
  6871. }, files);
  6872. }
  6873. return texture;
  6874. };
  6875. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6876. var _this = this;
  6877. var gl = this._gl;
  6878. var texture = gl.createTexture();
  6879. scene._addPendingData(texture);
  6880. texture.isCube = true;
  6881. texture.references = 1;
  6882. texture.url = url;
  6883. var internalFormat = this._getInternalFormat(format);
  6884. var textureType = gl.UNSIGNED_BYTE;
  6885. if (type === Engine.TEXTURETYPE_FLOAT) {
  6886. textureType = gl.FLOAT;
  6887. }
  6888. var width = size;
  6889. var height = width;
  6890. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6891. texture._width = width;
  6892. texture._height = height;
  6893. var onerror = function () {
  6894. scene._removePendingData(texture);
  6895. };
  6896. var internalCallback = function (data) {
  6897. var rgbeDataArrays = callback(data);
  6898. var facesIndex = [
  6899. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6900. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6901. ];
  6902. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6903. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6904. for (var index = 0; index < facesIndex.length; index++) {
  6905. var faceData = rgbeDataArrays[index];
  6906. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6907. }
  6908. if (!noMipmap && isPot) {
  6909. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6910. }
  6911. else {
  6912. noMipmap = true;
  6913. }
  6914. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6917. }
  6918. else {
  6919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6921. }
  6922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6923. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6924. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6925. texture.isReady = true;
  6926. _this.resetTextureCache();
  6927. scene._removePendingData(texture);
  6928. };
  6929. BABYLON.Tools.LoadFile(url, function (data) {
  6930. internalCallback(data);
  6931. }, onerror, scene.database, true);
  6932. return texture;
  6933. };
  6934. ;
  6935. Engine.prototype._releaseTexture = function (texture) {
  6936. var gl = this._gl;
  6937. if (texture._framebuffer) {
  6938. gl.deleteFramebuffer(texture._framebuffer);
  6939. }
  6940. if (texture._depthBuffer) {
  6941. gl.deleteRenderbuffer(texture._depthBuffer);
  6942. }
  6943. gl.deleteTexture(texture);
  6944. // Unbind channels
  6945. this.unbindAllTextures();
  6946. var index = this._loadedTexturesCache.indexOf(texture);
  6947. if (index !== -1) {
  6948. this._loadedTexturesCache.splice(index, 1);
  6949. }
  6950. };
  6951. Engine.prototype.bindSamplers = function (effect) {
  6952. this._gl.useProgram(effect.getProgram());
  6953. var samplers = effect.getSamplers();
  6954. for (var index = 0; index < samplers.length; index++) {
  6955. var uniform = effect.getUniform(samplers[index]);
  6956. this._gl.uniform1i(uniform, index);
  6957. }
  6958. this._currentEffect = null;
  6959. };
  6960. Engine.prototype._bindTexture = function (channel, texture) {
  6961. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6962. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6963. this._activeTexturesCache[channel] = null;
  6964. };
  6965. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6966. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6967. };
  6968. Engine.prototype.unbindAllTextures = function () {
  6969. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6970. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6971. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6972. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6973. this._activeTexturesCache[channel] = null;
  6974. }
  6975. };
  6976. Engine.prototype.setTexture = function (channel, texture) {
  6977. if (channel < 0) {
  6978. return;
  6979. }
  6980. // Not ready?
  6981. if (!texture || !texture.isReady()) {
  6982. if (this._activeTexturesCache[channel] != null) {
  6983. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6984. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6985. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6986. this._activeTexturesCache[channel] = null;
  6987. }
  6988. return;
  6989. }
  6990. // Video
  6991. var alreadyActivated = false;
  6992. if (texture instanceof BABYLON.VideoTexture) {
  6993. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6994. alreadyActivated = true;
  6995. texture.update();
  6996. }
  6997. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6998. texture.delayLoad();
  6999. return;
  7000. }
  7001. if (this._activeTexturesCache[channel] === texture) {
  7002. return;
  7003. }
  7004. this._activeTexturesCache[channel] = texture;
  7005. var internalTexture = texture.getInternalTexture();
  7006. if (!alreadyActivated) {
  7007. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7008. }
  7009. if (internalTexture.isCube) {
  7010. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7011. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7012. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7013. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7014. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7015. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7016. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7017. }
  7018. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7019. }
  7020. else {
  7021. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7022. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7023. internalTexture._cachedWrapU = texture.wrapU;
  7024. switch (texture.wrapU) {
  7025. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7026. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7027. break;
  7028. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7030. break;
  7031. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7032. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7033. break;
  7034. }
  7035. }
  7036. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7037. internalTexture._cachedWrapV = texture.wrapV;
  7038. switch (texture.wrapV) {
  7039. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7040. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7041. break;
  7042. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7043. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7044. break;
  7045. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7046. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7047. break;
  7048. }
  7049. }
  7050. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7051. }
  7052. };
  7053. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7054. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7055. var value = texture.anisotropicFilteringLevel;
  7056. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7057. value = 1;
  7058. }
  7059. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7060. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7061. texture._cachedAnisotropicFilteringLevel = value;
  7062. }
  7063. };
  7064. Engine.prototype.readPixels = function (x, y, width, height) {
  7065. var data = new Uint8Array(height * width * 4);
  7066. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7067. return data;
  7068. };
  7069. Engine.prototype.releaseInternalTexture = function (texture) {
  7070. if (!texture) {
  7071. return;
  7072. }
  7073. texture.references--;
  7074. // Final reference ?
  7075. if (texture.references === 0) {
  7076. var texturesCache = this.getLoadedTexturesCache();
  7077. var index = texturesCache.indexOf(texture);
  7078. if (index > -1) {
  7079. texturesCache.splice(index, 1);
  7080. }
  7081. this._releaseTexture(texture);
  7082. }
  7083. };
  7084. // Dispose
  7085. Engine.prototype.dispose = function () {
  7086. this.hideLoadingUI();
  7087. this.stopRenderLoop();
  7088. // Release scenes
  7089. while (this.scenes.length) {
  7090. this.scenes[0].dispose();
  7091. }
  7092. // Release audio engine
  7093. Engine.audioEngine.dispose();
  7094. // Release effects
  7095. for (var name in this._compiledEffects) {
  7096. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7097. }
  7098. // Unbind
  7099. for (var i in this._vertexAttribArrays) {
  7100. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  7101. continue;
  7102. }
  7103. this._gl.disableVertexAttribArray(i);
  7104. }
  7105. this._gl = null;
  7106. // Events
  7107. window.removeEventListener("blur", this._onBlur);
  7108. window.removeEventListener("focus", this._onFocus);
  7109. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7110. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7111. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7112. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7113. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7114. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7115. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7116. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7117. };
  7118. // Loading screen
  7119. Engine.prototype.displayLoadingUI = function () {
  7120. this._loadingScreen.displayLoadingUI();
  7121. };
  7122. Engine.prototype.hideLoadingUI = function () {
  7123. this._loadingScreen.hideLoadingUI();
  7124. };
  7125. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7126. get: function () {
  7127. return this._loadingScreen;
  7128. },
  7129. set: function (loadingScreen) {
  7130. this._loadingScreen = loadingScreen;
  7131. },
  7132. enumerable: true,
  7133. configurable: true
  7134. });
  7135. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7136. set: function (text) {
  7137. this._loadingScreen.loadingUIText = text;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7143. set: function (color) {
  7144. this._loadingScreen.loadingUIBackgroundColor = color;
  7145. },
  7146. enumerable: true,
  7147. configurable: true
  7148. });
  7149. // FPS
  7150. Engine.prototype.getFps = function () {
  7151. return this.fps;
  7152. };
  7153. Engine.prototype.getDeltaTime = function () {
  7154. return this.deltaTime;
  7155. };
  7156. Engine.prototype._measureFps = function () {
  7157. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7158. var length = this.previousFramesDuration.length;
  7159. if (length >= 2) {
  7160. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7161. }
  7162. if (length >= this.fpsRange) {
  7163. if (length > this.fpsRange) {
  7164. this.previousFramesDuration.splice(0, 1);
  7165. length = this.previousFramesDuration.length;
  7166. }
  7167. var sum = 0;
  7168. for (var id = 0; id < length - 1; id++) {
  7169. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7170. }
  7171. this.fps = 1000.0 / (sum / (length - 1));
  7172. }
  7173. };
  7174. // Statics
  7175. Engine.isSupported = function () {
  7176. try {
  7177. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7178. if (navigator.isCocoonJS) {
  7179. return true;
  7180. }
  7181. var tempcanvas = document.createElement("canvas");
  7182. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7183. return gl != null && !!window.WebGLRenderingContext;
  7184. }
  7185. catch (e) {
  7186. return false;
  7187. }
  7188. };
  7189. // Const statics
  7190. Engine._ALPHA_DISABLE = 0;
  7191. Engine._ALPHA_ADD = 1;
  7192. Engine._ALPHA_COMBINE = 2;
  7193. Engine._ALPHA_SUBTRACT = 3;
  7194. Engine._ALPHA_MULTIPLY = 4;
  7195. Engine._ALPHA_MAXIMIZED = 5;
  7196. Engine._ALPHA_ONEONE = 6;
  7197. Engine._DELAYLOADSTATE_NONE = 0;
  7198. Engine._DELAYLOADSTATE_LOADED = 1;
  7199. Engine._DELAYLOADSTATE_LOADING = 2;
  7200. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7201. Engine._TEXTUREFORMAT_ALPHA = 0;
  7202. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7203. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7204. Engine._TEXTUREFORMAT_RGB = 4;
  7205. Engine._TEXTUREFORMAT_RGBA = 5;
  7206. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7207. Engine._TEXTURETYPE_FLOAT = 1;
  7208. // Updatable statics so stick with vars here
  7209. Engine.Epsilon = 0.001;
  7210. Engine.CollisionsEpsilon = 0.001;
  7211. Engine.CodeRepository = "src/";
  7212. Engine.ShadersRepository = "src/Shaders/";
  7213. return Engine;
  7214. })();
  7215. BABYLON.Engine = Engine;
  7216. })(BABYLON || (BABYLON = {}));
  7217. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7218. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7219. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7220. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  7221. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7222. };
  7223. var BABYLON;
  7224. (function (BABYLON) {
  7225. /**
  7226. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7227. */
  7228. var Node = (function () {
  7229. /**
  7230. * @constructor
  7231. * @param {string} name - the name and id to be given to this node
  7232. * @param {BABYLON.Scene} the scene this node will be added to
  7233. */
  7234. function Node(name, scene) {
  7235. this.state = "";
  7236. this.animations = new Array();
  7237. this._ranges = {};
  7238. this._childrenFlag = -1;
  7239. this._isEnabled = true;
  7240. this._isReady = true;
  7241. this._currentRenderId = -1;
  7242. this._parentRenderId = -1;
  7243. this.name = name;
  7244. this.id = name;
  7245. this._scene = scene;
  7246. this._initCache();
  7247. }
  7248. Node.prototype.getScene = function () {
  7249. return this._scene;
  7250. };
  7251. Node.prototype.getEngine = function () {
  7252. return this._scene.getEngine();
  7253. };
  7254. // override it in derived class
  7255. Node.prototype.getWorldMatrix = function () {
  7256. return BABYLON.Matrix.Identity();
  7257. };
  7258. // override it in derived class if you add new variables to the cache
  7259. // and call the parent class method
  7260. Node.prototype._initCache = function () {
  7261. this._cache = {};
  7262. this._cache.parent = undefined;
  7263. };
  7264. Node.prototype.updateCache = function (force) {
  7265. if (!force && this.isSynchronized())
  7266. return;
  7267. this._cache.parent = this.parent;
  7268. this._updateCache();
  7269. };
  7270. // override it in derived class if you add new variables to the cache
  7271. // and call the parent class method if !ignoreParentClass
  7272. Node.prototype._updateCache = function (ignoreParentClass) {
  7273. };
  7274. // override it in derived class if you add new variables to the cache
  7275. Node.prototype._isSynchronized = function () {
  7276. return true;
  7277. };
  7278. Node.prototype._markSyncedWithParent = function () {
  7279. this._parentRenderId = this.parent._currentRenderId;
  7280. };
  7281. Node.prototype.isSynchronizedWithParent = function () {
  7282. if (!this.parent) {
  7283. return true;
  7284. }
  7285. if (this._parentRenderId !== this.parent._currentRenderId) {
  7286. return false;
  7287. }
  7288. return this.parent.isSynchronized();
  7289. };
  7290. Node.prototype.isSynchronized = function (updateCache) {
  7291. var check = this.hasNewParent();
  7292. check = check || !this.isSynchronizedWithParent();
  7293. check = check || !this._isSynchronized();
  7294. if (updateCache)
  7295. this.updateCache(true);
  7296. return !check;
  7297. };
  7298. Node.prototype.hasNewParent = function (update) {
  7299. if (this._cache.parent === this.parent)
  7300. return false;
  7301. if (update)
  7302. this._cache.parent = this.parent;
  7303. return true;
  7304. };
  7305. /**
  7306. * Is this node ready to be used/rendered
  7307. * @return {boolean} is it ready
  7308. */
  7309. Node.prototype.isReady = function () {
  7310. return this._isReady;
  7311. };
  7312. /**
  7313. * Is this node enabled.
  7314. * If the node has a parent and is enabled, the parent will be inspected as well.
  7315. * @return {boolean} whether this node (and its parent) is enabled.
  7316. * @see setEnabled
  7317. */
  7318. Node.prototype.isEnabled = function () {
  7319. if (!this._isEnabled) {
  7320. return false;
  7321. }
  7322. if (this.parent) {
  7323. return this.parent.isEnabled();
  7324. }
  7325. return true;
  7326. };
  7327. /**
  7328. * Set the enabled state of this node.
  7329. * @param {boolean} value - the new enabled state
  7330. * @see isEnabled
  7331. */
  7332. Node.prototype.setEnabled = function (value) {
  7333. this._isEnabled = value;
  7334. };
  7335. /**
  7336. * Is this node a descendant of the given node.
  7337. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7338. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7339. * @see parent
  7340. */
  7341. Node.prototype.isDescendantOf = function (ancestor) {
  7342. if (this.parent) {
  7343. if (this.parent === ancestor) {
  7344. return true;
  7345. }
  7346. return this.parent.isDescendantOf(ancestor);
  7347. }
  7348. return false;
  7349. };
  7350. Node.prototype._getDescendants = function (list, results) {
  7351. for (var index = 0; index < list.length; index++) {
  7352. var item = list[index];
  7353. if (item.isDescendantOf(this)) {
  7354. results.push(item);
  7355. }
  7356. }
  7357. };
  7358. /**
  7359. * Will return all nodes that have this node as parent.
  7360. * @return {BABYLON.Node[]} all children nodes of all types.
  7361. */
  7362. Node.prototype.getDescendants = function () {
  7363. var results = [];
  7364. this._getDescendants(this._scene.meshes, results);
  7365. this._getDescendants(this._scene.lights, results);
  7366. this._getDescendants(this._scene.cameras, results);
  7367. return results;
  7368. };
  7369. Node.prototype._setReady = function (state) {
  7370. if (state === this._isReady) {
  7371. return;
  7372. }
  7373. if (!state) {
  7374. this._isReady = false;
  7375. return;
  7376. }
  7377. this._isReady = true;
  7378. if (this.onReady) {
  7379. this.onReady(this);
  7380. }
  7381. };
  7382. Node.prototype.getAnimationByName = function (name) {
  7383. for (var i = 0; i < this.animations.length; i++) {
  7384. var animation = this.animations[i];
  7385. if (animation.name === name) {
  7386. return animation;
  7387. }
  7388. }
  7389. return null;
  7390. };
  7391. Node.prototype.createAnimationRange = function (name, from, to) {
  7392. // check name not already in use
  7393. if (!this._ranges[name]) {
  7394. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7395. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7396. if (this.animations[i]) {
  7397. this.animations[i].createRange(name, from, to);
  7398. }
  7399. }
  7400. }
  7401. };
  7402. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7403. if (deleteFrames === void 0) { deleteFrames = true; }
  7404. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7405. if (this.animations[i]) {
  7406. this.animations[i].deleteRange(name, deleteFrames);
  7407. }
  7408. }
  7409. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7410. };
  7411. Node.prototype.getAnimationRange = function (name) {
  7412. return this._ranges[name];
  7413. };
  7414. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7415. var range = this.getAnimationRange(name);
  7416. if (!range) {
  7417. return null;
  7418. }
  7419. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7420. };
  7421. Node.prototype.serializeAnimationRanges = function () {
  7422. var serializationRanges = [];
  7423. for (var name in this._ranges) {
  7424. var range = {};
  7425. range.name = name;
  7426. range.from = this._ranges[name].from;
  7427. range.to = this._ranges[name].to;
  7428. serializationRanges.push(range);
  7429. }
  7430. return serializationRanges;
  7431. };
  7432. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7433. if (parsedNode.ranges) {
  7434. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7435. var data = parsedNode.ranges[index];
  7436. node.createAnimationRange(data.name, data.from, data.to);
  7437. }
  7438. }
  7439. };
  7440. __decorate([
  7441. BABYLON.serialize()
  7442. ], Node.prototype, "name", void 0);
  7443. __decorate([
  7444. BABYLON.serialize()
  7445. ], Node.prototype, "id", void 0);
  7446. __decorate([
  7447. BABYLON.serialize()
  7448. ], Node.prototype, "uniqueId", void 0);
  7449. __decorate([
  7450. BABYLON.serialize()
  7451. ], Node.prototype, "state", void 0);
  7452. return Node;
  7453. })();
  7454. BABYLON.Node = Node;
  7455. })(BABYLON || (BABYLON = {}));
  7456. var BABYLON;
  7457. (function (BABYLON) {
  7458. var FilesInput = (function () {
  7459. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7460. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7461. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7462. this._engine = p_engine;
  7463. this._canvas = p_canvas;
  7464. this._currentScene = p_scene;
  7465. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7466. this._progressCallback = p_progressCallback;
  7467. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7468. this._textureLoadingCallback = p_textureLoadingCallback;
  7469. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7470. }
  7471. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7472. var _this = this;
  7473. if (p_elementToMonitor) {
  7474. this._elementToMonitor = p_elementToMonitor;
  7475. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7476. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7477. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7478. }
  7479. };
  7480. FilesInput.prototype.renderFunction = function () {
  7481. if (this._additionnalRenderLoopLogicCallback) {
  7482. this._additionnalRenderLoopLogicCallback();
  7483. }
  7484. if (this._currentScene) {
  7485. if (this._textureLoadingCallback) {
  7486. var remaining = this._currentScene.getWaitingItemsCount();
  7487. if (remaining > 0) {
  7488. this._textureLoadingCallback(remaining);
  7489. }
  7490. }
  7491. this._currentScene.render();
  7492. }
  7493. };
  7494. FilesInput.prototype.drag = function (e) {
  7495. e.stopPropagation();
  7496. e.preventDefault();
  7497. };
  7498. FilesInput.prototype.drop = function (eventDrop) {
  7499. eventDrop.stopPropagation();
  7500. eventDrop.preventDefault();
  7501. this.loadFiles(eventDrop);
  7502. };
  7503. FilesInput.prototype.loadFiles = function (event) {
  7504. if (this._startingProcessingFilesCallback)
  7505. this._startingProcessingFilesCallback();
  7506. // Handling data transfer via drag'n'drop
  7507. if (event && event.dataTransfer && event.dataTransfer.files) {
  7508. this._filesToLoad = event.dataTransfer.files;
  7509. }
  7510. // Handling files from input files
  7511. if (event && event.target && event.target.files) {
  7512. this._filesToLoad = event.target.files;
  7513. }
  7514. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7515. for (var i = 0; i < this._filesToLoad.length; i++) {
  7516. switch (this._filesToLoad[i].type) {
  7517. case "image/jpeg":
  7518. case "image/png":
  7519. case "image/bmp":
  7520. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7521. break;
  7522. case "image/targa":
  7523. case "image/vnd.ms-dds":
  7524. case "audio/wav":
  7525. case "audio/x-wav":
  7526. case "audio/mp3":
  7527. case "audio/mpeg":
  7528. case "audio/mpeg3":
  7529. case "audio/x-mpeg-3":
  7530. case "audio/ogg":
  7531. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7532. break;
  7533. default:
  7534. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7535. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7536. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7537. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7538. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7539. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7540. this._sceneFileToLoad = this._filesToLoad[i];
  7541. }
  7542. break;
  7543. }
  7544. }
  7545. this.reload();
  7546. }
  7547. };
  7548. FilesInput.prototype.reload = function () {
  7549. var _this = this;
  7550. var that = this;
  7551. // If a ".babylon" file has been provided
  7552. if (this._sceneFileToLoad) {
  7553. if (this._currentScene) {
  7554. if (BABYLON.Tools.errorsCount > 0) {
  7555. BABYLON.Tools.ClearLogCache();
  7556. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7557. }
  7558. this._engine.stopRenderLoop();
  7559. this._currentScene.dispose();
  7560. }
  7561. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7562. that._currentScene = newScene;
  7563. // Wait for textures and shaders to be ready
  7564. that._currentScene.executeWhenReady(function () {
  7565. // Attach camera to canvas inputs
  7566. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7567. that._currentScene.createDefaultCameraOrLight();
  7568. }
  7569. that._currentScene.activeCamera.attachControl(that._canvas);
  7570. if (that._sceneLoadedCallback) {
  7571. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7572. }
  7573. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7574. });
  7575. }, function (progress) {
  7576. if (_this._progressCallback) {
  7577. _this._progressCallback(progress);
  7578. }
  7579. });
  7580. }
  7581. else {
  7582. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7583. }
  7584. };
  7585. FilesInput.FilesTextures = new Array();
  7586. FilesInput.FilesToLoad = new Array();
  7587. return FilesInput;
  7588. })();
  7589. BABYLON.FilesInput = FilesInput;
  7590. })(BABYLON || (BABYLON = {}));
  7591. var BABYLON;
  7592. (function (BABYLON) {
  7593. var IntersectionInfo = (function () {
  7594. function IntersectionInfo(bu, bv, distance) {
  7595. this.bu = bu;
  7596. this.bv = bv;
  7597. this.distance = distance;
  7598. this.faceId = 0;
  7599. this.subMeshId = 0;
  7600. }
  7601. return IntersectionInfo;
  7602. })();
  7603. BABYLON.IntersectionInfo = IntersectionInfo;
  7604. var PickingInfo = (function () {
  7605. function PickingInfo() {
  7606. this.hit = false;
  7607. this.distance = 0;
  7608. this.pickedPoint = null;
  7609. this.pickedMesh = null;
  7610. this.bu = 0;
  7611. this.bv = 0;
  7612. this.faceId = -1;
  7613. this.subMeshId = 0;
  7614. this.pickedSprite = null;
  7615. }
  7616. // Methods
  7617. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7618. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7619. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7620. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7621. return null;
  7622. }
  7623. var indices = this.pickedMesh.getIndices();
  7624. var result;
  7625. if (useVerticesNormals) {
  7626. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7627. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7628. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7629. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7630. normal0 = normal0.scale(this.bu);
  7631. normal1 = normal1.scale(this.bv);
  7632. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7633. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7634. }
  7635. else {
  7636. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7637. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7638. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7639. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7640. var p1p2 = vertex1.subtract(vertex2);
  7641. var p3p2 = vertex3.subtract(vertex2);
  7642. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7643. }
  7644. if (useWorldCoordinates) {
  7645. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7646. }
  7647. return BABYLON.Vector3.Normalize(result);
  7648. };
  7649. PickingInfo.prototype.getTextureCoordinates = function () {
  7650. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7651. return null;
  7652. }
  7653. var indices = this.pickedMesh.getIndices();
  7654. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7655. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7656. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7657. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7658. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7659. uv1 = uv1.scale(this.bu);
  7660. uv2 = uv2.scale(this.bv);
  7661. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7662. };
  7663. return PickingInfo;
  7664. })();
  7665. BABYLON.PickingInfo = PickingInfo;
  7666. })(BABYLON || (BABYLON = {}));
  7667. var BABYLON;
  7668. (function (BABYLON) {
  7669. var BoundingSphere = (function () {
  7670. function BoundingSphere(minimum, maximum) {
  7671. this.minimum = minimum;
  7672. this.maximum = maximum;
  7673. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7674. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7675. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7676. this.radius = distance * 0.5;
  7677. this.centerWorld = BABYLON.Vector3.Zero();
  7678. this._update(BABYLON.Matrix.Identity());
  7679. }
  7680. // Methods
  7681. BoundingSphere.prototype._update = function (world) {
  7682. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7683. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7684. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7685. };
  7686. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7687. for (var i = 0; i < 6; i++) {
  7688. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7689. return false;
  7690. }
  7691. return true;
  7692. };
  7693. BoundingSphere.prototype.intersectsPoint = function (point) {
  7694. var x = this.centerWorld.x - point.x;
  7695. var y = this.centerWorld.y - point.y;
  7696. var z = this.centerWorld.z - point.z;
  7697. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7698. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7699. return false;
  7700. return true;
  7701. };
  7702. // Statics
  7703. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7704. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7705. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7706. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7707. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7708. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7709. return false;
  7710. return true;
  7711. };
  7712. return BoundingSphere;
  7713. })();
  7714. BABYLON.BoundingSphere = BoundingSphere;
  7715. })(BABYLON || (BABYLON = {}));
  7716. var BABYLON;
  7717. (function (BABYLON) {
  7718. var BoundingBox = (function () {
  7719. function BoundingBox(minimum, maximum) {
  7720. this.minimum = minimum;
  7721. this.maximum = maximum;
  7722. this.vectors = new Array();
  7723. this.vectorsWorld = new Array();
  7724. // Bounding vectors
  7725. this.vectors.push(this.minimum.clone());
  7726. this.vectors.push(this.maximum.clone());
  7727. this.vectors.push(this.minimum.clone());
  7728. this.vectors[2].x = this.maximum.x;
  7729. this.vectors.push(this.minimum.clone());
  7730. this.vectors[3].y = this.maximum.y;
  7731. this.vectors.push(this.minimum.clone());
  7732. this.vectors[4].z = this.maximum.z;
  7733. this.vectors.push(this.maximum.clone());
  7734. this.vectors[5].z = this.minimum.z;
  7735. this.vectors.push(this.maximum.clone());
  7736. this.vectors[6].x = this.minimum.x;
  7737. this.vectors.push(this.maximum.clone());
  7738. this.vectors[7].y = this.minimum.y;
  7739. // OBB
  7740. this.center = this.maximum.add(this.minimum).scale(0.5);
  7741. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7742. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7743. // World
  7744. for (var index = 0; index < this.vectors.length; index++) {
  7745. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7746. }
  7747. this.minimumWorld = BABYLON.Vector3.Zero();
  7748. this.maximumWorld = BABYLON.Vector3.Zero();
  7749. this._update(BABYLON.Matrix.Identity());
  7750. }
  7751. // Methods
  7752. BoundingBox.prototype.getWorldMatrix = function () {
  7753. return this._worldMatrix;
  7754. };
  7755. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7756. this._worldMatrix.copyFrom(matrix);
  7757. return this;
  7758. };
  7759. BoundingBox.prototype._update = function (world) {
  7760. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7761. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7762. for (var index = 0; index < this.vectors.length; index++) {
  7763. var v = this.vectorsWorld[index];
  7764. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7765. if (v.x < this.minimumWorld.x)
  7766. this.minimumWorld.x = v.x;
  7767. if (v.y < this.minimumWorld.y)
  7768. this.minimumWorld.y = v.y;
  7769. if (v.z < this.minimumWorld.z)
  7770. this.minimumWorld.z = v.z;
  7771. if (v.x > this.maximumWorld.x)
  7772. this.maximumWorld.x = v.x;
  7773. if (v.y > this.maximumWorld.y)
  7774. this.maximumWorld.y = v.y;
  7775. if (v.z > this.maximumWorld.z)
  7776. this.maximumWorld.z = v.z;
  7777. }
  7778. // OBB
  7779. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7780. this.center.scaleInPlace(0.5);
  7781. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7782. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7783. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7784. this._worldMatrix = world;
  7785. };
  7786. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7787. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7788. };
  7789. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7790. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7791. };
  7792. BoundingBox.prototype.intersectsPoint = function (point) {
  7793. var delta = -BABYLON.Engine.Epsilon;
  7794. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7795. return false;
  7796. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7797. return false;
  7798. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7799. return false;
  7800. return true;
  7801. };
  7802. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7803. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7804. };
  7805. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7806. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7807. return false;
  7808. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7809. return false;
  7810. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7811. return false;
  7812. return true;
  7813. };
  7814. // Statics
  7815. BoundingBox.Intersects = function (box0, box1) {
  7816. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7817. return false;
  7818. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7819. return false;
  7820. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7821. return false;
  7822. return true;
  7823. };
  7824. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7825. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7826. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7827. return (num <= (sphereRadius * sphereRadius));
  7828. };
  7829. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7830. for (var p = 0; p < 6; p++) {
  7831. for (var i = 0; i < 8; i++) {
  7832. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7833. return false;
  7834. }
  7835. }
  7836. }
  7837. return true;
  7838. };
  7839. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7840. for (var p = 0; p < 6; p++) {
  7841. var inCount = 8;
  7842. for (var i = 0; i < 8; i++) {
  7843. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7844. --inCount;
  7845. }
  7846. else {
  7847. break;
  7848. }
  7849. }
  7850. if (inCount === 0)
  7851. return false;
  7852. }
  7853. return true;
  7854. };
  7855. return BoundingBox;
  7856. })();
  7857. BABYLON.BoundingBox = BoundingBox;
  7858. })(BABYLON || (BABYLON = {}));
  7859. var BABYLON;
  7860. (function (BABYLON) {
  7861. var computeBoxExtents = function (axis, box) {
  7862. var p = BABYLON.Vector3.Dot(box.center, axis);
  7863. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7864. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7865. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7866. var r = r0 + r1 + r2;
  7867. return {
  7868. min: p - r,
  7869. max: p + r
  7870. };
  7871. };
  7872. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7873. var axisOverlap = function (axis, box0, box1) {
  7874. var result0 = computeBoxExtents(axis, box0);
  7875. var result1 = computeBoxExtents(axis, box1);
  7876. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7877. };
  7878. var BoundingInfo = (function () {
  7879. function BoundingInfo(minimum, maximum) {
  7880. this.minimum = minimum;
  7881. this.maximum = maximum;
  7882. this._isLocked = false;
  7883. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7884. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7885. }
  7886. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7887. get: function () {
  7888. return this._isLocked;
  7889. },
  7890. set: function (value) {
  7891. this._isLocked = value;
  7892. },
  7893. enumerable: true,
  7894. configurable: true
  7895. });
  7896. // Methods
  7897. BoundingInfo.prototype.update = function (world) {
  7898. if (this._isLocked) {
  7899. return;
  7900. }
  7901. this.boundingBox._update(world);
  7902. this.boundingSphere._update(world);
  7903. };
  7904. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7905. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7906. return false;
  7907. return this.boundingBox.isInFrustum(frustumPlanes);
  7908. };
  7909. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7910. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7911. };
  7912. BoundingInfo.prototype._checkCollision = function (collider) {
  7913. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7914. };
  7915. BoundingInfo.prototype.intersectsPoint = function (point) {
  7916. if (!this.boundingSphere.centerWorld) {
  7917. return false;
  7918. }
  7919. if (!this.boundingSphere.intersectsPoint(point)) {
  7920. return false;
  7921. }
  7922. if (!this.boundingBox.intersectsPoint(point)) {
  7923. return false;
  7924. }
  7925. return true;
  7926. };
  7927. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7928. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7929. return false;
  7930. }
  7931. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7932. return false;
  7933. }
  7934. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7935. return false;
  7936. }
  7937. if (!precise) {
  7938. return true;
  7939. }
  7940. var box0 = this.boundingBox;
  7941. var box1 = boundingInfo.boundingBox;
  7942. if (!axisOverlap(box0.directions[0], box0, box1))
  7943. return false;
  7944. if (!axisOverlap(box0.directions[1], box0, box1))
  7945. return false;
  7946. if (!axisOverlap(box0.directions[2], box0, box1))
  7947. return false;
  7948. if (!axisOverlap(box1.directions[0], box0, box1))
  7949. return false;
  7950. if (!axisOverlap(box1.directions[1], box0, box1))
  7951. return false;
  7952. if (!axisOverlap(box1.directions[2], box0, box1))
  7953. return false;
  7954. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7955. return false;
  7956. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7957. return false;
  7958. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7959. return false;
  7960. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7961. return false;
  7962. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7963. return false;
  7964. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7965. return false;
  7966. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7967. return false;
  7968. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7969. return false;
  7970. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7971. return false;
  7972. return true;
  7973. };
  7974. return BoundingInfo;
  7975. })();
  7976. BABYLON.BoundingInfo = BoundingInfo;
  7977. })(BABYLON || (BABYLON = {}));
  7978. var BABYLON;
  7979. (function (BABYLON) {
  7980. var AbstractMesh = (function (_super) {
  7981. __extends(AbstractMesh, _super);
  7982. // Constructor
  7983. function AbstractMesh(name, scene) {
  7984. var _this = this;
  7985. _super.call(this, name, scene);
  7986. // Properties
  7987. this.definedFacingForward = true; // orientation for POV movement & rotation
  7988. this.position = new BABYLON.Vector3(0, 0, 0);
  7989. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7990. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7991. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7992. this.visibility = 1.0;
  7993. this.alphaIndex = Number.MAX_VALUE;
  7994. this.infiniteDistance = false;
  7995. this.isVisible = true;
  7996. this.isPickable = true;
  7997. this.showBoundingBox = false;
  7998. this.showSubMeshesBoundingBox = false;
  7999. this.onDispose = null;
  8000. this.isBlocker = false;
  8001. this.renderingGroupId = 0;
  8002. this.receiveShadows = false;
  8003. this.renderOutline = false;
  8004. this.outlineColor = BABYLON.Color3.Red();
  8005. this.outlineWidth = 0.02;
  8006. this.renderOverlay = false;
  8007. this.overlayColor = BABYLON.Color3.Red();
  8008. this.overlayAlpha = 0.5;
  8009. this.hasVertexAlpha = false;
  8010. this.useVertexColors = true;
  8011. this.applyFog = true;
  8012. this.computeBonesUsingShaders = true;
  8013. this.scalingDeterminant = 1;
  8014. this.numBoneInfluencers = 4;
  8015. this.useOctreeForRenderingSelection = true;
  8016. this.useOctreeForPicking = true;
  8017. this.useOctreeForCollisions = true;
  8018. this.layerMask = 0x0FFFFFFF;
  8019. this.alwaysSelectAsActiveMesh = false;
  8020. // Physics
  8021. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8022. // Collisions
  8023. this._checkCollisions = false;
  8024. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8025. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8026. this._collider = new BABYLON.Collider();
  8027. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8028. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8029. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8030. // Edges
  8031. this.edgesWidth = 1;
  8032. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8033. // Cache
  8034. this._localWorld = BABYLON.Matrix.Zero();
  8035. this._worldMatrix = BABYLON.Matrix.Zero();
  8036. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8037. this._absolutePosition = BABYLON.Vector3.Zero();
  8038. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8039. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8040. this._isDirty = false;
  8041. this._pivotMatrix = BABYLON.Matrix.Identity();
  8042. this._isDisposed = false;
  8043. this._renderId = 0;
  8044. this._intersectionsInProgress = new Array();
  8045. this._onAfterWorldMatrixUpdate = new Array();
  8046. this._isWorldMatrixFrozen = false;
  8047. this._unIndexed = false;
  8048. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8049. if (collidedMesh === void 0) { collidedMesh = null; }
  8050. //TODO move this to the collision coordinator!
  8051. if (_this.getScene().workerCollisions)
  8052. newPosition.multiplyInPlace(_this._collider.radius);
  8053. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8054. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8055. _this.position.addInPlace(_this._diffPositionForCollisions);
  8056. }
  8057. if (_this.onCollide && collidedMesh) {
  8058. _this.onCollide(collidedMesh);
  8059. }
  8060. if (_this.onCollisionPositionChange) {
  8061. _this.onCollisionPositionChange(_this.position);
  8062. }
  8063. };
  8064. scene.addMesh(this);
  8065. }
  8066. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8067. get: function () {
  8068. return AbstractMesh._BILLBOARDMODE_NONE;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8074. get: function () {
  8075. return AbstractMesh._BILLBOARDMODE_X;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8081. get: function () {
  8082. return AbstractMesh._BILLBOARDMODE_Y;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8088. get: function () {
  8089. return AbstractMesh._BILLBOARDMODE_Z;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8095. get: function () {
  8096. return AbstractMesh._BILLBOARDMODE_ALL;
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8102. get: function () {
  8103. return this._skeleton;
  8104. },
  8105. set: function (value) {
  8106. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8107. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8108. }
  8109. if (value && value.needInitialSkinMatrix) {
  8110. value._registerMeshWithPoseMatrix(this);
  8111. }
  8112. this._skeleton = value;
  8113. if (!this._skeleton) {
  8114. this._bonesTransformMatrices = null;
  8115. }
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. // Methods
  8121. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8122. this._poseMatrix.copyFrom(matrix);
  8123. };
  8124. AbstractMesh.prototype.getPoseMatrix = function () {
  8125. return this._poseMatrix;
  8126. };
  8127. AbstractMesh.prototype.disableEdgesRendering = function () {
  8128. if (this._edgesRenderer !== undefined) {
  8129. this._edgesRenderer.dispose();
  8130. this._edgesRenderer = undefined;
  8131. }
  8132. };
  8133. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8134. if (epsilon === void 0) { epsilon = 0.95; }
  8135. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8136. this.disableEdgesRendering();
  8137. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8138. };
  8139. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8140. get: function () {
  8141. return false;
  8142. },
  8143. enumerable: true,
  8144. configurable: true
  8145. });
  8146. AbstractMesh.prototype.getLOD = function (camera) {
  8147. return this;
  8148. };
  8149. AbstractMesh.prototype.getTotalVertices = function () {
  8150. return 0;
  8151. };
  8152. AbstractMesh.prototype.getIndices = function () {
  8153. return null;
  8154. };
  8155. AbstractMesh.prototype.getVerticesData = function (kind) {
  8156. return null;
  8157. };
  8158. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8159. return false;
  8160. };
  8161. AbstractMesh.prototype.getBoundingInfo = function () {
  8162. if (this._masterMesh) {
  8163. return this._masterMesh.getBoundingInfo();
  8164. }
  8165. if (!this._boundingInfo) {
  8166. this._updateBoundingInfo();
  8167. }
  8168. return this._boundingInfo;
  8169. };
  8170. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8171. get: function () {
  8172. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. AbstractMesh.prototype._preActivate = function () {
  8178. };
  8179. AbstractMesh.prototype._activate = function (renderId) {
  8180. this._renderId = renderId;
  8181. };
  8182. AbstractMesh.prototype.getWorldMatrix = function () {
  8183. if (this._masterMesh) {
  8184. return this._masterMesh.getWorldMatrix();
  8185. }
  8186. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8187. this.computeWorldMatrix();
  8188. }
  8189. return this._worldMatrix;
  8190. };
  8191. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8192. get: function () {
  8193. return this._worldMatrix;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8199. get: function () {
  8200. return this._absolutePosition;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8206. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8207. this.computeWorldMatrix(true);
  8208. this._isWorldMatrixFrozen = true;
  8209. };
  8210. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8211. this._isWorldMatrixFrozen = false;
  8212. this.computeWorldMatrix(true);
  8213. };
  8214. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8215. get: function () {
  8216. return this._isWorldMatrixFrozen;
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8222. axis.normalize();
  8223. if (!this.rotationQuaternion) {
  8224. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8225. this.rotation = BABYLON.Vector3.Zero();
  8226. }
  8227. var rotationQuaternion;
  8228. if (!space || space === BABYLON.Space.LOCAL) {
  8229. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8230. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8231. }
  8232. else {
  8233. if (this.parent) {
  8234. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8235. invertParentWorldMatrix.invert();
  8236. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8237. }
  8238. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8239. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8240. }
  8241. };
  8242. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8243. var displacementVector = axis.scale(distance);
  8244. if (!space || space === BABYLON.Space.LOCAL) {
  8245. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8246. this.setPositionWithLocalVector(tempV3);
  8247. }
  8248. else {
  8249. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8250. }
  8251. };
  8252. AbstractMesh.prototype.getAbsolutePosition = function () {
  8253. this.computeWorldMatrix();
  8254. return this._absolutePosition;
  8255. };
  8256. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8257. if (!absolutePosition) {
  8258. return;
  8259. }
  8260. var absolutePositionX;
  8261. var absolutePositionY;
  8262. var absolutePositionZ;
  8263. if (absolutePosition.x === undefined) {
  8264. if (arguments.length < 3) {
  8265. return;
  8266. }
  8267. absolutePositionX = arguments[0];
  8268. absolutePositionY = arguments[1];
  8269. absolutePositionZ = arguments[2];
  8270. }
  8271. else {
  8272. absolutePositionX = absolutePosition.x;
  8273. absolutePositionY = absolutePosition.y;
  8274. absolutePositionZ = absolutePosition.z;
  8275. }
  8276. if (this.parent) {
  8277. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8278. invertParentWorldMatrix.invert();
  8279. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8280. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8281. }
  8282. else {
  8283. this.position.x = absolutePositionX;
  8284. this.position.y = absolutePositionY;
  8285. this.position.z = absolutePositionZ;
  8286. }
  8287. };
  8288. // ================================== Point of View Movement =================================
  8289. /**
  8290. * Perform relative position change from the point of view of behind the front of the mesh.
  8291. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8292. * Supports definition of mesh facing forward or backward.
  8293. * @param {number} amountRight
  8294. * @param {number} amountUp
  8295. * @param {number} amountForward
  8296. */
  8297. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8298. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8299. };
  8300. /**
  8301. * Calculate relative position change from the point of view of behind the front of the mesh.
  8302. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8303. * Supports definition of mesh facing forward or backward.
  8304. * @param {number} amountRight
  8305. * @param {number} amountUp
  8306. * @param {number} amountForward
  8307. */
  8308. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8309. var rotMatrix = new BABYLON.Matrix();
  8310. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8311. rotQuaternion.toRotationMatrix(rotMatrix);
  8312. var translationDelta = BABYLON.Vector3.Zero();
  8313. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8315. return translationDelta;
  8316. };
  8317. // ================================== Point of View Rotation =================================
  8318. /**
  8319. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8320. * Supports definition of mesh facing forward or backward.
  8321. * @param {number} flipBack
  8322. * @param {number} twirlClockwise
  8323. * @param {number} tiltRight
  8324. */
  8325. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8326. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8327. };
  8328. /**
  8329. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8330. * Supports definition of mesh facing forward or backward.
  8331. * @param {number} flipBack
  8332. * @param {number} twirlClockwise
  8333. * @param {number} tiltRight
  8334. */
  8335. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8336. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8337. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8338. };
  8339. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8340. this._pivotMatrix = matrix;
  8341. this._cache.pivotMatrixUpdated = true;
  8342. };
  8343. AbstractMesh.prototype.getPivotMatrix = function () {
  8344. return this._pivotMatrix;
  8345. };
  8346. AbstractMesh.prototype._isSynchronized = function () {
  8347. if (this._isDirty) {
  8348. return false;
  8349. }
  8350. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8351. return false;
  8352. if (this._cache.pivotMatrixUpdated) {
  8353. return false;
  8354. }
  8355. if (this.infiniteDistance) {
  8356. return false;
  8357. }
  8358. if (!this._cache.position.equals(this.position))
  8359. return false;
  8360. if (this.rotationQuaternion) {
  8361. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8362. return false;
  8363. }
  8364. else {
  8365. if (!this._cache.rotation.equals(this.rotation))
  8366. return false;
  8367. }
  8368. if (!this._cache.scaling.equals(this.scaling))
  8369. return false;
  8370. return true;
  8371. };
  8372. AbstractMesh.prototype._initCache = function () {
  8373. _super.prototype._initCache.call(this);
  8374. this._cache.localMatrixUpdated = false;
  8375. this._cache.position = BABYLON.Vector3.Zero();
  8376. this._cache.scaling = BABYLON.Vector3.Zero();
  8377. this._cache.rotation = BABYLON.Vector3.Zero();
  8378. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8379. this._cache.billboardMode = -1;
  8380. };
  8381. AbstractMesh.prototype.markAsDirty = function (property) {
  8382. if (property === "rotation") {
  8383. this.rotationQuaternion = null;
  8384. }
  8385. this._currentRenderId = Number.MAX_VALUE;
  8386. this._isDirty = true;
  8387. };
  8388. AbstractMesh.prototype._updateBoundingInfo = function () {
  8389. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8390. this._boundingInfo.update(this.worldMatrixFromCache);
  8391. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8392. };
  8393. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8394. if (!this.subMeshes) {
  8395. return;
  8396. }
  8397. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8398. var subMesh = this.subMeshes[subIndex];
  8399. if (!subMesh.IsGlobal) {
  8400. subMesh.updateBoundingInfo(matrix);
  8401. }
  8402. }
  8403. };
  8404. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8405. if (this._isWorldMatrixFrozen) {
  8406. return this._worldMatrix;
  8407. }
  8408. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8409. this._currentRenderId = this.getScene().getRenderId();
  8410. return this._worldMatrix;
  8411. }
  8412. this._cache.position.copyFrom(this.position);
  8413. this._cache.scaling.copyFrom(this.scaling);
  8414. this._cache.pivotMatrixUpdated = false;
  8415. this._cache.billboardMode = this.billboardMode;
  8416. this._currentRenderId = this.getScene().getRenderId();
  8417. this._isDirty = false;
  8418. // Scaling
  8419. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8420. // Rotation
  8421. if (this.rotationQuaternion) {
  8422. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8423. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8424. }
  8425. else {
  8426. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8427. this._cache.rotation.copyFrom(this.rotation);
  8428. }
  8429. // Translation
  8430. if (this.infiniteDistance && !this.parent) {
  8431. var camera = this.getScene().activeCamera;
  8432. if (camera) {
  8433. var cameraWorldMatrix = camera.getWorldMatrix();
  8434. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8435. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8436. }
  8437. }
  8438. else {
  8439. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8440. }
  8441. // Composing transformations
  8442. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8443. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8444. // Billboarding
  8445. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8446. var localPosition = this.position.clone();
  8447. var zero = this.getScene().activeCamera.globalPosition.clone();
  8448. if (this.parent && this.parent.position) {
  8449. localPosition.addInPlace(this.parent.position);
  8450. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8451. }
  8452. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8453. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8454. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8455. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8456. zero.y = localPosition.y + 0.001;
  8457. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8458. zero.z = localPosition.z + 0.001;
  8459. }
  8460. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8461. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8462. BABYLON.Tmp.Matrix[3].invert();
  8463. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8464. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8465. }
  8466. // Local world
  8467. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8468. // Parent
  8469. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8470. this._markSyncedWithParent();
  8471. if (this._meshToBoneReferal) {
  8472. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8473. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8474. }
  8475. else {
  8476. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8477. }
  8478. }
  8479. else {
  8480. this._worldMatrix.copyFrom(this._localWorld);
  8481. }
  8482. // Bounding info
  8483. this._updateBoundingInfo();
  8484. // Absolute position
  8485. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8486. // Callbacks
  8487. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8488. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8489. }
  8490. if (!this._poseMatrix) {
  8491. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8492. }
  8493. return this._worldMatrix;
  8494. };
  8495. /**
  8496. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8497. * @param func: callback function to add
  8498. */
  8499. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8500. this._onAfterWorldMatrixUpdate.push(func);
  8501. };
  8502. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8503. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8504. if (index > -1) {
  8505. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8506. }
  8507. };
  8508. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8509. this.computeWorldMatrix();
  8510. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8511. };
  8512. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8513. this.computeWorldMatrix();
  8514. var invLocalWorldMatrix = this._localWorld.clone();
  8515. invLocalWorldMatrix.invert();
  8516. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8517. };
  8518. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8519. this.computeWorldMatrix(true);
  8520. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8521. };
  8522. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8523. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8524. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8525. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8526. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8527. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8528. /// <returns>Mesh oriented towards targetMesh</returns>
  8529. yawCor = yawCor || 0; // default to zero if undefined
  8530. pitchCor = pitchCor || 0;
  8531. rollCor = rollCor || 0;
  8532. var dv = targetPoint.subtract(this.position);
  8533. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8534. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8535. var pitch = Math.atan2(dv.y, len);
  8536. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8537. };
  8538. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8539. this._meshToBoneReferal = affectedMesh;
  8540. this.parent = bone;
  8541. if (bone.getWorldMatrix().determinant() < 0) {
  8542. this.scalingDeterminant *= -1;
  8543. }
  8544. };
  8545. AbstractMesh.prototype.detachFromBone = function () {
  8546. if (this.parent.getWorldMatrix().determinant() < 0) {
  8547. this.scalingDeterminant *= -1;
  8548. }
  8549. this._meshToBoneReferal = null;
  8550. this.parent = null;
  8551. };
  8552. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8553. return this._boundingInfo.isInFrustum(frustumPlanes);
  8554. };
  8555. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8556. if (!camera) {
  8557. camera = this.getScene().activeCamera;
  8558. }
  8559. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8560. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8561. return false;
  8562. }
  8563. return true;
  8564. };
  8565. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8566. if (!this._boundingInfo || !mesh._boundingInfo) {
  8567. return false;
  8568. }
  8569. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8570. };
  8571. AbstractMesh.prototype.intersectsPoint = function (point) {
  8572. if (!this._boundingInfo) {
  8573. return false;
  8574. }
  8575. return this._boundingInfo.intersectsPoint(point);
  8576. };
  8577. // Physics
  8578. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8579. var physicsEngine = this.getScene().getPhysicsEngine();
  8580. if (!physicsEngine) {
  8581. return null;
  8582. }
  8583. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8584. if (impostor.impostor) {
  8585. // Old API
  8586. options = impostor;
  8587. impostor = impostor.impostor;
  8588. }
  8589. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8590. physicsEngine._unregisterMesh(this);
  8591. return null;
  8592. }
  8593. if (!options) {
  8594. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8595. }
  8596. else {
  8597. if (!options.mass && options.mass !== 0)
  8598. options.mass = 0;
  8599. if (!options.friction && options.friction !== 0)
  8600. options.friction = 0.2;
  8601. if (!options.restitution && options.restitution !== 0)
  8602. options.restitution = 0.2;
  8603. }
  8604. this._physicImpostor = impostor;
  8605. this._physicsMass = options.mass;
  8606. this._physicsFriction = options.friction;
  8607. this._physicRestitution = options.restitution;
  8608. return physicsEngine._registerMesh(this, impostor, options);
  8609. };
  8610. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8611. if (!this._physicImpostor) {
  8612. return BABYLON.PhysicsEngine.NoImpostor;
  8613. }
  8614. return this._physicImpostor;
  8615. };
  8616. AbstractMesh.prototype.getPhysicsMass = function () {
  8617. if (!this._physicsMass) {
  8618. return 0;
  8619. }
  8620. return this._physicsMass;
  8621. };
  8622. AbstractMesh.prototype.getPhysicsFriction = function () {
  8623. if (!this._physicsFriction) {
  8624. return 0;
  8625. }
  8626. return this._physicsFriction;
  8627. };
  8628. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8629. if (!this._physicRestitution) {
  8630. return 0;
  8631. }
  8632. return this._physicRestitution;
  8633. };
  8634. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8635. if (!camera) {
  8636. camera = this.getScene().activeCamera;
  8637. }
  8638. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8639. };
  8640. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8641. if (!camera) {
  8642. camera = this.getScene().activeCamera;
  8643. }
  8644. return this.absolutePosition.subtract(camera.position).length();
  8645. };
  8646. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8647. if (!this._physicImpostor) {
  8648. return;
  8649. }
  8650. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8651. };
  8652. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8653. if (!this._physicImpostor) {
  8654. return;
  8655. }
  8656. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8657. };
  8658. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8659. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8660. this.updatePhysicsBody();
  8661. };
  8662. AbstractMesh.prototype.updatePhysicsBody = function () {
  8663. if (!this._physicImpostor) {
  8664. return;
  8665. }
  8666. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8667. };
  8668. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8669. // Collisions
  8670. get: function () {
  8671. return this._checkCollisions;
  8672. },
  8673. set: function (collisionEnabled) {
  8674. this._checkCollisions = collisionEnabled;
  8675. if (this.getScene().workerCollisions) {
  8676. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8677. }
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8683. var globalPosition = this.getAbsolutePosition();
  8684. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8685. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8686. this._collider.radius = this.ellipsoid;
  8687. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8688. };
  8689. // Submeshes octree
  8690. /**
  8691. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8692. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8693. */
  8694. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8695. if (maxCapacity === void 0) { maxCapacity = 64; }
  8696. if (maxDepth === void 0) { maxDepth = 2; }
  8697. if (!this._submeshesOctree) {
  8698. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8699. }
  8700. this.computeWorldMatrix(true);
  8701. // Update octree
  8702. var bbox = this.getBoundingInfo().boundingBox;
  8703. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8704. return this._submeshesOctree;
  8705. };
  8706. // Collisions
  8707. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8708. this._generatePointsArray();
  8709. // Transformation
  8710. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8711. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8712. subMesh._lastColliderWorldVertices = [];
  8713. subMesh._trianglePlanes = [];
  8714. var start = subMesh.verticesStart;
  8715. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8716. for (var i = start; i < end; i++) {
  8717. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8718. }
  8719. }
  8720. // Collide
  8721. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8722. if (collider.collisionFound) {
  8723. collider.collidedMesh = this;
  8724. }
  8725. };
  8726. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8727. var subMeshes;
  8728. var len;
  8729. // Octrees
  8730. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8731. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8732. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8733. len = intersections.length;
  8734. subMeshes = intersections.data;
  8735. }
  8736. else {
  8737. subMeshes = this.subMeshes;
  8738. len = subMeshes.length;
  8739. }
  8740. for (var index = 0; index < len; index++) {
  8741. var subMesh = subMeshes[index];
  8742. // Bounding test
  8743. if (len > 1 && !subMesh._checkCollision(collider))
  8744. continue;
  8745. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8746. }
  8747. };
  8748. AbstractMesh.prototype._checkCollision = function (collider) {
  8749. // Bounding box test
  8750. if (!this._boundingInfo._checkCollision(collider))
  8751. return;
  8752. // Transformation matrix
  8753. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8754. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8755. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8756. };
  8757. // Picking
  8758. AbstractMesh.prototype._generatePointsArray = function () {
  8759. return false;
  8760. };
  8761. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8762. var pickingInfo = new BABYLON.PickingInfo();
  8763. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8764. return pickingInfo;
  8765. }
  8766. if (!this._generatePointsArray()) {
  8767. return pickingInfo;
  8768. }
  8769. var intersectInfo = null;
  8770. // Octrees
  8771. var subMeshes;
  8772. var len;
  8773. if (this._submeshesOctree && this.useOctreeForPicking) {
  8774. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8775. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8776. len = intersections.length;
  8777. subMeshes = intersections.data;
  8778. }
  8779. else {
  8780. subMeshes = this.subMeshes;
  8781. len = subMeshes.length;
  8782. }
  8783. for (var index = 0; index < len; index++) {
  8784. var subMesh = subMeshes[index];
  8785. // Bounding test
  8786. if (len > 1 && !subMesh.canIntersects(ray))
  8787. continue;
  8788. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8789. if (currentIntersectInfo) {
  8790. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8791. intersectInfo = currentIntersectInfo;
  8792. intersectInfo.subMeshId = index;
  8793. if (fastCheck) {
  8794. break;
  8795. }
  8796. }
  8797. }
  8798. }
  8799. if (intersectInfo) {
  8800. // Get picked point
  8801. var world = this.getWorldMatrix();
  8802. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8803. var direction = ray.direction.clone();
  8804. direction = direction.scale(intersectInfo.distance);
  8805. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8806. var pickedPoint = worldOrigin.add(worldDirection);
  8807. // Return result
  8808. pickingInfo.hit = true;
  8809. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8810. pickingInfo.pickedPoint = pickedPoint;
  8811. pickingInfo.pickedMesh = this;
  8812. pickingInfo.bu = intersectInfo.bu;
  8813. pickingInfo.bv = intersectInfo.bv;
  8814. pickingInfo.faceId = intersectInfo.faceId;
  8815. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8816. return pickingInfo;
  8817. }
  8818. return pickingInfo;
  8819. };
  8820. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8821. return null;
  8822. };
  8823. AbstractMesh.prototype.releaseSubMeshes = function () {
  8824. if (this.subMeshes) {
  8825. while (this.subMeshes.length) {
  8826. this.subMeshes[0].dispose();
  8827. }
  8828. }
  8829. else {
  8830. this.subMeshes = new Array();
  8831. }
  8832. };
  8833. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8834. var index;
  8835. // Action manager
  8836. if (this.actionManager) {
  8837. this.actionManager.dispose();
  8838. this.actionManager = null;
  8839. }
  8840. // Skeleton
  8841. this.skeleton = null;
  8842. // Animations
  8843. this.getScene().stopAnimation(this);
  8844. // Physics
  8845. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8846. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8847. }
  8848. // Intersections in progress
  8849. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8850. var other = this._intersectionsInProgress[index];
  8851. var pos = other._intersectionsInProgress.indexOf(this);
  8852. other._intersectionsInProgress.splice(pos, 1);
  8853. }
  8854. this._intersectionsInProgress = [];
  8855. // Edges
  8856. if (this._edgesRenderer) {
  8857. this._edgesRenderer.dispose();
  8858. this._edgesRenderer = null;
  8859. }
  8860. // SubMeshes
  8861. this.releaseSubMeshes();
  8862. // Remove from scene
  8863. this.getScene().removeMesh(this);
  8864. if (!doNotRecurse) {
  8865. // Particles
  8866. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8867. if (this.getScene().particleSystems[index].emitter === this) {
  8868. this.getScene().particleSystems[index].dispose();
  8869. index--;
  8870. }
  8871. }
  8872. // Children
  8873. var objects = this.getScene().meshes.slice(0);
  8874. for (index = 0; index < objects.length; index++) {
  8875. if (objects[index].parent === this) {
  8876. objects[index].dispose();
  8877. }
  8878. }
  8879. }
  8880. else {
  8881. for (index = 0; index < this.getScene().meshes.length; index++) {
  8882. var obj = this.getScene().meshes[index];
  8883. if (obj.parent === this) {
  8884. obj.parent = null;
  8885. obj.computeWorldMatrix(true);
  8886. }
  8887. }
  8888. }
  8889. this._onAfterWorldMatrixUpdate = [];
  8890. this._isDisposed = true;
  8891. // Callback
  8892. if (this.onDispose) {
  8893. this.onDispose();
  8894. }
  8895. };
  8896. // Statics
  8897. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8898. AbstractMesh._BILLBOARDMODE_X = 1;
  8899. AbstractMesh._BILLBOARDMODE_Y = 2;
  8900. AbstractMesh._BILLBOARDMODE_Z = 4;
  8901. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8902. return AbstractMesh;
  8903. })(BABYLON.Node);
  8904. BABYLON.AbstractMesh = AbstractMesh;
  8905. })(BABYLON || (BABYLON = {}));
  8906. var BABYLON;
  8907. (function (BABYLON) {
  8908. var Light = (function (_super) {
  8909. __extends(Light, _super);
  8910. function Light(name, scene) {
  8911. _super.call(this, name, scene);
  8912. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8913. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8914. this.intensity = 1.0;
  8915. this.range = Number.MAX_VALUE;
  8916. this.includeOnlyWithLayerMask = 0;
  8917. this.includedOnlyMeshes = new Array();
  8918. this.excludedMeshes = new Array();
  8919. this.excludeWithLayerMask = 0;
  8920. // PBR Properties.
  8921. this.radius = 0.00001;
  8922. this._excludedMeshesIds = new Array();
  8923. this._includedOnlyMeshesIds = new Array();
  8924. scene.addLight(this);
  8925. }
  8926. Light.prototype.getShadowGenerator = function () {
  8927. return this._shadowGenerator;
  8928. };
  8929. Light.prototype.getAbsolutePosition = function () {
  8930. return BABYLON.Vector3.Zero();
  8931. };
  8932. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8933. };
  8934. Light.prototype._getWorldMatrix = function () {
  8935. return BABYLON.Matrix.Identity();
  8936. };
  8937. Light.prototype.canAffectMesh = function (mesh) {
  8938. if (!mesh) {
  8939. return true;
  8940. }
  8941. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8942. return false;
  8943. }
  8944. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8945. return false;
  8946. }
  8947. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8948. return false;
  8949. }
  8950. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8951. return false;
  8952. }
  8953. return true;
  8954. };
  8955. Light.prototype.getWorldMatrix = function () {
  8956. this._currentRenderId = this.getScene().getRenderId();
  8957. var worldMatrix = this._getWorldMatrix();
  8958. if (this.parent && this.parent.getWorldMatrix) {
  8959. if (!this._parentedWorldMatrix) {
  8960. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8961. }
  8962. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8963. this._markSyncedWithParent();
  8964. return this._parentedWorldMatrix;
  8965. }
  8966. return worldMatrix;
  8967. };
  8968. Light.prototype.dispose = function () {
  8969. if (this._shadowGenerator) {
  8970. this._shadowGenerator.dispose();
  8971. this._shadowGenerator = null;
  8972. }
  8973. // Animations
  8974. this.getScene().stopAnimation(this);
  8975. // Remove from scene
  8976. this.getScene().removeLight(this);
  8977. };
  8978. Light.prototype.getTypeID = function () {
  8979. return 0;
  8980. };
  8981. Light.prototype.clone = function (name) {
  8982. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  8983. };
  8984. Light.prototype.serialize = function () {
  8985. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  8986. // Type
  8987. serializationObject.type = this.getTypeID();
  8988. // Parent
  8989. if (this.parent) {
  8990. serializationObject.parentId = this.parent.id;
  8991. }
  8992. return serializationObject;
  8993. };
  8994. Light.GetConstructorFromName = function (type, name, scene) {
  8995. switch (type) {
  8996. case 0:
  8997. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  8998. case 1:
  8999. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9000. case 2:
  9001. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9002. case 3:
  9003. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9004. }
  9005. };
  9006. Light.Parse = function (parsedLight, scene) {
  9007. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9008. // Inclusion / exclusions
  9009. if (parsedLight.excludedMeshesIds) {
  9010. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9011. }
  9012. if (parsedLight.includedOnlyMeshesIds) {
  9013. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9014. }
  9015. // Parent
  9016. if (parsedLight.parentId) {
  9017. light._waitingParentId = parsedLight.parentId;
  9018. }
  9019. // Animations
  9020. if (parsedLight.animations) {
  9021. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9022. var parsedAnimation = parsedLight.animations[animationIndex];
  9023. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9024. }
  9025. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9026. }
  9027. if (parsedLight.autoAnimate) {
  9028. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  9029. }
  9030. return light;
  9031. };
  9032. __decorate([
  9033. BABYLON.serializeAsColor3()
  9034. ], Light.prototype, "diffuse", void 0);
  9035. __decorate([
  9036. BABYLON.serializeAsColor3()
  9037. ], Light.prototype, "specular", void 0);
  9038. __decorate([
  9039. BABYLON.serialize()
  9040. ], Light.prototype, "intensity", void 0);
  9041. __decorate([
  9042. BABYLON.serialize()
  9043. ], Light.prototype, "range", void 0);
  9044. __decorate([
  9045. BABYLON.serialize()
  9046. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9047. __decorate([
  9048. BABYLON.serialize()
  9049. ], Light.prototype, "radius", void 0);
  9050. return Light;
  9051. })(BABYLON.Node);
  9052. BABYLON.Light = Light;
  9053. })(BABYLON || (BABYLON = {}));
  9054. var BABYLON;
  9055. (function (BABYLON) {
  9056. var PointLight = (function (_super) {
  9057. __extends(PointLight, _super);
  9058. function PointLight(name, position, scene) {
  9059. _super.call(this, name, scene);
  9060. this.position = position;
  9061. }
  9062. PointLight.prototype.getAbsolutePosition = function () {
  9063. return this.transformedPosition ? this.transformedPosition : this.position;
  9064. };
  9065. PointLight.prototype.computeTransformedPosition = function () {
  9066. if (this.parent && this.parent.getWorldMatrix) {
  9067. if (!this.transformedPosition) {
  9068. this.transformedPosition = BABYLON.Vector3.Zero();
  9069. }
  9070. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9071. return true;
  9072. }
  9073. return false;
  9074. };
  9075. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9076. if (this.parent && this.parent.getWorldMatrix) {
  9077. this.computeTransformedPosition();
  9078. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9079. return;
  9080. }
  9081. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9082. };
  9083. PointLight.prototype.needCube = function () {
  9084. return true;
  9085. };
  9086. PointLight.prototype.supportsVSM = function () {
  9087. return false;
  9088. };
  9089. PointLight.prototype.needRefreshPerFrame = function () {
  9090. return false;
  9091. };
  9092. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9093. switch (faceIndex) {
  9094. case 0:
  9095. return new BABYLON.Vector3(1, 0, 0);
  9096. case 1:
  9097. return new BABYLON.Vector3(-1, 0, 0);
  9098. case 2:
  9099. return new BABYLON.Vector3(0, -1, 0);
  9100. case 3:
  9101. return new BABYLON.Vector3(0, 1, 0);
  9102. case 4:
  9103. return new BABYLON.Vector3(0, 0, 1);
  9104. case 5:
  9105. return new BABYLON.Vector3(0, 0, -1);
  9106. }
  9107. return BABYLON.Vector3.Zero();
  9108. };
  9109. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9110. var activeCamera = this.getScene().activeCamera;
  9111. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9112. };
  9113. PointLight.prototype._getWorldMatrix = function () {
  9114. if (!this._worldMatrix) {
  9115. this._worldMatrix = BABYLON.Matrix.Identity();
  9116. }
  9117. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9118. return this._worldMatrix;
  9119. };
  9120. PointLight.prototype.getTypeID = function () {
  9121. return 0;
  9122. };
  9123. __decorate([
  9124. BABYLON.serializeAsVector3()
  9125. ], PointLight.prototype, "position", void 0);
  9126. return PointLight;
  9127. })(BABYLON.Light);
  9128. BABYLON.PointLight = PointLight;
  9129. })(BABYLON || (BABYLON = {}));
  9130. var BABYLON;
  9131. (function (BABYLON) {
  9132. var SpotLight = (function (_super) {
  9133. __extends(SpotLight, _super);
  9134. function SpotLight(name, position, direction, angle, exponent, scene) {
  9135. _super.call(this, name, scene);
  9136. this.position = position;
  9137. this.direction = direction;
  9138. this.angle = angle;
  9139. this.exponent = exponent;
  9140. }
  9141. SpotLight.prototype.getAbsolutePosition = function () {
  9142. return this.transformedPosition ? this.transformedPosition : this.position;
  9143. };
  9144. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9145. var activeCamera = this.getScene().activeCamera;
  9146. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9147. };
  9148. SpotLight.prototype.needCube = function () {
  9149. return false;
  9150. };
  9151. SpotLight.prototype.supportsVSM = function () {
  9152. return true;
  9153. };
  9154. SpotLight.prototype.needRefreshPerFrame = function () {
  9155. return false;
  9156. };
  9157. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9158. return this.direction;
  9159. };
  9160. SpotLight.prototype.setDirectionToTarget = function (target) {
  9161. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9162. return this.direction;
  9163. };
  9164. SpotLight.prototype.computeTransformedPosition = function () {
  9165. if (this.parent && this.parent.getWorldMatrix) {
  9166. if (!this.transformedPosition) {
  9167. this.transformedPosition = BABYLON.Vector3.Zero();
  9168. }
  9169. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9170. return true;
  9171. }
  9172. return false;
  9173. };
  9174. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9175. var normalizeDirection;
  9176. if (this.parent && this.parent.getWorldMatrix) {
  9177. if (!this._transformedDirection) {
  9178. this._transformedDirection = BABYLON.Vector3.Zero();
  9179. }
  9180. this.computeTransformedPosition();
  9181. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9182. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9183. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9184. }
  9185. else {
  9186. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9187. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9188. }
  9189. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9190. };
  9191. SpotLight.prototype._getWorldMatrix = function () {
  9192. if (!this._worldMatrix) {
  9193. this._worldMatrix = BABYLON.Matrix.Identity();
  9194. }
  9195. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9196. return this._worldMatrix;
  9197. };
  9198. SpotLight.prototype.getTypeID = function () {
  9199. return 2;
  9200. };
  9201. __decorate([
  9202. BABYLON.serializeAsVector3()
  9203. ], SpotLight.prototype, "position", void 0);
  9204. __decorate([
  9205. BABYLON.serializeAsVector3()
  9206. ], SpotLight.prototype, "direction", void 0);
  9207. __decorate([
  9208. BABYLON.serialize()
  9209. ], SpotLight.prototype, "angle", void 0);
  9210. __decorate([
  9211. BABYLON.serialize()
  9212. ], SpotLight.prototype, "exponent", void 0);
  9213. return SpotLight;
  9214. })(BABYLON.Light);
  9215. BABYLON.SpotLight = SpotLight;
  9216. })(BABYLON || (BABYLON = {}));
  9217. var BABYLON;
  9218. (function (BABYLON) {
  9219. var HemisphericLight = (function (_super) {
  9220. __extends(HemisphericLight, _super);
  9221. function HemisphericLight(name, direction, scene) {
  9222. _super.call(this, name, scene);
  9223. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9224. this.direction = direction;
  9225. }
  9226. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9227. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9228. return this.direction;
  9229. };
  9230. HemisphericLight.prototype.getShadowGenerator = function () {
  9231. return null;
  9232. };
  9233. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9234. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9235. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9236. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9237. };
  9238. HemisphericLight.prototype._getWorldMatrix = function () {
  9239. if (!this._worldMatrix) {
  9240. this._worldMatrix = BABYLON.Matrix.Identity();
  9241. }
  9242. return this._worldMatrix;
  9243. };
  9244. HemisphericLight.prototype.getTypeID = function () {
  9245. return 3;
  9246. };
  9247. __decorate([
  9248. BABYLON.serializeAsColor3()
  9249. ], HemisphericLight.prototype, "groundColor", void 0);
  9250. __decorate([
  9251. BABYLON.serializeAsVector3()
  9252. ], HemisphericLight.prototype, "direction", void 0);
  9253. return HemisphericLight;
  9254. })(BABYLON.Light);
  9255. BABYLON.HemisphericLight = HemisphericLight;
  9256. })(BABYLON || (BABYLON = {}));
  9257. var BABYLON;
  9258. (function (BABYLON) {
  9259. var DirectionalLight = (function (_super) {
  9260. __extends(DirectionalLight, _super);
  9261. function DirectionalLight(name, direction, scene) {
  9262. _super.call(this, name, scene);
  9263. this.shadowOrthoScale = 0.5;
  9264. this.autoUpdateExtends = true;
  9265. // Cache
  9266. this._orthoLeft = Number.MAX_VALUE;
  9267. this._orthoRight = Number.MIN_VALUE;
  9268. this._orthoTop = Number.MIN_VALUE;
  9269. this._orthoBottom = Number.MAX_VALUE;
  9270. this.position = direction.scale(-1);
  9271. this.direction = direction;
  9272. }
  9273. DirectionalLight.prototype.getAbsolutePosition = function () {
  9274. return this.transformedPosition ? this.transformedPosition : this.position;
  9275. };
  9276. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9277. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9278. return this.direction;
  9279. };
  9280. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9281. var activeCamera = this.getScene().activeCamera;
  9282. // Check extends
  9283. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9284. var tempVector3 = BABYLON.Vector3.Zero();
  9285. this._orthoLeft = Number.MAX_VALUE;
  9286. this._orthoRight = Number.MIN_VALUE;
  9287. this._orthoTop = Number.MIN_VALUE;
  9288. this._orthoBottom = Number.MAX_VALUE;
  9289. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9290. var mesh = renderList[meshIndex];
  9291. if (!mesh) {
  9292. continue;
  9293. }
  9294. var boundingInfo = mesh.getBoundingInfo();
  9295. if (!boundingInfo) {
  9296. continue;
  9297. }
  9298. var boundingBox = boundingInfo.boundingBox;
  9299. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9300. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9301. if (tempVector3.x < this._orthoLeft)
  9302. this._orthoLeft = tempVector3.x;
  9303. if (tempVector3.y < this._orthoBottom)
  9304. this._orthoBottom = tempVector3.y;
  9305. if (tempVector3.x > this._orthoRight)
  9306. this._orthoRight = tempVector3.x;
  9307. if (tempVector3.y > this._orthoTop)
  9308. this._orthoTop = tempVector3.y;
  9309. }
  9310. }
  9311. }
  9312. var xOffset = this._orthoRight - this._orthoLeft;
  9313. var yOffset = this._orthoTop - this._orthoBottom;
  9314. 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);
  9315. };
  9316. DirectionalLight.prototype.supportsVSM = function () {
  9317. return true;
  9318. };
  9319. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9320. return true;
  9321. };
  9322. DirectionalLight.prototype.needCube = function () {
  9323. return false;
  9324. };
  9325. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9326. return this.direction;
  9327. };
  9328. DirectionalLight.prototype.computeTransformedPosition = function () {
  9329. if (this.parent && this.parent.getWorldMatrix) {
  9330. if (!this.transformedPosition) {
  9331. this.transformedPosition = BABYLON.Vector3.Zero();
  9332. }
  9333. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9334. return true;
  9335. }
  9336. return false;
  9337. };
  9338. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9339. if (this.parent && this.parent.getWorldMatrix) {
  9340. if (!this._transformedDirection) {
  9341. this._transformedDirection = BABYLON.Vector3.Zero();
  9342. }
  9343. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9344. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9345. return;
  9346. }
  9347. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9348. };
  9349. DirectionalLight.prototype._getWorldMatrix = function () {
  9350. if (!this._worldMatrix) {
  9351. this._worldMatrix = BABYLON.Matrix.Identity();
  9352. }
  9353. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9354. return this._worldMatrix;
  9355. };
  9356. DirectionalLight.prototype.getTypeID = function () {
  9357. return 1;
  9358. };
  9359. __decorate([
  9360. BABYLON.serializeAsVector3()
  9361. ], DirectionalLight.prototype, "position", void 0);
  9362. __decorate([
  9363. BABYLON.serializeAsVector3()
  9364. ], DirectionalLight.prototype, "direction", void 0);
  9365. __decorate([
  9366. BABYLON.serialize()
  9367. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9368. __decorate([
  9369. BABYLON.serialize()
  9370. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9371. return DirectionalLight;
  9372. })(BABYLON.Light);
  9373. BABYLON.DirectionalLight = DirectionalLight;
  9374. })(BABYLON || (BABYLON = {}));
  9375. var BABYLON;
  9376. (function (BABYLON) {
  9377. var ShadowGenerator = (function () {
  9378. function ShadowGenerator(mapSize, light) {
  9379. var _this = this;
  9380. // Members
  9381. this._filter = ShadowGenerator.FILTER_NONE;
  9382. this.blurScale = 2;
  9383. this._blurBoxOffset = 0;
  9384. this._bias = 0.00005;
  9385. this._lightDirection = BABYLON.Vector3.Zero();
  9386. this.forceBackFacesOnly = false;
  9387. this._darkness = 0;
  9388. this._transparencyShadow = false;
  9389. this._viewMatrix = BABYLON.Matrix.Zero();
  9390. this._projectionMatrix = BABYLON.Matrix.Zero();
  9391. this._transformMatrix = BABYLON.Matrix.Zero();
  9392. this._worldViewProjection = BABYLON.Matrix.Zero();
  9393. this._currentFaceIndex = 0;
  9394. this._currentFaceIndexCache = 0;
  9395. this._light = light;
  9396. this._scene = light.getScene();
  9397. this._mapSize = mapSize;
  9398. light._shadowGenerator = this;
  9399. // Render target
  9400. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9401. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9402. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9403. this._shadowMap.anisotropicFilteringLevel = 1;
  9404. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9405. this._shadowMap.renderParticles = false;
  9406. this._shadowMap.onBeforeRender = function (faceIndex) {
  9407. _this._currentFaceIndex = faceIndex;
  9408. };
  9409. this._shadowMap.onAfterUnbind = function () {
  9410. if (!_this.useBlurVarianceShadowMap) {
  9411. return;
  9412. }
  9413. if (!_this._shadowMap2) {
  9414. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9415. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9416. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9417. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9418. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9419. _this._downSamplePostprocess.onApply = function (effect) {
  9420. effect.setTexture("textureSampler", _this._shadowMap);
  9421. };
  9422. _this.blurBoxOffset = 1;
  9423. }
  9424. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9425. };
  9426. // Custom render function
  9427. var renderSubMesh = function (subMesh) {
  9428. var mesh = subMesh.getRenderingMesh();
  9429. var scene = _this._scene;
  9430. var engine = scene.getEngine();
  9431. // Culling
  9432. engine.setState(subMesh.getMaterial().backFaceCulling);
  9433. // Managing instances
  9434. var batch = mesh._getInstancesRenderList(subMesh._id);
  9435. if (batch.mustReturn) {
  9436. return;
  9437. }
  9438. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9439. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9440. engine.enableEffect(_this._effect);
  9441. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9442. var material = subMesh.getMaterial();
  9443. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9444. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9445. if (_this.getLight().needCube()) {
  9446. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9447. }
  9448. // Alpha test
  9449. if (material && material.needAlphaTesting()) {
  9450. var alphaTexture = material.getAlphaTestTexture();
  9451. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9452. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9453. }
  9454. // Bones
  9455. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9456. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9457. }
  9458. if (_this.forceBackFacesOnly) {
  9459. engine.setState(true, 0, false, true);
  9460. }
  9461. // Draw
  9462. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9463. if (_this.forceBackFacesOnly) {
  9464. engine.setState(true, 0, false, false);
  9465. }
  9466. }
  9467. else {
  9468. // Need to reset refresh rate of the shadowMap
  9469. _this._shadowMap.resetRefreshCounter();
  9470. }
  9471. };
  9472. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9473. var index;
  9474. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9475. renderSubMesh(opaqueSubMeshes.data[index]);
  9476. }
  9477. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9478. renderSubMesh(alphaTestSubMeshes.data[index]);
  9479. }
  9480. if (_this._transparencyShadow) {
  9481. for (index = 0; index < transparentSubMeshes.length; index++) {
  9482. renderSubMesh(transparentSubMeshes.data[index]);
  9483. }
  9484. }
  9485. };
  9486. this._shadowMap.onClear = function (engine) {
  9487. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9488. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9489. }
  9490. else {
  9491. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9492. }
  9493. };
  9494. }
  9495. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9496. // Static
  9497. get: function () {
  9498. return ShadowGenerator._FILTER_NONE;
  9499. },
  9500. enumerable: true,
  9501. configurable: true
  9502. });
  9503. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9504. get: function () {
  9505. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9506. },
  9507. enumerable: true,
  9508. configurable: true
  9509. });
  9510. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9511. get: function () {
  9512. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9513. },
  9514. enumerable: true,
  9515. configurable: true
  9516. });
  9517. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9518. get: function () {
  9519. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9520. },
  9521. enumerable: true,
  9522. configurable: true
  9523. });
  9524. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9525. get: function () {
  9526. return this._bias;
  9527. },
  9528. set: function (bias) {
  9529. this._bias = bias;
  9530. },
  9531. enumerable: true,
  9532. configurable: true
  9533. });
  9534. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9535. get: function () {
  9536. return this._blurBoxOffset;
  9537. },
  9538. set: function (value) {
  9539. var _this = this;
  9540. if (this._blurBoxOffset === value) {
  9541. return;
  9542. }
  9543. this._blurBoxOffset = value;
  9544. if (this._boxBlurPostprocess) {
  9545. this._boxBlurPostprocess.dispose();
  9546. }
  9547. 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);
  9548. this._boxBlurPostprocess.onApply = function (effect) {
  9549. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9550. };
  9551. },
  9552. enumerable: true,
  9553. configurable: true
  9554. });
  9555. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9556. get: function () {
  9557. return this._filter;
  9558. },
  9559. set: function (value) {
  9560. if (this._filter === value) {
  9561. return;
  9562. }
  9563. this._filter = value;
  9564. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9565. this._shadowMap.anisotropicFilteringLevel = 16;
  9566. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9567. }
  9568. else {
  9569. this._shadowMap.anisotropicFilteringLevel = 1;
  9570. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9571. }
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9577. get: function () {
  9578. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9579. },
  9580. set: function (value) {
  9581. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9582. },
  9583. enumerable: true,
  9584. configurable: true
  9585. });
  9586. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9587. get: function () {
  9588. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9589. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9590. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9591. },
  9592. set: function (value) {
  9593. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9594. },
  9595. enumerable: true,
  9596. configurable: true
  9597. });
  9598. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9599. get: function () {
  9600. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9601. },
  9602. set: function (value) {
  9603. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9609. var defines = [];
  9610. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9611. defines.push("#define VSM");
  9612. }
  9613. if (this.getLight().needCube()) {
  9614. defines.push("#define CUBEMAP");
  9615. }
  9616. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9617. var mesh = subMesh.getMesh();
  9618. var material = subMesh.getMaterial();
  9619. // Alpha test
  9620. if (material && material.needAlphaTesting()) {
  9621. defines.push("#define ALPHATEST");
  9622. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9623. attribs.push(BABYLON.VertexBuffer.UVKind);
  9624. defines.push("#define UV1");
  9625. }
  9626. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9627. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9628. defines.push("#define UV2");
  9629. }
  9630. }
  9631. // Bones
  9632. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9635. if (mesh.numBoneInfluencers > 4) {
  9636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9638. }
  9639. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9640. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9641. }
  9642. else {
  9643. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9644. }
  9645. // Instances
  9646. if (useInstances) {
  9647. defines.push("#define INSTANCES");
  9648. attribs.push("world0");
  9649. attribs.push("world1");
  9650. attribs.push("world2");
  9651. attribs.push("world3");
  9652. }
  9653. // Get correct effect
  9654. var join = defines.join("\n");
  9655. if (this._cachedDefines !== join) {
  9656. this._cachedDefines = join;
  9657. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9658. }
  9659. return this._effect.isReady();
  9660. };
  9661. ShadowGenerator.prototype.getShadowMap = function () {
  9662. return this._shadowMap;
  9663. };
  9664. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9665. if (this._shadowMap2) {
  9666. return this._shadowMap2;
  9667. }
  9668. return this._shadowMap;
  9669. };
  9670. ShadowGenerator.prototype.getLight = function () {
  9671. return this._light;
  9672. };
  9673. // Methods
  9674. ShadowGenerator.prototype.getTransformMatrix = function () {
  9675. var scene = this._scene;
  9676. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9677. return this._transformMatrix;
  9678. }
  9679. this._currentRenderID = scene.getRenderId();
  9680. this._currentFaceIndexCache = this._currentFaceIndex;
  9681. var lightPosition = this._light.position;
  9682. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9683. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9684. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9685. }
  9686. if (this._light.computeTransformedPosition()) {
  9687. lightPosition = this._light.transformedPosition;
  9688. }
  9689. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9690. this._cachedPosition = lightPosition.clone();
  9691. this._cachedDirection = this._lightDirection.clone();
  9692. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9693. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9694. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9695. }
  9696. return this._transformMatrix;
  9697. };
  9698. ShadowGenerator.prototype.getDarkness = function () {
  9699. return this._darkness;
  9700. };
  9701. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9702. if (darkness >= 1.0)
  9703. this._darkness = 1.0;
  9704. else if (darkness <= 0.0)
  9705. this._darkness = 0.0;
  9706. else
  9707. this._darkness = darkness;
  9708. };
  9709. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9710. this._transparencyShadow = hasShadow;
  9711. };
  9712. ShadowGenerator.prototype._packHalf = function (depth) {
  9713. var scale = depth * 255.0;
  9714. var fract = scale - Math.floor(scale);
  9715. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9716. };
  9717. ShadowGenerator.prototype.dispose = function () {
  9718. this._shadowMap.dispose();
  9719. if (this._shadowMap2) {
  9720. this._shadowMap2.dispose();
  9721. }
  9722. if (this._downSamplePostprocess) {
  9723. this._downSamplePostprocess.dispose();
  9724. }
  9725. if (this._boxBlurPostprocess) {
  9726. this._boxBlurPostprocess.dispose();
  9727. }
  9728. };
  9729. ShadowGenerator.prototype.serialize = function () {
  9730. var serializationObject = {};
  9731. serializationObject.lightId = this._light.id;
  9732. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9733. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9734. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9735. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9736. serializationObject.renderList = [];
  9737. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9738. var mesh = this.getShadowMap().renderList[meshIndex];
  9739. serializationObject.renderList.push(mesh.id);
  9740. }
  9741. return serializationObject;
  9742. };
  9743. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9744. //casting to point light, as light is missing the position attr and typescript complains.
  9745. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9746. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9747. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9748. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9749. shadowGenerator.getShadowMap().renderList.push(mesh);
  9750. }
  9751. if (parsedShadowGenerator.usePoissonSampling) {
  9752. shadowGenerator.usePoissonSampling = true;
  9753. }
  9754. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9755. shadowGenerator.useVarianceShadowMap = true;
  9756. }
  9757. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9758. shadowGenerator.useBlurVarianceShadowMap = true;
  9759. if (parsedShadowGenerator.blurScale) {
  9760. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9761. }
  9762. if (parsedShadowGenerator.blurBoxOffset) {
  9763. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9764. }
  9765. }
  9766. if (parsedShadowGenerator.bias !== undefined) {
  9767. shadowGenerator.bias = parsedShadowGenerator.bias;
  9768. }
  9769. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9770. return shadowGenerator;
  9771. };
  9772. ShadowGenerator._FILTER_NONE = 0;
  9773. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9774. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9775. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9776. return ShadowGenerator;
  9777. })();
  9778. BABYLON.ShadowGenerator = ShadowGenerator;
  9779. })(BABYLON || (BABYLON = {}));
  9780. var BABYLON;
  9781. (function (BABYLON) {
  9782. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9783. if (boxMin.x > sphereCenter.x + sphereRadius)
  9784. return false;
  9785. if (sphereCenter.x - sphereRadius > boxMax.x)
  9786. return false;
  9787. if (boxMin.y > sphereCenter.y + sphereRadius)
  9788. return false;
  9789. if (sphereCenter.y - sphereRadius > boxMax.y)
  9790. return false;
  9791. if (boxMin.z > sphereCenter.z + sphereRadius)
  9792. return false;
  9793. if (sphereCenter.z - sphereRadius > boxMax.z)
  9794. return false;
  9795. return true;
  9796. };
  9797. var getLowestRoot = function (a, b, c, maxR) {
  9798. var determinant = b * b - 4.0 * a * c;
  9799. var result = { root: 0, found: false };
  9800. if (determinant < 0)
  9801. return result;
  9802. var sqrtD = Math.sqrt(determinant);
  9803. var r1 = (-b - sqrtD) / (2.0 * a);
  9804. var r2 = (-b + sqrtD) / (2.0 * a);
  9805. if (r1 > r2) {
  9806. var temp = r2;
  9807. r2 = r1;
  9808. r1 = temp;
  9809. }
  9810. if (r1 > 0 && r1 < maxR) {
  9811. result.root = r1;
  9812. result.found = true;
  9813. return result;
  9814. }
  9815. if (r2 > 0 && r2 < maxR) {
  9816. result.root = r2;
  9817. result.found = true;
  9818. return result;
  9819. }
  9820. return result;
  9821. };
  9822. var Collider = (function () {
  9823. function Collider() {
  9824. this.radius = new BABYLON.Vector3(1, 1, 1);
  9825. this.retry = 0;
  9826. this.basePointWorld = BABYLON.Vector3.Zero();
  9827. this.velocityWorld = BABYLON.Vector3.Zero();
  9828. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9829. this._collisionPoint = BABYLON.Vector3.Zero();
  9830. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9831. this._tempVector = BABYLON.Vector3.Zero();
  9832. this._tempVector2 = BABYLON.Vector3.Zero();
  9833. this._tempVector3 = BABYLON.Vector3.Zero();
  9834. this._tempVector4 = BABYLON.Vector3.Zero();
  9835. this._edge = BABYLON.Vector3.Zero();
  9836. this._baseToVertex = BABYLON.Vector3.Zero();
  9837. this._destinationPoint = BABYLON.Vector3.Zero();
  9838. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9839. this._displacementVector = BABYLON.Vector3.Zero();
  9840. }
  9841. // Methods
  9842. Collider.prototype._initialize = function (source, dir, e) {
  9843. this.velocity = dir;
  9844. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9845. this.basePoint = source;
  9846. source.multiplyToRef(this.radius, this.basePointWorld);
  9847. dir.multiplyToRef(this.radius, this.velocityWorld);
  9848. this.velocityWorldLength = this.velocityWorld.length();
  9849. this.epsilon = e;
  9850. this.collisionFound = false;
  9851. };
  9852. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9853. pa.subtractToRef(point, this._tempVector);
  9854. pb.subtractToRef(point, this._tempVector2);
  9855. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9856. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9857. if (d < 0)
  9858. return false;
  9859. pc.subtractToRef(point, this._tempVector3);
  9860. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9861. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9862. if (d < 0)
  9863. return false;
  9864. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9865. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9866. return d >= 0;
  9867. };
  9868. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9869. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9870. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9871. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9872. return false;
  9873. }
  9874. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9875. return false;
  9876. return true;
  9877. };
  9878. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9879. var t0;
  9880. var embeddedInPlane = false;
  9881. //defensive programming, actually not needed.
  9882. if (!trianglePlaneArray) {
  9883. trianglePlaneArray = [];
  9884. }
  9885. if (!trianglePlaneArray[faceIndex]) {
  9886. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9887. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9888. }
  9889. var trianglePlane = trianglePlaneArray[faceIndex];
  9890. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9891. return;
  9892. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9893. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9894. if (normalDotVelocity == 0) {
  9895. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9896. return;
  9897. embeddedInPlane = true;
  9898. t0 = 0;
  9899. }
  9900. else {
  9901. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9902. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9903. if (t0 > t1) {
  9904. var temp = t1;
  9905. t1 = t0;
  9906. t0 = temp;
  9907. }
  9908. if (t0 > 1.0 || t1 < 0.0)
  9909. return;
  9910. if (t0 < 0)
  9911. t0 = 0;
  9912. if (t0 > 1.0)
  9913. t0 = 1.0;
  9914. }
  9915. this._collisionPoint.copyFromFloats(0, 0, 0);
  9916. var found = false;
  9917. var t = 1.0;
  9918. if (!embeddedInPlane) {
  9919. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9920. this.velocity.scaleToRef(t0, this._tempVector);
  9921. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9922. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9923. found = true;
  9924. t = t0;
  9925. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9926. }
  9927. }
  9928. if (!found) {
  9929. var velocitySquaredLength = this.velocity.lengthSquared();
  9930. var a = velocitySquaredLength;
  9931. this.basePoint.subtractToRef(p1, this._tempVector);
  9932. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9933. var c = this._tempVector.lengthSquared() - 1.0;
  9934. var lowestRoot = getLowestRoot(a, b, c, t);
  9935. if (lowestRoot.found) {
  9936. t = lowestRoot.root;
  9937. found = true;
  9938. this._collisionPoint.copyFrom(p1);
  9939. }
  9940. this.basePoint.subtractToRef(p2, this._tempVector);
  9941. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9942. c = this._tempVector.lengthSquared() - 1.0;
  9943. lowestRoot = getLowestRoot(a, b, c, t);
  9944. if (lowestRoot.found) {
  9945. t = lowestRoot.root;
  9946. found = true;
  9947. this._collisionPoint.copyFrom(p2);
  9948. }
  9949. this.basePoint.subtractToRef(p3, this._tempVector);
  9950. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9951. c = this._tempVector.lengthSquared() - 1.0;
  9952. lowestRoot = getLowestRoot(a, b, c, t);
  9953. if (lowestRoot.found) {
  9954. t = lowestRoot.root;
  9955. found = true;
  9956. this._collisionPoint.copyFrom(p3);
  9957. }
  9958. p2.subtractToRef(p1, this._edge);
  9959. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9960. var edgeSquaredLength = this._edge.lengthSquared();
  9961. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9962. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9963. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9964. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9965. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9966. lowestRoot = getLowestRoot(a, b, c, t);
  9967. if (lowestRoot.found) {
  9968. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9969. if (f >= 0.0 && f <= 1.0) {
  9970. t = lowestRoot.root;
  9971. found = true;
  9972. this._edge.scaleInPlace(f);
  9973. p1.addToRef(this._edge, this._collisionPoint);
  9974. }
  9975. }
  9976. p3.subtractToRef(p2, this._edge);
  9977. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9978. edgeSquaredLength = this._edge.lengthSquared();
  9979. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9980. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9981. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9982. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9983. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9984. lowestRoot = getLowestRoot(a, b, c, t);
  9985. if (lowestRoot.found) {
  9986. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9987. if (f >= 0.0 && f <= 1.0) {
  9988. t = lowestRoot.root;
  9989. found = true;
  9990. this._edge.scaleInPlace(f);
  9991. p2.addToRef(this._edge, this._collisionPoint);
  9992. }
  9993. }
  9994. p1.subtractToRef(p3, this._edge);
  9995. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9996. edgeSquaredLength = this._edge.lengthSquared();
  9997. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9998. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9999. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10000. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10001. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10002. lowestRoot = getLowestRoot(a, b, c, t);
  10003. if (lowestRoot.found) {
  10004. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10005. if (f >= 0.0 && f <= 1.0) {
  10006. t = lowestRoot.root;
  10007. found = true;
  10008. this._edge.scaleInPlace(f);
  10009. p3.addToRef(this._edge, this._collisionPoint);
  10010. }
  10011. }
  10012. }
  10013. if (found) {
  10014. var distToCollision = t * this.velocity.length();
  10015. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10016. if (!this.intersectionPoint) {
  10017. this.intersectionPoint = this._collisionPoint.clone();
  10018. }
  10019. else {
  10020. this.intersectionPoint.copyFrom(this._collisionPoint);
  10021. }
  10022. this.nearestDistance = distToCollision;
  10023. this.collisionFound = true;
  10024. }
  10025. }
  10026. };
  10027. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10028. for (var i = indexStart; i < indexEnd; i += 3) {
  10029. var p1 = pts[indices[i] - decal];
  10030. var p2 = pts[indices[i + 1] - decal];
  10031. var p3 = pts[indices[i + 2] - decal];
  10032. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10033. }
  10034. };
  10035. Collider.prototype._getResponse = function (pos, vel) {
  10036. pos.addToRef(vel, this._destinationPoint);
  10037. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10038. this.basePoint.addToRef(vel, pos);
  10039. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10040. this._slidePlaneNormal.normalize();
  10041. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10042. pos.addInPlace(this._displacementVector);
  10043. this.intersectionPoint.addInPlace(this._displacementVector);
  10044. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10045. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10046. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10047. };
  10048. return Collider;
  10049. })();
  10050. BABYLON.Collider = Collider;
  10051. })(BABYLON || (BABYLON = {}));
  10052. var BABYLON;
  10053. (function (BABYLON) {
  10054. //WebWorker code will be inserted to this variable.
  10055. BABYLON.CollisionWorker = "";
  10056. (function (WorkerTaskType) {
  10057. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10058. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10059. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10060. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10061. var WorkerTaskType = BABYLON.WorkerTaskType;
  10062. (function (WorkerReplyType) {
  10063. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10064. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10065. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10066. var WorkerReplyType = BABYLON.WorkerReplyType;
  10067. var CollisionCoordinatorWorker = (function () {
  10068. function CollisionCoordinatorWorker() {
  10069. var _this = this;
  10070. this._scaledPosition = BABYLON.Vector3.Zero();
  10071. this._scaledVelocity = BABYLON.Vector3.Zero();
  10072. this.onMeshUpdated = function (mesh) {
  10073. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10074. };
  10075. this.onGeometryUpdated = function (geometry) {
  10076. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10077. };
  10078. this._afterRender = function () {
  10079. if (!_this._init)
  10080. return;
  10081. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10082. return;
  10083. }
  10084. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10085. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10086. if (_this._runningUpdated > 4) {
  10087. return;
  10088. }
  10089. ++_this._runningUpdated;
  10090. var payload = {
  10091. updatedMeshes: _this._addUpdateMeshesList,
  10092. updatedGeometries: _this._addUpdateGeometriesList,
  10093. removedGeometries: _this._toRemoveGeometryArray,
  10094. removedMeshes: _this._toRemoveMeshesArray
  10095. };
  10096. var message = {
  10097. payload: payload,
  10098. taskType: WorkerTaskType.UPDATE
  10099. };
  10100. var serializable = [];
  10101. for (var id in payload.updatedGeometries) {
  10102. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10103. //prepare transferables
  10104. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10105. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10106. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10107. }
  10108. }
  10109. _this._worker.postMessage(message, serializable);
  10110. _this._addUpdateMeshesList = {};
  10111. _this._addUpdateGeometriesList = {};
  10112. _this._toRemoveGeometryArray = [];
  10113. _this._toRemoveMeshesArray = [];
  10114. };
  10115. this._onMessageFromWorker = function (e) {
  10116. var returnData = e.data;
  10117. if (returnData.error != WorkerReplyType.SUCCESS) {
  10118. //TODO what errors can be returned from the worker?
  10119. BABYLON.Tools.Warn("error returned from worker!");
  10120. return;
  10121. }
  10122. switch (returnData.taskType) {
  10123. case WorkerTaskType.INIT:
  10124. _this._init = true;
  10125. //Update the worked with ALL of the scene's current state
  10126. _this._scene.meshes.forEach(function (mesh) {
  10127. _this.onMeshAdded(mesh);
  10128. });
  10129. _this._scene.getGeometries().forEach(function (geometry) {
  10130. _this.onGeometryAdded(geometry);
  10131. });
  10132. break;
  10133. case WorkerTaskType.UPDATE:
  10134. _this._runningUpdated--;
  10135. break;
  10136. case WorkerTaskType.COLLIDE:
  10137. _this._runningCollisionTask = false;
  10138. var returnPayload = returnData.payload;
  10139. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10140. return;
  10141. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10142. //cleanup
  10143. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10144. break;
  10145. }
  10146. };
  10147. this._collisionsCallbackArray = [];
  10148. this._init = false;
  10149. this._runningUpdated = 0;
  10150. this._runningCollisionTask = false;
  10151. this._addUpdateMeshesList = {};
  10152. this._addUpdateGeometriesList = {};
  10153. this._toRemoveGeometryArray = [];
  10154. this._toRemoveMeshesArray = [];
  10155. }
  10156. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10157. if (!this._init)
  10158. return;
  10159. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10160. return;
  10161. position.divideToRef(collider.radius, this._scaledPosition);
  10162. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10163. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10164. var payload = {
  10165. collider: {
  10166. position: this._scaledPosition.asArray(),
  10167. velocity: this._scaledVelocity.asArray(),
  10168. radius: collider.radius.asArray()
  10169. },
  10170. collisionId: collisionIndex,
  10171. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10172. maximumRetry: maximumRetry
  10173. };
  10174. var message = {
  10175. payload: payload,
  10176. taskType: WorkerTaskType.COLLIDE
  10177. };
  10178. this._worker.postMessage(message);
  10179. };
  10180. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10181. this._scene = scene;
  10182. this._scene.registerAfterRender(this._afterRender);
  10183. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10184. this._worker = new Worker(workerUrl);
  10185. this._worker.onmessage = this._onMessageFromWorker;
  10186. var message = {
  10187. payload: {},
  10188. taskType: WorkerTaskType.INIT
  10189. };
  10190. this._worker.postMessage(message);
  10191. };
  10192. CollisionCoordinatorWorker.prototype.destroy = function () {
  10193. this._scene.unregisterAfterRender(this._afterRender);
  10194. this._worker.terminate();
  10195. };
  10196. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10197. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10198. this.onMeshUpdated(mesh);
  10199. };
  10200. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10201. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10202. };
  10203. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10204. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10205. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10206. this.onGeometryUpdated(geometry);
  10207. };
  10208. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10209. this._toRemoveGeometryArray.push(geometry.id);
  10210. };
  10211. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10212. var submeshes = [];
  10213. if (mesh.subMeshes) {
  10214. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10215. return {
  10216. position: idx,
  10217. verticesStart: sm.verticesStart,
  10218. verticesCount: sm.verticesCount,
  10219. indexStart: sm.indexStart,
  10220. indexCount: sm.indexCount,
  10221. hasMaterial: !!sm.getMaterial(),
  10222. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10223. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10224. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10225. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10226. };
  10227. });
  10228. }
  10229. var geometryId = null;
  10230. if (mesh instanceof BABYLON.Mesh) {
  10231. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10232. }
  10233. else if (mesh instanceof BABYLON.InstancedMesh) {
  10234. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10235. }
  10236. return {
  10237. uniqueId: mesh.uniqueId,
  10238. id: mesh.id,
  10239. name: mesh.name,
  10240. geometryId: geometryId,
  10241. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10242. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10243. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10244. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10245. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10246. subMeshes: submeshes,
  10247. checkCollisions: mesh.checkCollisions
  10248. };
  10249. };
  10250. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10251. return {
  10252. id: geometry.id,
  10253. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10254. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10255. indices: new Int32Array(geometry.getIndices() || []),
  10256. };
  10257. };
  10258. return CollisionCoordinatorWorker;
  10259. })();
  10260. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10261. var CollisionCoordinatorLegacy = (function () {
  10262. function CollisionCoordinatorLegacy() {
  10263. this._scaledPosition = BABYLON.Vector3.Zero();
  10264. this._scaledVelocity = BABYLON.Vector3.Zero();
  10265. this._finalPosition = BABYLON.Vector3.Zero();
  10266. }
  10267. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10268. position.divideToRef(collider.radius, this._scaledPosition);
  10269. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10270. collider.collidedMesh = null;
  10271. collider.retry = 0;
  10272. collider.initialVelocity = this._scaledVelocity;
  10273. collider.initialPosition = this._scaledPosition;
  10274. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10275. this._finalPosition.multiplyInPlace(collider.radius);
  10276. //run the callback
  10277. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10278. };
  10279. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10280. this._scene = scene;
  10281. };
  10282. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10283. //Legacy need no destruction method.
  10284. };
  10285. //No update in legacy mode
  10286. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10287. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10288. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10289. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10290. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10291. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10292. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10293. if (excludedMesh === void 0) { excludedMesh = null; }
  10294. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10295. if (collider.retry >= maximumRetry) {
  10296. finalPosition.copyFrom(position);
  10297. return;
  10298. }
  10299. collider._initialize(position, velocity, closeDistance);
  10300. // Check all meshes
  10301. for (var index = 0; index < this._scene.meshes.length; index++) {
  10302. var mesh = this._scene.meshes[index];
  10303. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10304. mesh._checkCollision(collider);
  10305. }
  10306. }
  10307. if (!collider.collisionFound) {
  10308. position.addToRef(velocity, finalPosition);
  10309. return;
  10310. }
  10311. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10312. collider._getResponse(position, velocity);
  10313. }
  10314. if (velocity.length() <= closeDistance) {
  10315. finalPosition.copyFrom(position);
  10316. return;
  10317. }
  10318. collider.retry++;
  10319. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10320. };
  10321. return CollisionCoordinatorLegacy;
  10322. })();
  10323. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10324. })(BABYLON || (BABYLON = {}));
  10325. var BABYLON;
  10326. (function (BABYLON) {
  10327. var Camera = (function (_super) {
  10328. __extends(Camera, _super);
  10329. function Camera(name, position, scene) {
  10330. _super.call(this, name, scene);
  10331. this.upVector = BABYLON.Vector3.Up();
  10332. this.orthoLeft = null;
  10333. this.orthoRight = null;
  10334. this.orthoBottom = null;
  10335. this.orthoTop = null;
  10336. this.fov = 0.8;
  10337. this.minZ = 1.0;
  10338. this.maxZ = 10000.0;
  10339. this.inertia = 0.9;
  10340. this.mode = Camera.PERSPECTIVE_CAMERA;
  10341. this.isIntermediate = false;
  10342. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10343. this.layerMask = 0x0FFFFFFF;
  10344. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10345. // Camera rig members
  10346. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10347. this._rigCameras = new Array();
  10348. // Cache
  10349. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10350. this._projectionMatrix = new BABYLON.Matrix();
  10351. this._postProcesses = new Array();
  10352. this._postProcessesTakenIndices = [];
  10353. this._activeMeshes = new BABYLON.SmartArray(256);
  10354. this._globalPosition = BABYLON.Vector3.Zero();
  10355. scene.addCamera(this);
  10356. if (!scene.activeCamera) {
  10357. scene.activeCamera = this;
  10358. }
  10359. this.position = position;
  10360. }
  10361. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10362. get: function () {
  10363. return Camera._PERSPECTIVE_CAMERA;
  10364. },
  10365. enumerable: true,
  10366. configurable: true
  10367. });
  10368. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10369. get: function () {
  10370. return Camera._ORTHOGRAPHIC_CAMERA;
  10371. },
  10372. enumerable: true,
  10373. configurable: true
  10374. });
  10375. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10376. get: function () {
  10377. return Camera._FOVMODE_VERTICAL_FIXED;
  10378. },
  10379. enumerable: true,
  10380. configurable: true
  10381. });
  10382. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10383. get: function () {
  10384. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10385. },
  10386. enumerable: true,
  10387. configurable: true
  10388. });
  10389. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10390. get: function () {
  10391. return Camera._RIG_MODE_NONE;
  10392. },
  10393. enumerable: true,
  10394. configurable: true
  10395. });
  10396. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10397. get: function () {
  10398. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10399. },
  10400. enumerable: true,
  10401. configurable: true
  10402. });
  10403. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10404. get: function () {
  10405. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10411. get: function () {
  10412. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10413. },
  10414. enumerable: true,
  10415. configurable: true
  10416. });
  10417. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10418. get: function () {
  10419. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10420. },
  10421. enumerable: true,
  10422. configurable: true
  10423. });
  10424. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10425. get: function () {
  10426. return Camera._RIG_MODE_VR;
  10427. },
  10428. enumerable: true,
  10429. configurable: true
  10430. });
  10431. Object.defineProperty(Camera.prototype, "globalPosition", {
  10432. get: function () {
  10433. return this._globalPosition;
  10434. },
  10435. enumerable: true,
  10436. configurable: true
  10437. });
  10438. Camera.prototype.getActiveMeshes = function () {
  10439. return this._activeMeshes;
  10440. };
  10441. Camera.prototype.isActiveMesh = function (mesh) {
  10442. return (this._activeMeshes.indexOf(mesh) !== -1);
  10443. };
  10444. //Cache
  10445. Camera.prototype._initCache = function () {
  10446. _super.prototype._initCache.call(this);
  10447. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10448. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10449. this._cache.mode = undefined;
  10450. this._cache.minZ = undefined;
  10451. this._cache.maxZ = undefined;
  10452. this._cache.fov = undefined;
  10453. this._cache.aspectRatio = undefined;
  10454. this._cache.orthoLeft = undefined;
  10455. this._cache.orthoRight = undefined;
  10456. this._cache.orthoBottom = undefined;
  10457. this._cache.orthoTop = undefined;
  10458. this._cache.renderWidth = undefined;
  10459. this._cache.renderHeight = undefined;
  10460. };
  10461. Camera.prototype._updateCache = function (ignoreParentClass) {
  10462. if (!ignoreParentClass) {
  10463. _super.prototype._updateCache.call(this);
  10464. }
  10465. var engine = this.getEngine();
  10466. this._cache.position.copyFrom(this.position);
  10467. this._cache.upVector.copyFrom(this.upVector);
  10468. this._cache.mode = this.mode;
  10469. this._cache.minZ = this.minZ;
  10470. this._cache.maxZ = this.maxZ;
  10471. this._cache.fov = this.fov;
  10472. this._cache.aspectRatio = engine.getAspectRatio(this);
  10473. this._cache.orthoLeft = this.orthoLeft;
  10474. this._cache.orthoRight = this.orthoRight;
  10475. this._cache.orthoBottom = this.orthoBottom;
  10476. this._cache.orthoTop = this.orthoTop;
  10477. this._cache.renderWidth = engine.getRenderWidth();
  10478. this._cache.renderHeight = engine.getRenderHeight();
  10479. };
  10480. Camera.prototype._updateFromScene = function () {
  10481. this.updateCache();
  10482. this._update();
  10483. };
  10484. // Synchronized
  10485. Camera.prototype._isSynchronized = function () {
  10486. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10487. };
  10488. Camera.prototype._isSynchronizedViewMatrix = function () {
  10489. if (!_super.prototype._isSynchronized.call(this))
  10490. return false;
  10491. return this._cache.position.equals(this.position)
  10492. && this._cache.upVector.equals(this.upVector)
  10493. && this.isSynchronizedWithParent();
  10494. };
  10495. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10496. var check = this._cache.mode === this.mode
  10497. && this._cache.minZ === this.minZ
  10498. && this._cache.maxZ === this.maxZ;
  10499. if (!check) {
  10500. return false;
  10501. }
  10502. var engine = this.getEngine();
  10503. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10504. check = this._cache.fov === this.fov
  10505. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10506. }
  10507. else {
  10508. check = this._cache.orthoLeft === this.orthoLeft
  10509. && this._cache.orthoRight === this.orthoRight
  10510. && this._cache.orthoBottom === this.orthoBottom
  10511. && this._cache.orthoTop === this.orthoTop
  10512. && this._cache.renderWidth === engine.getRenderWidth()
  10513. && this._cache.renderHeight === engine.getRenderHeight();
  10514. }
  10515. return check;
  10516. };
  10517. // Controls
  10518. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10519. };
  10520. Camera.prototype.detachControl = function (element) {
  10521. };
  10522. Camera.prototype._update = function () {
  10523. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10524. this._updateRigCameras();
  10525. }
  10526. this._checkInputs();
  10527. };
  10528. Camera.prototype._checkInputs = function () {
  10529. };
  10530. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10531. if (insertAt === void 0) { insertAt = null; }
  10532. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10533. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10534. return 0;
  10535. }
  10536. if (insertAt == null || insertAt < 0) {
  10537. this._postProcesses.push(postProcess);
  10538. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10539. return this._postProcesses.length - 1;
  10540. }
  10541. var add = 0;
  10542. var i;
  10543. var start;
  10544. if (this._postProcesses[insertAt]) {
  10545. start = this._postProcesses.length - 1;
  10546. for (i = start; i >= insertAt + 1; --i) {
  10547. this._postProcesses[i + 1] = this._postProcesses[i];
  10548. }
  10549. add = 1;
  10550. }
  10551. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10552. if (this._postProcessesTakenIndices[i] < insertAt) {
  10553. continue;
  10554. }
  10555. start = this._postProcessesTakenIndices.length - 1;
  10556. for (var j = start; j >= i; --j) {
  10557. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10558. }
  10559. this._postProcessesTakenIndices[i] = insertAt;
  10560. break;
  10561. }
  10562. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10563. this._postProcessesTakenIndices.push(insertAt);
  10564. }
  10565. var result = insertAt + add;
  10566. this._postProcesses[result] = postProcess;
  10567. return result;
  10568. };
  10569. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10570. if (atIndices === void 0) { atIndices = null; }
  10571. var result = [];
  10572. var i;
  10573. var index;
  10574. if (!atIndices) {
  10575. var length = this._postProcesses.length;
  10576. for (i = 0; i < length; i++) {
  10577. if (this._postProcesses[i] !== postProcess) {
  10578. continue;
  10579. }
  10580. delete this._postProcesses[i];
  10581. index = this._postProcessesTakenIndices.indexOf(i);
  10582. this._postProcessesTakenIndices.splice(index, 1);
  10583. }
  10584. }
  10585. else {
  10586. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10587. for (i = 0; i < atIndices.length; i++) {
  10588. var foundPostProcess = this._postProcesses[atIndices[i]];
  10589. if (foundPostProcess !== postProcess) {
  10590. result.push(i);
  10591. continue;
  10592. }
  10593. delete this._postProcesses[atIndices[i]];
  10594. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10595. this._postProcessesTakenIndices.splice(index, 1);
  10596. }
  10597. }
  10598. return result;
  10599. };
  10600. Camera.prototype.getWorldMatrix = function () {
  10601. if (!this._worldMatrix) {
  10602. this._worldMatrix = BABYLON.Matrix.Identity();
  10603. }
  10604. var viewMatrix = this.getViewMatrix();
  10605. viewMatrix.invertToRef(this._worldMatrix);
  10606. return this._worldMatrix;
  10607. };
  10608. Camera.prototype._getViewMatrix = function () {
  10609. return BABYLON.Matrix.Identity();
  10610. };
  10611. Camera.prototype.getViewMatrix = function (force) {
  10612. this._computedViewMatrix = this._computeViewMatrix(force);
  10613. if (!force && this._isSynchronizedViewMatrix()) {
  10614. return this._computedViewMatrix;
  10615. }
  10616. if (!this.parent || !this.parent.getWorldMatrix) {
  10617. this._globalPosition.copyFrom(this.position);
  10618. }
  10619. else {
  10620. if (!this._worldMatrix) {
  10621. this._worldMatrix = BABYLON.Matrix.Identity();
  10622. }
  10623. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10624. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10625. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10626. this._computedViewMatrix.invert();
  10627. this._markSyncedWithParent();
  10628. }
  10629. this._currentRenderId = this.getScene().getRenderId();
  10630. return this._computedViewMatrix;
  10631. };
  10632. Camera.prototype._computeViewMatrix = function (force) {
  10633. if (!force && this._isSynchronizedViewMatrix()) {
  10634. return this._computedViewMatrix;
  10635. }
  10636. this._computedViewMatrix = this._getViewMatrix();
  10637. this._currentRenderId = this.getScene().getRenderId();
  10638. return this._computedViewMatrix;
  10639. };
  10640. Camera.prototype.getProjectionMatrix = function (force) {
  10641. if (!force && this._isSynchronizedProjectionMatrix()) {
  10642. return this._projectionMatrix;
  10643. }
  10644. var engine = this.getEngine();
  10645. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10646. if (this.minZ <= 0) {
  10647. this.minZ = 0.1;
  10648. }
  10649. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10650. return this._projectionMatrix;
  10651. }
  10652. var halfWidth = engine.getRenderWidth() / 2.0;
  10653. var halfHeight = engine.getRenderHeight() / 2.0;
  10654. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10655. return this._projectionMatrix;
  10656. };
  10657. Camera.prototype.dispose = function () {
  10658. // Animations
  10659. this.getScene().stopAnimation(this);
  10660. // Remove from scene
  10661. this.getScene().removeCamera(this);
  10662. while (this._rigCameras.length > 0) {
  10663. this._rigCameras.pop().dispose();
  10664. }
  10665. // Postprocesses
  10666. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10667. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10668. }
  10669. };
  10670. // ---- Camera rigs section ----
  10671. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10672. while (this._rigCameras.length > 0) {
  10673. this._rigCameras.pop().dispose();
  10674. }
  10675. this.cameraRigMode = mode;
  10676. this._cameraRigParams = {};
  10677. switch (this.cameraRigMode) {
  10678. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10679. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10680. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10681. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10682. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10683. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10684. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10685. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10686. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10687. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10688. break;
  10689. }
  10690. var postProcesses = new Array();
  10691. switch (this.cameraRigMode) {
  10692. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10693. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10694. this._rigCameras[0].isIntermediate = true;
  10695. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10696. postProcesses[1].onApply = function (effect) {
  10697. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10698. };
  10699. break;
  10700. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10701. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10702. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10703. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10704. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10705. var secondCamIndex = 1 - firstCamIndex;
  10706. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10707. this._rigCameras[firstCamIndex].isIntermediate = true;
  10708. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10709. break;
  10710. case Camera.RIG_MODE_VR:
  10711. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10712. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10713. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10714. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10715. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10716. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10717. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10718. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10719. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10720. if (metrics.compensateDistortion) {
  10721. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10722. }
  10723. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10724. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10725. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10726. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10727. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10728. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10729. if (metrics.compensateDistortion) {
  10730. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10731. }
  10732. break;
  10733. }
  10734. this._update();
  10735. };
  10736. Camera.prototype._getVRProjectionMatrix = function () {
  10737. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10738. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10739. return this._projectionMatrix;
  10740. };
  10741. Camera.prototype.setCameraRigParameter = function (name, value) {
  10742. this._cameraRigParams[name] = value;
  10743. //provisionnally:
  10744. if (name === "interaxialDistance") {
  10745. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10746. }
  10747. };
  10748. /**
  10749. * May needs to be overridden by children so sub has required properties to be copied
  10750. */
  10751. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10752. return null;
  10753. };
  10754. /**
  10755. * May needs to be overridden by children
  10756. */
  10757. Camera.prototype._updateRigCameras = function () {
  10758. for (var i = 0; i < this._rigCameras.length; i++) {
  10759. this._rigCameras[i].minZ = this.minZ;
  10760. this._rigCameras[i].maxZ = this.maxZ;
  10761. this._rigCameras[i].fov = this.fov;
  10762. }
  10763. // only update viewport when ANAGLYPH
  10764. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10765. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10766. }
  10767. };
  10768. Camera.prototype.serialize = function () {
  10769. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10770. // Type
  10771. serializationObject.type = this.getTypeName();
  10772. // Parent
  10773. if (this.parent) {
  10774. serializationObject.parentId = this.parent.id;
  10775. }
  10776. // Animations
  10777. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10778. serializationObject.ranges = this.serializeAnimationRanges();
  10779. return serializationObject;
  10780. };
  10781. Camera.prototype.getTypeName = function () {
  10782. return "Camera";
  10783. };
  10784. Camera.prototype.clone = function (name) {
  10785. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10786. };
  10787. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10788. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10789. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10790. switch (type) {
  10791. case "ArcRotateCamera":
  10792. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10793. case "DeviceOrientationCamera":
  10794. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10795. case "FollowCamera":
  10796. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10797. case "ArcFollowCamera":
  10798. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10799. case "GamepadCamera":
  10800. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10801. case "TouchCamera":
  10802. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10803. case "VirtualJoysticksCamera":
  10804. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10805. case "WebVRFreeCamera":
  10806. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10807. case "VRDeviceOrientationFreeCamera":
  10808. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10809. case "AnaglyphArcRotateCamera":
  10810. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10811. case "AnaglyphFreeCamera":
  10812. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10813. case "AnaglyphGamepadCamera":
  10814. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10815. case "AnaglyphUniversalCamera":
  10816. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10817. case "StereoscopicArcRotateCamera":
  10818. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10819. case "StereoscopicFreeCamera":
  10820. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10821. case "StereoscopicGamepadCamera":
  10822. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10823. case "StereoscopicUniversalCamera":
  10824. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10825. case "FreeCamera":
  10826. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10827. default:
  10828. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10829. }
  10830. };
  10831. Camera.Parse = function (parsedCamera, scene) {
  10832. var type = parsedCamera.type;
  10833. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10834. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10835. // Parent
  10836. if (parsedCamera.parentId) {
  10837. camera._waitingParentId = parsedCamera.parentId;
  10838. }
  10839. // Target
  10840. if (parsedCamera.target) {
  10841. if (camera.setTarget) {
  10842. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10843. }
  10844. }
  10845. // Apply 3d rig, when found
  10846. if (parsedCamera.cameraRigMode) {
  10847. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10848. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10849. }
  10850. // Animations
  10851. if (parsedCamera.animations) {
  10852. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10853. var parsedAnimation = parsedCamera.animations[animationIndex];
  10854. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10855. }
  10856. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10857. }
  10858. if (parsedCamera.autoAnimate) {
  10859. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10860. }
  10861. return camera;
  10862. };
  10863. // Statics
  10864. Camera._PERSPECTIVE_CAMERA = 0;
  10865. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10866. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10867. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10868. Camera._RIG_MODE_NONE = 0;
  10869. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10870. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10871. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10872. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10873. Camera._RIG_MODE_VR = 20;
  10874. __decorate([
  10875. BABYLON.serializeAsVector3()
  10876. ], Camera.prototype, "position", void 0);
  10877. __decorate([
  10878. BABYLON.serialize()
  10879. ], Camera.prototype, "upVector", void 0);
  10880. __decorate([
  10881. BABYLON.serialize()
  10882. ], Camera.prototype, "orthoLeft", void 0);
  10883. __decorate([
  10884. BABYLON.serialize()
  10885. ], Camera.prototype, "orthoRight", void 0);
  10886. __decorate([
  10887. BABYLON.serialize()
  10888. ], Camera.prototype, "orthoBottom", void 0);
  10889. __decorate([
  10890. BABYLON.serialize()
  10891. ], Camera.prototype, "orthoTop", void 0);
  10892. __decorate([
  10893. BABYLON.serialize()
  10894. ], Camera.prototype, "fov", void 0);
  10895. __decorate([
  10896. BABYLON.serialize()
  10897. ], Camera.prototype, "minZ", void 0);
  10898. __decorate([
  10899. BABYLON.serialize()
  10900. ], Camera.prototype, "maxZ", void 0);
  10901. __decorate([
  10902. BABYLON.serialize()
  10903. ], Camera.prototype, "inertia", void 0);
  10904. __decorate([
  10905. BABYLON.serialize()
  10906. ], Camera.prototype, "mode", void 0);
  10907. __decorate([
  10908. BABYLON.serialize()
  10909. ], Camera.prototype, "layerMask", void 0);
  10910. __decorate([
  10911. BABYLON.serialize()
  10912. ], Camera.prototype, "fovMode", void 0);
  10913. __decorate([
  10914. BABYLON.serialize()
  10915. ], Camera.prototype, "cameraRigMode", void 0);
  10916. __decorate([
  10917. BABYLON.serialize()
  10918. ], Camera.prototype, "interaxialDistance", void 0);
  10919. __decorate([
  10920. BABYLON.serialize()
  10921. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  10922. return Camera;
  10923. })(BABYLON.Node);
  10924. BABYLON.Camera = Camera;
  10925. })(BABYLON || (BABYLON = {}));
  10926. var BABYLON;
  10927. (function (BABYLON) {
  10928. var TargetCamera = (function (_super) {
  10929. __extends(TargetCamera, _super);
  10930. function TargetCamera(name, position, scene) {
  10931. _super.call(this, name, position, scene);
  10932. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10933. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10934. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10935. this.speed = 2.0;
  10936. this.noRotationConstraint = false;
  10937. this.lockedTarget = null;
  10938. this._currentTarget = BABYLON.Vector3.Zero();
  10939. this._viewMatrix = BABYLON.Matrix.Zero();
  10940. this._camMatrix = BABYLON.Matrix.Zero();
  10941. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10942. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10943. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10944. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10945. this._lookAtTemp = BABYLON.Matrix.Zero();
  10946. this._tempMatrix = BABYLON.Matrix.Zero();
  10947. }
  10948. TargetCamera.prototype.getFrontPosition = function (distance) {
  10949. var direction = this.getTarget().subtract(this.position);
  10950. direction.normalize();
  10951. direction.scaleInPlace(distance);
  10952. return this.globalPosition.add(direction);
  10953. };
  10954. TargetCamera.prototype._getLockedTargetPosition = function () {
  10955. if (!this.lockedTarget) {
  10956. return null;
  10957. }
  10958. return this.lockedTarget.position || this.lockedTarget;
  10959. };
  10960. // Cache
  10961. TargetCamera.prototype._initCache = function () {
  10962. _super.prototype._initCache.call(this);
  10963. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10964. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10965. };
  10966. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10967. if (!ignoreParentClass) {
  10968. _super.prototype._updateCache.call(this);
  10969. }
  10970. var lockedTargetPosition = this._getLockedTargetPosition();
  10971. if (!lockedTargetPosition) {
  10972. this._cache.lockedTarget = null;
  10973. }
  10974. else {
  10975. if (!this._cache.lockedTarget) {
  10976. this._cache.lockedTarget = lockedTargetPosition.clone();
  10977. }
  10978. else {
  10979. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10980. }
  10981. }
  10982. this._cache.rotation.copyFrom(this.rotation);
  10983. };
  10984. // Synchronized
  10985. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10986. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10987. return false;
  10988. }
  10989. var lockedTargetPosition = this._getLockedTargetPosition();
  10990. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10991. && this._cache.rotation.equals(this.rotation);
  10992. };
  10993. // Methods
  10994. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10995. var engine = this.getEngine();
  10996. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10997. };
  10998. // Target
  10999. TargetCamera.prototype.setTarget = function (target) {
  11000. this.upVector.normalize();
  11001. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11002. this._camMatrix.invert();
  11003. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11004. var vDir = target.subtract(this.position);
  11005. if (vDir.x >= 0.0) {
  11006. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11007. }
  11008. else {
  11009. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11010. }
  11011. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11012. if (isNaN(this.rotation.x)) {
  11013. this.rotation.x = 0;
  11014. }
  11015. if (isNaN(this.rotation.y)) {
  11016. this.rotation.y = 0;
  11017. }
  11018. if (isNaN(this.rotation.z)) {
  11019. this.rotation.z = 0;
  11020. }
  11021. };
  11022. TargetCamera.prototype.getTarget = function () {
  11023. return this._currentTarget;
  11024. };
  11025. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11026. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11027. };
  11028. TargetCamera.prototype._updatePosition = function () {
  11029. this.position.addInPlace(this.cameraDirection);
  11030. };
  11031. TargetCamera.prototype._checkInputs = function () {
  11032. var needToMove = this._decideIfNeedsToMove();
  11033. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11034. // Move
  11035. if (needToMove) {
  11036. this._updatePosition();
  11037. }
  11038. // Rotate
  11039. if (needToRotate) {
  11040. this.rotation.x += this.cameraRotation.x;
  11041. this.rotation.y += this.cameraRotation.y;
  11042. if (!this.noRotationConstraint) {
  11043. var limit = (Math.PI / 2) * 0.95;
  11044. if (this.rotation.x > limit)
  11045. this.rotation.x = limit;
  11046. if (this.rotation.x < -limit)
  11047. this.rotation.x = -limit;
  11048. }
  11049. }
  11050. // Inertia
  11051. if (needToMove) {
  11052. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  11053. this.cameraDirection.x = 0;
  11054. }
  11055. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  11056. this.cameraDirection.y = 0;
  11057. }
  11058. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  11059. this.cameraDirection.z = 0;
  11060. }
  11061. this.cameraDirection.scaleInPlace(this.inertia);
  11062. }
  11063. if (needToRotate) {
  11064. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  11065. this.cameraRotation.x = 0;
  11066. }
  11067. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  11068. this.cameraRotation.y = 0;
  11069. }
  11070. this.cameraRotation.scaleInPlace(this.inertia);
  11071. }
  11072. _super.prototype._checkInputs.call(this);
  11073. };
  11074. TargetCamera.prototype._getViewMatrix = function () {
  11075. if (!this.lockedTarget) {
  11076. // Compute
  11077. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11078. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11079. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11080. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11081. this._lookAtTemp.invert();
  11082. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11083. }
  11084. else {
  11085. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11086. }
  11087. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11088. // Computing target and final matrix
  11089. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11090. }
  11091. else {
  11092. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11093. }
  11094. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11095. return this._viewMatrix;
  11096. };
  11097. TargetCamera.prototype._getVRViewMatrix = function () {
  11098. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11099. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11100. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11101. // Computing target and final matrix
  11102. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11103. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11104. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11105. return this._viewMatrix;
  11106. };
  11107. /**
  11108. * @override
  11109. * Override Camera.createRigCamera
  11110. */
  11111. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11112. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11113. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11114. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11115. rigCamera._cameraRigParams = {};
  11116. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11117. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11118. }
  11119. return rigCamera;
  11120. }
  11121. return null;
  11122. };
  11123. /**
  11124. * @override
  11125. * Override Camera._updateRigCameras
  11126. */
  11127. TargetCamera.prototype._updateRigCameras = function () {
  11128. switch (this.cameraRigMode) {
  11129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11132. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11133. case BABYLON.Camera.RIG_MODE_VR:
  11134. var camLeft = this._rigCameras[0];
  11135. var camRight = this._rigCameras[1];
  11136. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11137. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11138. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11139. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11140. camLeft.position.copyFrom(this.position);
  11141. camRight.position.copyFrom(this.position);
  11142. }
  11143. else {
  11144. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11145. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11146. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11147. camLeft.setTarget(this.getTarget());
  11148. camRight.setTarget(this.getTarget());
  11149. }
  11150. break;
  11151. }
  11152. _super.prototype._updateRigCameras.call(this);
  11153. };
  11154. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11155. if (!this._rigCamTransformMatrix) {
  11156. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11157. }
  11158. var target = this.getTarget();
  11159. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11160. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11161. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11162. };
  11163. TargetCamera.prototype.getTypeName = function () {
  11164. return "TargetCamera";
  11165. };
  11166. __decorate([
  11167. BABYLON.serializeAsVector3()
  11168. ], TargetCamera.prototype, "rotation", void 0);
  11169. __decorate([
  11170. BABYLON.serialize()
  11171. ], TargetCamera.prototype, "speed", void 0);
  11172. __decorate([
  11173. BABYLON.serializeAsMeshReference("lockedTargetId")
  11174. ], TargetCamera.prototype, "lockedTarget", void 0);
  11175. return TargetCamera;
  11176. })(BABYLON.Camera);
  11177. BABYLON.TargetCamera = TargetCamera;
  11178. })(BABYLON || (BABYLON = {}));
  11179. var BABYLON;
  11180. (function (BABYLON) {
  11181. var FreeCamera = (function (_super) {
  11182. __extends(FreeCamera, _super);
  11183. function FreeCamera(name, position, scene) {
  11184. var _this = this;
  11185. _super.call(this, name, position, scene);
  11186. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11187. this.keysUp = [38];
  11188. this.keysDown = [40];
  11189. this.keysLeft = [37];
  11190. this.keysRight = [39];
  11191. this.checkCollisions = false;
  11192. this.applyGravity = false;
  11193. this.angularSensibility = 2000.0;
  11194. this._keys = [];
  11195. this._collider = new BABYLON.Collider();
  11196. this._needMoveForGravity = false;
  11197. this._oldPosition = BABYLON.Vector3.Zero();
  11198. this._diffPosition = BABYLON.Vector3.Zero();
  11199. this._newPosition = BABYLON.Vector3.Zero();
  11200. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11201. if (collidedMesh === void 0) { collidedMesh = null; }
  11202. //TODO move this to the collision coordinator!
  11203. if (_this.getScene().workerCollisions)
  11204. newPosition.multiplyInPlace(_this._collider.radius);
  11205. var updatePosition = function (newPos) {
  11206. _this._newPosition.copyFrom(newPos);
  11207. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11208. var oldPosition = _this.position.clone();
  11209. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11210. _this.position.addInPlace(_this._diffPosition);
  11211. if (_this.onCollide && collidedMesh) {
  11212. _this.onCollide(collidedMesh);
  11213. }
  11214. }
  11215. };
  11216. updatePosition(newPosition);
  11217. };
  11218. }
  11219. FreeCamera.prototype._onLostFocus = function (e) {
  11220. this._keys = [];
  11221. };
  11222. // Controls
  11223. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11224. var _this = this;
  11225. var previousPosition;
  11226. var engine = this.getEngine();
  11227. if (this._attachedElement) {
  11228. return;
  11229. }
  11230. this._attachedElement = element;
  11231. if (this._onMouseDown === undefined) {
  11232. this._onMouseDown = function (evt) {
  11233. previousPosition = {
  11234. x: evt.clientX,
  11235. y: evt.clientY
  11236. };
  11237. if (!noPreventDefault) {
  11238. evt.preventDefault();
  11239. }
  11240. };
  11241. this._onMouseUp = function (evt) {
  11242. previousPosition = null;
  11243. if (!noPreventDefault) {
  11244. evt.preventDefault();
  11245. }
  11246. };
  11247. this._onMouseOut = function (evt) {
  11248. previousPosition = null;
  11249. _this._keys = [];
  11250. if (!noPreventDefault) {
  11251. evt.preventDefault();
  11252. }
  11253. };
  11254. this._onMouseMove = function (evt) {
  11255. if (!previousPosition && !engine.isPointerLock) {
  11256. return;
  11257. }
  11258. var offsetX;
  11259. var offsetY;
  11260. if (!engine.isPointerLock) {
  11261. offsetX = evt.clientX - previousPosition.x;
  11262. offsetY = evt.clientY - previousPosition.y;
  11263. }
  11264. else {
  11265. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11266. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11267. }
  11268. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11269. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11270. previousPosition = {
  11271. x: evt.clientX,
  11272. y: evt.clientY
  11273. };
  11274. if (!noPreventDefault) {
  11275. evt.preventDefault();
  11276. }
  11277. };
  11278. this._onKeyDown = function (evt) {
  11279. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11280. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11281. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11282. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11283. var index = _this._keys.indexOf(evt.keyCode);
  11284. if (index === -1) {
  11285. _this._keys.push(evt.keyCode);
  11286. }
  11287. if (!noPreventDefault) {
  11288. evt.preventDefault();
  11289. }
  11290. }
  11291. };
  11292. this._onKeyUp = function (evt) {
  11293. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11294. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11295. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11296. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11297. var index = _this._keys.indexOf(evt.keyCode);
  11298. if (index >= 0) {
  11299. _this._keys.splice(index, 1);
  11300. }
  11301. if (!noPreventDefault) {
  11302. evt.preventDefault();
  11303. }
  11304. }
  11305. };
  11306. this._reset = function () {
  11307. _this._keys = [];
  11308. previousPosition = null;
  11309. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11310. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11311. };
  11312. }
  11313. element.addEventListener("mousedown", this._onMouseDown, false);
  11314. element.addEventListener("mouseup", this._onMouseUp, false);
  11315. element.addEventListener("mouseout", this._onMouseOut, false);
  11316. element.addEventListener("mousemove", this._onMouseMove, false);
  11317. BABYLON.Tools.RegisterTopRootEvents([
  11318. { name: "keydown", handler: this._onKeyDown },
  11319. { name: "keyup", handler: this._onKeyUp },
  11320. { name: "blur", handler: this._onLostFocus }
  11321. ]);
  11322. };
  11323. FreeCamera.prototype.detachControl = function (element) {
  11324. if (this._attachedElement !== element) {
  11325. return;
  11326. }
  11327. element.removeEventListener("mousedown", this._onMouseDown);
  11328. element.removeEventListener("mouseup", this._onMouseUp);
  11329. element.removeEventListener("mouseout", this._onMouseOut);
  11330. element.removeEventListener("mousemove", this._onMouseMove);
  11331. BABYLON.Tools.UnregisterTopRootEvents([
  11332. { name: "keydown", handler: this._onKeyDown },
  11333. { name: "keyup", handler: this._onKeyUp },
  11334. { name: "blur", handler: this._onLostFocus }
  11335. ]);
  11336. this._attachedElement = null;
  11337. if (this._reset) {
  11338. this._reset();
  11339. }
  11340. };
  11341. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11342. var globalPosition;
  11343. if (this.parent) {
  11344. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11345. }
  11346. else {
  11347. globalPosition = this.position;
  11348. }
  11349. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11350. this._collider.radius = this.ellipsoid;
  11351. //no need for clone, as long as gravity is not on.
  11352. var actualVelocity = velocity;
  11353. //add gravity to the velocity to prevent the dual-collision checking
  11354. if (this.applyGravity) {
  11355. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11356. actualVelocity = velocity.add(this.getScene().gravity);
  11357. }
  11358. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11359. };
  11360. FreeCamera.prototype._checkInputs = function () {
  11361. if (!this._localDirection) {
  11362. this._localDirection = BABYLON.Vector3.Zero();
  11363. this._transformedDirection = BABYLON.Vector3.Zero();
  11364. }
  11365. // Keyboard
  11366. for (var index = 0; index < this._keys.length; index++) {
  11367. var keyCode = this._keys[index];
  11368. var speed = this._computeLocalCameraSpeed();
  11369. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11370. this._localDirection.copyFromFloats(-speed, 0, 0);
  11371. }
  11372. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11373. this._localDirection.copyFromFloats(0, 0, speed);
  11374. }
  11375. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11376. this._localDirection.copyFromFloats(speed, 0, 0);
  11377. }
  11378. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11379. this._localDirection.copyFromFloats(0, 0, -speed);
  11380. }
  11381. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11382. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11383. this.cameraDirection.addInPlace(this._transformedDirection);
  11384. }
  11385. _super.prototype._checkInputs.call(this);
  11386. };
  11387. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11388. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11389. };
  11390. FreeCamera.prototype._updatePosition = function () {
  11391. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11392. this._collideWithWorld(this.cameraDirection);
  11393. }
  11394. else {
  11395. this.position.addInPlace(this.cameraDirection);
  11396. }
  11397. };
  11398. FreeCamera.prototype.getTypeName = function () {
  11399. return "FreeCamera";
  11400. };
  11401. __decorate([
  11402. BABYLON.serializeAsVector3()
  11403. ], FreeCamera.prototype, "ellipsoid", void 0);
  11404. __decorate([
  11405. BABYLON.serialize()
  11406. ], FreeCamera.prototype, "keysUp", void 0);
  11407. __decorate([
  11408. BABYLON.serialize()
  11409. ], FreeCamera.prototype, "keysDown", void 0);
  11410. __decorate([
  11411. BABYLON.serialize()
  11412. ], FreeCamera.prototype, "keysLeft", void 0);
  11413. __decorate([
  11414. BABYLON.serialize()
  11415. ], FreeCamera.prototype, "keysRight", void 0);
  11416. __decorate([
  11417. BABYLON.serialize()
  11418. ], FreeCamera.prototype, "checkCollisions", void 0);
  11419. __decorate([
  11420. BABYLON.serialize()
  11421. ], FreeCamera.prototype, "applyGravity", void 0);
  11422. __decorate([
  11423. BABYLON.serialize()
  11424. ], FreeCamera.prototype, "angularSensibility", void 0);
  11425. return FreeCamera;
  11426. })(BABYLON.TargetCamera);
  11427. BABYLON.FreeCamera = FreeCamera;
  11428. })(BABYLON || (BABYLON = {}));
  11429. var BABYLON;
  11430. (function (BABYLON) {
  11431. var FollowCamera = (function (_super) {
  11432. __extends(FollowCamera, _super);
  11433. function FollowCamera(name, position, scene, target) {
  11434. _super.call(this, name, position, scene);
  11435. this.radius = 12;
  11436. this.rotationOffset = 0;
  11437. this.heightOffset = 4;
  11438. this.cameraAcceleration = 0.05;
  11439. this.maxCameraSpeed = 20;
  11440. this.target = target;
  11441. }
  11442. FollowCamera.prototype.getRadians = function (degrees) {
  11443. return degrees * Math.PI / 180;
  11444. };
  11445. FollowCamera.prototype.follow = function (cameraTarget) {
  11446. if (!cameraTarget)
  11447. return;
  11448. var yRotation;
  11449. if (cameraTarget.rotationQuaternion) {
  11450. var rotMatrix = new BABYLON.Matrix();
  11451. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11452. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11453. }
  11454. else {
  11455. yRotation = cameraTarget.rotation.y;
  11456. }
  11457. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11458. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11459. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11460. var dx = targetX - this.position.x;
  11461. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11462. var dz = (targetZ) - this.position.z;
  11463. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11464. var vy = dy * this.cameraAcceleration;
  11465. var vz = dz * this.cameraAcceleration * 2;
  11466. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11467. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11468. }
  11469. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11470. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11471. }
  11472. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11473. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11474. }
  11475. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11476. this.setTarget(cameraTarget.position);
  11477. };
  11478. FollowCamera.prototype._checkInputs = function () {
  11479. _super.prototype._checkInputs.call(this);
  11480. this.follow(this.target);
  11481. };
  11482. FollowCamera.prototype.getTypeName = function () {
  11483. return "FollowCamera";
  11484. };
  11485. __decorate([
  11486. BABYLON.serialize()
  11487. ], FollowCamera.prototype, "radius", void 0);
  11488. __decorate([
  11489. BABYLON.serialize()
  11490. ], FollowCamera.prototype, "rotationOffset", void 0);
  11491. __decorate([
  11492. BABYLON.serialize()
  11493. ], FollowCamera.prototype, "heightOffset", void 0);
  11494. __decorate([
  11495. BABYLON.serialize()
  11496. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11497. __decorate([
  11498. BABYLON.serialize()
  11499. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11500. __decorate([
  11501. BABYLON.serializeAsMeshReference("lockedTargetId")
  11502. ], FollowCamera.prototype, "target", void 0);
  11503. return FollowCamera;
  11504. })(BABYLON.TargetCamera);
  11505. BABYLON.FollowCamera = FollowCamera;
  11506. var ArcFollowCamera = (function (_super) {
  11507. __extends(ArcFollowCamera, _super);
  11508. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11509. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11510. this.alpha = alpha;
  11511. this.beta = beta;
  11512. this.radius = radius;
  11513. this.target = target;
  11514. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11515. this.follow();
  11516. }
  11517. ArcFollowCamera.prototype.follow = function () {
  11518. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11519. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11520. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11521. this.position = this.target.position.add(this._cartesianCoordinates);
  11522. this.setTarget(this.target.position);
  11523. };
  11524. ArcFollowCamera.prototype._checkInputs = function () {
  11525. _super.prototype._checkInputs.call(this);
  11526. this.follow();
  11527. };
  11528. ArcFollowCamera.prototype.getTypeName = function () {
  11529. return "ArcFollowCamera";
  11530. };
  11531. return ArcFollowCamera;
  11532. })(BABYLON.TargetCamera);
  11533. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11534. })(BABYLON || (BABYLON = {}));
  11535. var BABYLON;
  11536. (function (BABYLON) {
  11537. // We're mainly based on the logic defined into the FreeCamera code
  11538. var TouchCamera = (function (_super) {
  11539. __extends(TouchCamera, _super);
  11540. function TouchCamera(name, position, scene) {
  11541. _super.call(this, name, position, scene);
  11542. this._offsetX = null;
  11543. this._offsetY = null;
  11544. this._pointerCount = 0;
  11545. this._pointerPressed = [];
  11546. this.touchAngularSensibility = 200000.0;
  11547. this.touchMoveSensibility = 250.0;
  11548. }
  11549. TouchCamera.prototype._onLostFocus = function (e) {
  11550. this._offsetX = null;
  11551. this._offsetY = null;
  11552. _super.prototype._onLostFocus.call(this, e);
  11553. };
  11554. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11555. var _this = this;
  11556. var previousPosition;
  11557. if (this._attachedCanvas) {
  11558. return;
  11559. }
  11560. if (this._onPointerDown === undefined) {
  11561. this._onPointerDown = function (evt) {
  11562. if (evt.pointerType === "mouse") {
  11563. return;
  11564. }
  11565. if (!noPreventDefault) {
  11566. evt.preventDefault();
  11567. }
  11568. _this._pointerPressed.push(evt.pointerId);
  11569. if (_this._pointerPressed.length !== 1) {
  11570. return;
  11571. }
  11572. previousPosition = {
  11573. x: evt.clientX,
  11574. y: evt.clientY
  11575. };
  11576. };
  11577. this._onPointerUp = function (evt) {
  11578. if (evt.pointerType === "mouse") {
  11579. return;
  11580. }
  11581. if (!noPreventDefault) {
  11582. evt.preventDefault();
  11583. }
  11584. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11585. if (index === -1) {
  11586. return;
  11587. }
  11588. _this._pointerPressed.splice(index, 1);
  11589. if (index != 0) {
  11590. return;
  11591. }
  11592. previousPosition = null;
  11593. _this._offsetX = null;
  11594. _this._offsetY = null;
  11595. };
  11596. this._onPointerMove = function (evt) {
  11597. if (evt.pointerType === "mouse") {
  11598. return;
  11599. }
  11600. if (!noPreventDefault) {
  11601. evt.preventDefault();
  11602. }
  11603. if (!previousPosition) {
  11604. return;
  11605. }
  11606. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11607. if (index != 0) {
  11608. return;
  11609. }
  11610. _this._offsetX = evt.clientX - previousPosition.x;
  11611. _this._offsetY = -(evt.clientY - previousPosition.y);
  11612. };
  11613. }
  11614. canvas.addEventListener("pointerdown", this._onPointerDown);
  11615. canvas.addEventListener("pointerup", this._onPointerUp);
  11616. canvas.addEventListener("pointerout", this._onPointerUp);
  11617. canvas.addEventListener("pointermove", this._onPointerMove);
  11618. _super.prototype.attachControl.call(this, canvas);
  11619. };
  11620. TouchCamera.prototype.detachControl = function (canvas) {
  11621. if (this._attachedCanvas !== canvas) {
  11622. return;
  11623. }
  11624. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11625. canvas.removeEventListener("pointerup", this._onPointerUp);
  11626. canvas.removeEventListener("pointerout", this._onPointerUp);
  11627. canvas.removeEventListener("pointermove", this._onPointerMove);
  11628. _super.prototype.detachControl.call(this, canvas);
  11629. };
  11630. TouchCamera.prototype._checkInputs = function () {
  11631. if (this._offsetX) {
  11632. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11633. if (this._pointerPressed.length > 1) {
  11634. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11635. }
  11636. else {
  11637. var speed = this._computeLocalCameraSpeed();
  11638. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11639. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11640. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11641. }
  11642. }
  11643. _super.prototype._checkInputs.call(this);
  11644. };
  11645. TouchCamera.prototype.getTypeName = function () {
  11646. return "TouchCamera";
  11647. };
  11648. __decorate([
  11649. BABYLON.serialize()
  11650. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11651. __decorate([
  11652. BABYLON.serialize()
  11653. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11654. return TouchCamera;
  11655. })(BABYLON.FreeCamera);
  11656. BABYLON.TouchCamera = TouchCamera;
  11657. })(BABYLON || (BABYLON = {}));
  11658. var BABYLON;
  11659. (function (BABYLON) {
  11660. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11661. var ArcRotateCamera = (function (_super) {
  11662. __extends(ArcRotateCamera, _super);
  11663. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11664. var _this = this;
  11665. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11666. this.inertialAlphaOffset = 0;
  11667. this.inertialBetaOffset = 0;
  11668. this.inertialRadiusOffset = 0;
  11669. this.lowerAlphaLimit = null;
  11670. this.upperAlphaLimit = null;
  11671. this.lowerBetaLimit = 0.01;
  11672. this.upperBetaLimit = Math.PI;
  11673. this.lowerRadiusLimit = null;
  11674. this.upperRadiusLimit = null;
  11675. this.angularSensibilityX = 1000.0;
  11676. this.angularSensibilityY = 1000.0;
  11677. this.wheelPrecision = 3.0;
  11678. this.pinchPrecision = 2.0;
  11679. this.panningSensibility = 50.0;
  11680. this.inertialPanningX = 0;
  11681. this.inertialPanningY = 0;
  11682. this.keysUp = [38];
  11683. this.keysDown = [40];
  11684. this.keysLeft = [37];
  11685. this.keysRight = [39];
  11686. this.zoomOnFactor = 1;
  11687. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11688. this.pinchInwards = true;
  11689. this.allowUpsideDown = true;
  11690. this._keys = [];
  11691. this._viewMatrix = new BABYLON.Matrix();
  11692. // Panning
  11693. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11694. this._isRightClick = false;
  11695. this._isCtrlPushed = false;
  11696. this.checkCollisions = false;
  11697. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11698. this._collider = new BABYLON.Collider();
  11699. this._previousPosition = BABYLON.Vector3.Zero();
  11700. this._collisionVelocity = BABYLON.Vector3.Zero();
  11701. this._newPosition = BABYLON.Vector3.Zero();
  11702. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11703. if (collidedMesh === void 0) { collidedMesh = null; }
  11704. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11705. newPosition.multiplyInPlace(_this._collider.radius);
  11706. }
  11707. if (!collidedMesh) {
  11708. _this._previousPosition.copyFrom(_this.position);
  11709. }
  11710. else {
  11711. _this.setPosition(newPosition);
  11712. if (_this.onCollide) {
  11713. _this.onCollide(collidedMesh);
  11714. }
  11715. }
  11716. // Recompute because of constraints
  11717. var cosa = Math.cos(_this.alpha);
  11718. var sina = Math.sin(_this.alpha);
  11719. var cosb = Math.cos(_this.beta);
  11720. var sinb = Math.sin(_this.beta);
  11721. if (sinb === 0) {
  11722. sinb = 0.0001;
  11723. }
  11724. var target = _this.target;
  11725. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11726. _this.position.copyFrom(_this._newPosition);
  11727. var up = _this.upVector;
  11728. if (_this.allowUpsideDown && _this.beta < 0) {
  11729. up = up.clone();
  11730. up = up.negate();
  11731. }
  11732. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11733. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11734. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11735. _this._collisionTriggered = false;
  11736. };
  11737. if (!this.target) {
  11738. this.target = BABYLON.Vector3.Zero();
  11739. }
  11740. else {
  11741. this.target = target;
  11742. }
  11743. this.alpha = alpha;
  11744. this.beta = beta;
  11745. this.radius = radius;
  11746. this.getViewMatrix();
  11747. }
  11748. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11749. //deprecated angularSensibility support
  11750. get: function () {
  11751. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11752. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11753. },
  11754. //deprecated angularSensibility support
  11755. set: function (value) {
  11756. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11757. this.angularSensibilityX = value;
  11758. this.angularSensibilityY = value;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. // Cache
  11764. ArcRotateCamera.prototype._initCache = function () {
  11765. _super.prototype._initCache.call(this);
  11766. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11767. this._cache.alpha = undefined;
  11768. this._cache.beta = undefined;
  11769. this._cache.radius = undefined;
  11770. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11771. };
  11772. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11773. if (!ignoreParentClass) {
  11774. _super.prototype._updateCache.call(this);
  11775. }
  11776. this._cache.target.copyFrom(this.target);
  11777. this._cache.alpha = this.alpha;
  11778. this._cache.beta = this.beta;
  11779. this._cache.radius = this.radius;
  11780. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11781. };
  11782. // Synchronized
  11783. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11784. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11785. return false;
  11786. return this._cache.target.equals(this.target)
  11787. && this._cache.alpha === this.alpha
  11788. && this._cache.beta === this.beta
  11789. && this._cache.radius === this.radius
  11790. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11791. };
  11792. // Methods
  11793. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11794. var _this = this;
  11795. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11796. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11797. var previousPinchDistance = 0;
  11798. var pointers = new BABYLON.SmartCollection();
  11799. if (this._attachedElement) {
  11800. return;
  11801. }
  11802. this._attachedElement = element;
  11803. var engine = this.getEngine();
  11804. if (this._onPointerDown === undefined) {
  11805. this._onPointerDown = function (evt) {
  11806. // Manage panning with right click
  11807. _this._isRightClick = evt.button === 2;
  11808. // manage pointers
  11809. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11810. cacheSoloPointer = pointers.item(evt.pointerId);
  11811. if (!noPreventDefault) {
  11812. evt.preventDefault();
  11813. }
  11814. };
  11815. this._onPointerUp = function (evt) {
  11816. cacheSoloPointer = null;
  11817. previousPinchDistance = 0;
  11818. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11819. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11820. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11821. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11822. pointers.empty();
  11823. if (!noPreventDefault) {
  11824. evt.preventDefault();
  11825. }
  11826. };
  11827. this._onContextMenu = function (evt) {
  11828. evt.preventDefault();
  11829. };
  11830. this._onPointerMove = function (evt) {
  11831. if (!noPreventDefault) {
  11832. evt.preventDefault();
  11833. }
  11834. switch (pointers.count) {
  11835. case 1:
  11836. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11837. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11838. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11839. }
  11840. else {
  11841. var offsetX = evt.clientX - cacheSoloPointer.x;
  11842. var offsetY = evt.clientY - cacheSoloPointer.y;
  11843. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11844. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11845. }
  11846. cacheSoloPointer.x = evt.clientX;
  11847. cacheSoloPointer.y = evt.clientY;
  11848. break;
  11849. case 2:
  11850. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11851. pointers.item(evt.pointerId).x = evt.clientX;
  11852. pointers.item(evt.pointerId).y = evt.clientY;
  11853. var direction = _this.pinchInwards ? 1 : -1;
  11854. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11855. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11856. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11857. if (previousPinchDistance === 0) {
  11858. previousPinchDistance = pinchSquaredDistance;
  11859. return;
  11860. }
  11861. if (pinchSquaredDistance !== previousPinchDistance) {
  11862. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11863. previousPinchDistance = pinchSquaredDistance;
  11864. }
  11865. break;
  11866. default:
  11867. if (pointers.item(evt.pointerId)) {
  11868. pointers.item(evt.pointerId).x = evt.clientX;
  11869. pointers.item(evt.pointerId).y = evt.clientY;
  11870. }
  11871. }
  11872. };
  11873. this._onMouseMove = function (evt) {
  11874. if (!engine.isPointerLock) {
  11875. return;
  11876. }
  11877. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11878. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11879. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11880. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11881. if (!noPreventDefault) {
  11882. evt.preventDefault();
  11883. }
  11884. };
  11885. this._wheel = function (event) {
  11886. var delta = 0;
  11887. if (event.wheelDelta) {
  11888. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11889. }
  11890. else if (event.detail) {
  11891. delta = -event.detail / _this.wheelPrecision;
  11892. }
  11893. if (delta)
  11894. _this.inertialRadiusOffset += delta;
  11895. if (event.preventDefault) {
  11896. if (!noPreventDefault) {
  11897. event.preventDefault();
  11898. }
  11899. }
  11900. };
  11901. this._onKeyDown = function (evt) {
  11902. _this._isCtrlPushed = evt.ctrlKey;
  11903. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11904. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11905. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11906. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11907. var index = _this._keys.indexOf(evt.keyCode);
  11908. if (index === -1) {
  11909. _this._keys.push(evt.keyCode);
  11910. }
  11911. if (evt.preventDefault) {
  11912. if (!noPreventDefault) {
  11913. evt.preventDefault();
  11914. }
  11915. }
  11916. }
  11917. };
  11918. this._onKeyUp = function (evt) {
  11919. _this._isCtrlPushed = evt.ctrlKey;
  11920. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11921. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11922. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11923. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11924. var index = _this._keys.indexOf(evt.keyCode);
  11925. if (index >= 0) {
  11926. _this._keys.splice(index, 1);
  11927. }
  11928. if (evt.preventDefault) {
  11929. if (!noPreventDefault) {
  11930. evt.preventDefault();
  11931. }
  11932. }
  11933. }
  11934. };
  11935. this._onLostFocus = function () {
  11936. _this._keys = [];
  11937. pointers.empty();
  11938. previousPinchDistance = 0;
  11939. cacheSoloPointer = null;
  11940. };
  11941. this._onGestureStart = function (e) {
  11942. if (window.MSGesture === undefined) {
  11943. return;
  11944. }
  11945. if (!_this._MSGestureHandler) {
  11946. _this._MSGestureHandler = new MSGesture();
  11947. _this._MSGestureHandler.target = element;
  11948. }
  11949. _this._MSGestureHandler.addPointer(e.pointerId);
  11950. };
  11951. this._onGesture = function (e) {
  11952. _this.radius *= e.scale;
  11953. if (e.preventDefault) {
  11954. if (!noPreventDefault) {
  11955. e.stopPropagation();
  11956. e.preventDefault();
  11957. }
  11958. }
  11959. };
  11960. this._reset = function () {
  11961. _this._keys = [];
  11962. _this.inertialAlphaOffset = 0;
  11963. _this.inertialBetaOffset = 0;
  11964. _this.inertialRadiusOffset = 0;
  11965. pointers.empty();
  11966. previousPinchDistance = 0;
  11967. cacheSoloPointer = null;
  11968. };
  11969. }
  11970. if (!useCtrlForPanning) {
  11971. element.addEventListener("contextmenu", this._onContextMenu, false);
  11972. }
  11973. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11974. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11975. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11976. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11977. element.addEventListener("mousemove", this._onMouseMove, false);
  11978. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11979. element.addEventListener("MSGestureChange", this._onGesture, false);
  11980. element.addEventListener('mousewheel', this._wheel, false);
  11981. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11982. BABYLON.Tools.RegisterTopRootEvents([
  11983. { name: "keydown", handler: this._onKeyDown },
  11984. { name: "keyup", handler: this._onKeyUp },
  11985. { name: "blur", handler: this._onLostFocus }
  11986. ]);
  11987. };
  11988. ArcRotateCamera.prototype.detachControl = function (element) {
  11989. if (this._attachedElement !== element) {
  11990. return;
  11991. }
  11992. element.removeEventListener("contextmenu", this._onContextMenu);
  11993. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11994. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11995. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11996. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11997. element.removeEventListener("mousemove", this._onMouseMove);
  11998. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11999. element.removeEventListener("MSGestureChange", this._onGesture);
  12000. element.removeEventListener('mousewheel', this._wheel);
  12001. element.removeEventListener('DOMMouseScroll', this._wheel);
  12002. BABYLON.Tools.UnregisterTopRootEvents([
  12003. { name: "keydown", handler: this._onKeyDown },
  12004. { name: "keyup", handler: this._onKeyUp },
  12005. { name: "blur", handler: this._onLostFocus }
  12006. ]);
  12007. this._MSGestureHandler = null;
  12008. this._attachedElement = null;
  12009. if (this._reset) {
  12010. this._reset();
  12011. }
  12012. };
  12013. ArcRotateCamera.prototype._checkInputs = function () {
  12014. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12015. if (this._collisionTriggered) {
  12016. return;
  12017. }
  12018. // Keyboard
  12019. for (var index = 0; index < this._keys.length; index++) {
  12020. var keyCode = this._keys[index];
  12021. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12022. this.inertialAlphaOffset -= 0.01;
  12023. }
  12024. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12025. this.inertialBetaOffset -= 0.01;
  12026. }
  12027. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12028. this.inertialAlphaOffset += 0.01;
  12029. }
  12030. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12031. this.inertialBetaOffset += 0.01;
  12032. }
  12033. }
  12034. // Inertia
  12035. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12036. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12037. this.beta += this.inertialBetaOffset;
  12038. this.radius -= this.inertialRadiusOffset;
  12039. this.inertialAlphaOffset *= this.inertia;
  12040. this.inertialBetaOffset *= this.inertia;
  12041. this.inertialRadiusOffset *= this.inertia;
  12042. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  12043. this.inertialAlphaOffset = 0;
  12044. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  12045. this.inertialBetaOffset = 0;
  12046. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  12047. this.inertialRadiusOffset = 0;
  12048. }
  12049. // Panning inertia
  12050. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12051. if (!this._localDirection) {
  12052. this._localDirection = BABYLON.Vector3.Zero();
  12053. this._transformedDirection = BABYLON.Vector3.Zero();
  12054. }
  12055. this.inertialPanningX *= this.inertia;
  12056. this.inertialPanningY *= this.inertia;
  12057. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  12058. this.inertialPanningX = 0;
  12059. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  12060. this.inertialPanningY = 0;
  12061. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12062. this._localDirection.multiplyInPlace(this.panningAxis);
  12063. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12064. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12065. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12066. if (!this.panningAxis.y) {
  12067. this._transformedDirection.y = 0;
  12068. }
  12069. this.target.addInPlace(this._transformedDirection);
  12070. }
  12071. // Limits
  12072. this._checkLimits();
  12073. _super.prototype._checkInputs.call(this);
  12074. };
  12075. ArcRotateCamera.prototype._checkLimits = function () {
  12076. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12077. if (this.allowUpsideDown && this.beta > Math.PI) {
  12078. this.beta = this.beta - (2 * Math.PI);
  12079. }
  12080. }
  12081. else {
  12082. if (this.beta < this.lowerBetaLimit) {
  12083. this.beta = this.lowerBetaLimit;
  12084. }
  12085. }
  12086. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12087. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12088. this.beta = this.beta + (2 * Math.PI);
  12089. }
  12090. }
  12091. else {
  12092. if (this.beta > this.upperBetaLimit) {
  12093. this.beta = this.upperBetaLimit;
  12094. }
  12095. }
  12096. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12097. this.alpha = this.lowerAlphaLimit;
  12098. }
  12099. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12100. this.alpha = this.upperAlphaLimit;
  12101. }
  12102. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12103. this.radius = this.lowerRadiusLimit;
  12104. }
  12105. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12106. this.radius = this.upperRadiusLimit;
  12107. }
  12108. };
  12109. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12110. var radiusv3 = this.position.subtract(this.target);
  12111. this.radius = radiusv3.length();
  12112. // Alpha
  12113. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12114. if (radiusv3.z < 0) {
  12115. this.alpha = 2 * Math.PI - this.alpha;
  12116. }
  12117. // Beta
  12118. this.beta = Math.acos(radiusv3.y / this.radius);
  12119. this._checkLimits();
  12120. };
  12121. ArcRotateCamera.prototype.setPosition = function (position) {
  12122. if (this.position.equals(position)) {
  12123. return;
  12124. }
  12125. this.position = position;
  12126. this.rebuildAnglesAndRadius();
  12127. };
  12128. ArcRotateCamera.prototype.setTarget = function (target) {
  12129. if (this.target.equals(target)) {
  12130. return;
  12131. }
  12132. this.target = target;
  12133. this.rebuildAnglesAndRadius();
  12134. };
  12135. ArcRotateCamera.prototype._getViewMatrix = function () {
  12136. // Compute
  12137. var cosa = Math.cos(this.alpha);
  12138. var sina = Math.sin(this.alpha);
  12139. var cosb = Math.cos(this.beta);
  12140. var sinb = Math.sin(this.beta);
  12141. if (sinb === 0) {
  12142. sinb = 0.0001;
  12143. }
  12144. var target = this.target;
  12145. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12146. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12147. this._collider.radius = this.collisionRadius;
  12148. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12149. this._collisionTriggered = true;
  12150. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12151. }
  12152. else {
  12153. this.position.copyFrom(this._newPosition);
  12154. var up = this.upVector;
  12155. if (this.allowUpsideDown && this.beta < 0) {
  12156. up = up.clone();
  12157. up = up.negate();
  12158. }
  12159. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12160. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12161. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12162. }
  12163. return this._viewMatrix;
  12164. };
  12165. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12166. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12167. meshes = meshes || this.getScene().meshes;
  12168. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12169. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12170. this.radius = distance * this.zoomOnFactor;
  12171. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12172. };
  12173. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12174. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12175. var meshesOrMinMaxVector;
  12176. var distance;
  12177. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12178. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12179. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12180. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12181. }
  12182. else {
  12183. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12184. distance = meshesOrMinMaxVectorAndDistance.distance;
  12185. }
  12186. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12187. if (!doNotUpdateMaxZ) {
  12188. this.maxZ = distance * 2;
  12189. }
  12190. };
  12191. /**
  12192. * @override
  12193. * Override Camera.createRigCamera
  12194. */
  12195. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12196. switch (this.cameraRigMode) {
  12197. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12199. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12200. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12201. case BABYLON.Camera.RIG_MODE_VR:
  12202. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12203. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12204. }
  12205. return null;
  12206. };
  12207. /**
  12208. * @override
  12209. * Override Camera._updateRigCameras
  12210. */
  12211. ArcRotateCamera.prototype._updateRigCameras = function () {
  12212. switch (this.cameraRigMode) {
  12213. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12214. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12215. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12216. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12217. case BABYLON.Camera.RIG_MODE_VR:
  12218. var camLeft = this._rigCameras[0];
  12219. var camRight = this._rigCameras[1];
  12220. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12221. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12222. camLeft.beta = camRight.beta = this.beta;
  12223. camLeft.radius = camRight.radius = this.radius;
  12224. break;
  12225. }
  12226. _super.prototype._updateRigCameras.call(this);
  12227. };
  12228. ArcRotateCamera.prototype.getTypeName = function () {
  12229. return "ArcRotateCamera";
  12230. };
  12231. __decorate([
  12232. BABYLON.serialize()
  12233. ], ArcRotateCamera.prototype, "alpha", void 0);
  12234. __decorate([
  12235. BABYLON.serialize()
  12236. ], ArcRotateCamera.prototype, "beta", void 0);
  12237. __decorate([
  12238. BABYLON.serialize()
  12239. ], ArcRotateCamera.prototype, "radius", void 0);
  12240. __decorate([
  12241. BABYLON.serializeAsVector3()
  12242. ], ArcRotateCamera.prototype, "target", void 0);
  12243. __decorate([
  12244. BABYLON.serialize()
  12245. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12246. __decorate([
  12247. BABYLON.serialize()
  12248. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12249. __decorate([
  12250. BABYLON.serialize()
  12251. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12252. __decorate([
  12253. BABYLON.serialize()
  12254. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12255. __decorate([
  12256. BABYLON.serialize()
  12257. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12258. __decorate([
  12259. BABYLON.serialize()
  12260. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12261. __decorate([
  12262. BABYLON.serialize()
  12263. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12264. __decorate([
  12265. BABYLON.serialize()
  12266. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12267. __decorate([
  12268. BABYLON.serialize()
  12269. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12270. __decorate([
  12271. BABYLON.serialize()
  12272. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12273. __decorate([
  12274. BABYLON.serialize()
  12275. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12276. __decorate([
  12277. BABYLON.serialize()
  12278. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12279. __decorate([
  12280. BABYLON.serialize()
  12281. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12282. __decorate([
  12283. BABYLON.serialize()
  12284. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12285. __decorate([
  12286. BABYLON.serialize()
  12287. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12288. __decorate([
  12289. BABYLON.serialize()
  12290. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12291. __decorate([
  12292. BABYLON.serialize()
  12293. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12294. __decorate([
  12295. BABYLON.serialize()
  12296. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12297. __decorate([
  12298. BABYLON.serialize()
  12299. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12300. __decorate([
  12301. BABYLON.serialize()
  12302. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12303. __decorate([
  12304. BABYLON.serialize()
  12305. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12306. __decorate([
  12307. BABYLON.serialize()
  12308. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12309. return ArcRotateCamera;
  12310. })(BABYLON.TargetCamera);
  12311. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12312. })(BABYLON || (BABYLON = {}));
  12313. var BABYLON;
  12314. (function (BABYLON) {
  12315. var RenderingManager = (function () {
  12316. function RenderingManager(scene) {
  12317. this._renderingGroups = new Array();
  12318. this._scene = scene;
  12319. }
  12320. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12321. if (this._scene._activeParticleSystems.length === 0) {
  12322. return;
  12323. }
  12324. // Particles
  12325. var activeCamera = this._scene.activeCamera;
  12326. var beforeParticlesDate = BABYLON.Tools.Now;
  12327. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12328. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12329. if (particleSystem.renderingGroupId !== index) {
  12330. continue;
  12331. }
  12332. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12333. continue;
  12334. }
  12335. this._clearDepthBuffer();
  12336. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12337. this._scene._activeParticles += particleSystem.render();
  12338. }
  12339. }
  12340. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12341. };
  12342. RenderingManager.prototype._renderSprites = function (index) {
  12343. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12344. return;
  12345. }
  12346. // Sprites
  12347. var activeCamera = this._scene.activeCamera;
  12348. var beforeSpritessDate = BABYLON.Tools.Now;
  12349. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12350. var spriteManager = this._scene.spriteManagers[id];
  12351. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12352. this._clearDepthBuffer();
  12353. spriteManager.render();
  12354. }
  12355. }
  12356. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12357. };
  12358. RenderingManager.prototype._clearDepthBuffer = function () {
  12359. if (this._depthBufferAlreadyCleaned) {
  12360. return;
  12361. }
  12362. this._scene.getEngine().clear(0, false, true);
  12363. this._depthBufferAlreadyCleaned = true;
  12364. };
  12365. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12366. if (this._currentRenderSprites) {
  12367. this._renderSprites(this._currentIndex);
  12368. }
  12369. if (this._currentRenderParticles) {
  12370. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12371. }
  12372. };
  12373. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12374. this._currentActiveMeshes = activeMeshes;
  12375. this._currentRenderParticles = renderParticles;
  12376. this._currentRenderSprites = renderSprites;
  12377. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12378. this._depthBufferAlreadyCleaned = index == 0;
  12379. var renderingGroup = this._renderingGroups[index];
  12380. var needToStepBack = false;
  12381. this._currentIndex = index;
  12382. if (renderingGroup) {
  12383. this._clearDepthBuffer();
  12384. if (!renderingGroup.onBeforeTransparentRendering) {
  12385. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12386. }
  12387. if (!renderingGroup.render(customRenderFunction)) {
  12388. this._renderingGroups.splice(index, 1);
  12389. needToStepBack = true;
  12390. this._renderSpritesAndParticles();
  12391. }
  12392. }
  12393. else {
  12394. this._renderSpritesAndParticles();
  12395. }
  12396. if (needToStepBack) {
  12397. index--;
  12398. }
  12399. }
  12400. };
  12401. RenderingManager.prototype.reset = function () {
  12402. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12403. if (renderingGroup) {
  12404. renderingGroup.prepare();
  12405. }
  12406. });
  12407. };
  12408. RenderingManager.prototype.dispatch = function (subMesh) {
  12409. var mesh = subMesh.getMesh();
  12410. var renderingGroupId = mesh.renderingGroupId || 0;
  12411. if (!this._renderingGroups[renderingGroupId]) {
  12412. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12413. }
  12414. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12415. };
  12416. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12417. return RenderingManager;
  12418. })();
  12419. BABYLON.RenderingManager = RenderingManager;
  12420. })(BABYLON || (BABYLON = {}));
  12421. var BABYLON;
  12422. (function (BABYLON) {
  12423. var RenderingGroup = (function () {
  12424. function RenderingGroup(index, scene) {
  12425. this.index = index;
  12426. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12427. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12428. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12429. this._scene = scene;
  12430. }
  12431. RenderingGroup.prototype.render = function (customRenderFunction) {
  12432. if (customRenderFunction) {
  12433. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12434. return true;
  12435. }
  12436. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12437. if (this.onBeforeTransparentRendering) {
  12438. this.onBeforeTransparentRendering();
  12439. }
  12440. return false;
  12441. }
  12442. var engine = this._scene.getEngine();
  12443. // Opaque
  12444. var subIndex;
  12445. var submesh;
  12446. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12447. submesh = this._opaqueSubMeshes.data[subIndex];
  12448. submesh.render(false);
  12449. }
  12450. // Alpha test
  12451. engine.setAlphaTesting(true);
  12452. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12453. submesh = this._alphaTestSubMeshes.data[subIndex];
  12454. submesh.render(false);
  12455. }
  12456. engine.setAlphaTesting(false);
  12457. if (this.onBeforeTransparentRendering) {
  12458. this.onBeforeTransparentRendering();
  12459. }
  12460. // Transparent
  12461. if (this._transparentSubMeshes.length) {
  12462. // Sorting
  12463. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12464. submesh = this._transparentSubMeshes.data[subIndex];
  12465. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12466. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12467. }
  12468. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12469. sortedArray.sort(function (a, b) {
  12470. // Alpha index first
  12471. if (a._alphaIndex > b._alphaIndex) {
  12472. return 1;
  12473. }
  12474. if (a._alphaIndex < b._alphaIndex) {
  12475. return -1;
  12476. }
  12477. // Then distance to camera
  12478. if (a._distanceToCamera < b._distanceToCamera) {
  12479. return 1;
  12480. }
  12481. if (a._distanceToCamera > b._distanceToCamera) {
  12482. return -1;
  12483. }
  12484. return 0;
  12485. });
  12486. // Rendering
  12487. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12488. submesh = sortedArray[subIndex];
  12489. submesh.render(true);
  12490. }
  12491. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12492. }
  12493. return true;
  12494. };
  12495. RenderingGroup.prototype.prepare = function () {
  12496. this._opaqueSubMeshes.reset();
  12497. this._transparentSubMeshes.reset();
  12498. this._alphaTestSubMeshes.reset();
  12499. };
  12500. RenderingGroup.prototype.dispatch = function (subMesh) {
  12501. var material = subMesh.getMaterial();
  12502. var mesh = subMesh.getMesh();
  12503. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12504. this._transparentSubMeshes.push(subMesh);
  12505. }
  12506. else if (material.needAlphaTesting()) {
  12507. this._alphaTestSubMeshes.push(subMesh);
  12508. }
  12509. else {
  12510. this._opaqueSubMeshes.push(subMesh); // Opaque
  12511. }
  12512. };
  12513. return RenderingGroup;
  12514. })();
  12515. BABYLON.RenderingGroup = RenderingGroup;
  12516. })(BABYLON || (BABYLON = {}));
  12517. var BABYLON;
  12518. (function (BABYLON) {
  12519. /**
  12520. * Represents a scene to be rendered by the engine.
  12521. * @see http://doc.babylonjs.com/page.php?p=21911
  12522. */
  12523. var Scene = (function () {
  12524. /**
  12525. * @constructor
  12526. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12527. */
  12528. function Scene(engine) {
  12529. // Members
  12530. this.autoClear = true;
  12531. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12532. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12533. this.forceWireframe = false;
  12534. this.forcePointsCloud = false;
  12535. this.forceShowBoundingBoxes = false;
  12536. this.animationsEnabled = true;
  12537. this.constantlyUpdateMeshUnderPointer = false;
  12538. // Animations
  12539. this.animations = [];
  12540. 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
  12541. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12542. this._startingPointerTime = 0;
  12543. // Fog
  12544. /**
  12545. * is fog enabled on this scene.
  12546. * @type {boolean}
  12547. */
  12548. this.fogEnabled = true;
  12549. this.fogMode = Scene.FOGMODE_NONE;
  12550. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12551. this.fogDensity = 0.1;
  12552. this.fogStart = 0;
  12553. this.fogEnd = 1000.0;
  12554. // Lights
  12555. /**
  12556. * is shadow enabled on this scene.
  12557. * @type {boolean}
  12558. */
  12559. this.shadowsEnabled = true;
  12560. /**
  12561. * is light enabled on this scene.
  12562. * @type {boolean}
  12563. */
  12564. this.lightsEnabled = true;
  12565. /**
  12566. * All of the lights added to this scene.
  12567. * @see BABYLON.Light
  12568. * @type {BABYLON.Light[]}
  12569. */
  12570. this.lights = new Array();
  12571. // Cameras
  12572. /**
  12573. * All of the cameras added to this scene.
  12574. * @see BABYLON.Camera
  12575. * @type {BABYLON.Camera[]}
  12576. */
  12577. this.cameras = new Array();
  12578. this.activeCameras = new Array();
  12579. // Meshes
  12580. /**
  12581. * All of the (abstract) meshes added to this scene.
  12582. * @see BABYLON.AbstractMesh
  12583. * @type {BABYLON.AbstractMesh[]}
  12584. */
  12585. this.meshes = new Array();
  12586. // Geometries
  12587. this._geometries = new Array();
  12588. this.materials = new Array();
  12589. this.multiMaterials = new Array();
  12590. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12591. // Textures
  12592. this.texturesEnabled = true;
  12593. this.textures = new Array();
  12594. // Particles
  12595. this.particlesEnabled = true;
  12596. this.particleSystems = new Array();
  12597. // Sprites
  12598. this.spritesEnabled = true;
  12599. this.spriteManagers = new Array();
  12600. // Layers
  12601. this.layers = new Array();
  12602. // Skeletons
  12603. this.skeletonsEnabled = true;
  12604. this.skeletons = new Array();
  12605. // Lens flares
  12606. this.lensFlaresEnabled = true;
  12607. this.lensFlareSystems = new Array();
  12608. // Collisions
  12609. this.collisionsEnabled = true;
  12610. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12611. // Postprocesses
  12612. this.postProcessesEnabled = true;
  12613. // Customs render targets
  12614. this.renderTargetsEnabled = true;
  12615. this.dumpNextRenderTargets = false;
  12616. this.customRenderTargets = new Array();
  12617. // Imported meshes
  12618. this.importedMeshesFiles = new Array();
  12619. // Probes
  12620. this.probesEnabled = true;
  12621. this.reflectionProbes = new Array();
  12622. this._actionManagers = new Array();
  12623. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12624. // Procedural textures
  12625. this.proceduralTexturesEnabled = true;
  12626. this._proceduralTextures = new Array();
  12627. this.soundTracks = new Array();
  12628. this._audioEnabled = true;
  12629. this._headphone = false;
  12630. this._totalVertices = 0;
  12631. this._activeIndices = 0;
  12632. this._activeParticles = 0;
  12633. this._lastFrameDuration = 0;
  12634. this._evaluateActiveMeshesDuration = 0;
  12635. this._renderTargetsDuration = 0;
  12636. this._particlesDuration = 0;
  12637. this._renderDuration = 0;
  12638. this._spritesDuration = 0;
  12639. this._animationRatio = 0;
  12640. this._renderId = 0;
  12641. this._executeWhenReadyTimeoutId = -1;
  12642. this._toBeDisposed = new BABYLON.SmartArray(256);
  12643. this._onReadyCallbacks = new Array();
  12644. this._pendingData = []; //ANY
  12645. this._onBeforeRenderCallbacks = new Array();
  12646. this._onAfterRenderCallbacks = new Array();
  12647. this._activeMeshes = new BABYLON.SmartArray(256);
  12648. this._processedMaterials = new BABYLON.SmartArray(256);
  12649. this._renderTargets = new BABYLON.SmartArray(256);
  12650. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12651. this._activeSkeletons = new BABYLON.SmartArray(32);
  12652. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12653. this._activeBones = 0;
  12654. this._activeAnimatables = new Array();
  12655. this._transformMatrix = BABYLON.Matrix.Zero();
  12656. this._edgesRenderers = new BABYLON.SmartArray(16);
  12657. this._uniqueIdCounter = 0;
  12658. this._engine = engine;
  12659. engine.scenes.push(this);
  12660. this._renderingManager = new BABYLON.RenderingManager(this);
  12661. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12662. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12663. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12664. if (BABYLON.OutlineRenderer) {
  12665. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12666. }
  12667. this.attachControl();
  12668. this._debugLayer = new BABYLON.DebugLayer(this);
  12669. if (BABYLON.SoundTrack) {
  12670. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12671. }
  12672. //simplification queue
  12673. if (BABYLON.SimplificationQueue) {
  12674. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12675. }
  12676. //collision coordinator initialization. For now legacy per default.
  12677. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12678. }
  12679. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12680. get: function () {
  12681. return Scene._FOGMODE_NONE;
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12687. get: function () {
  12688. return Scene._FOGMODE_EXP;
  12689. },
  12690. enumerable: true,
  12691. configurable: true
  12692. });
  12693. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12694. get: function () {
  12695. return Scene._FOGMODE_EXP2;
  12696. },
  12697. enumerable: true,
  12698. configurable: true
  12699. });
  12700. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12701. get: function () {
  12702. return Scene._FOGMODE_LINEAR;
  12703. },
  12704. enumerable: true,
  12705. configurable: true
  12706. });
  12707. Object.defineProperty(Scene.prototype, "debugLayer", {
  12708. // Properties
  12709. get: function () {
  12710. return this._debugLayer;
  12711. },
  12712. enumerable: true,
  12713. configurable: true
  12714. });
  12715. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12716. get: function () {
  12717. return this._workerCollisions;
  12718. },
  12719. set: function (enabled) {
  12720. enabled = (enabled && !!Worker);
  12721. this._workerCollisions = enabled;
  12722. if (this.collisionCoordinator) {
  12723. this.collisionCoordinator.destroy();
  12724. }
  12725. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12726. this.collisionCoordinator.init(this);
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12732. get: function () {
  12733. return this._selectionOctree;
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12739. /**
  12740. * The mesh that is currently under the pointer.
  12741. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12742. */
  12743. get: function () {
  12744. return this._pointerOverMesh;
  12745. },
  12746. enumerable: true,
  12747. configurable: true
  12748. });
  12749. Object.defineProperty(Scene.prototype, "pointerX", {
  12750. /**
  12751. * Current on-screen X position of the pointer
  12752. * @return {number} X position of the pointer
  12753. */
  12754. get: function () {
  12755. return this._pointerX;
  12756. },
  12757. enumerable: true,
  12758. configurable: true
  12759. });
  12760. Object.defineProperty(Scene.prototype, "pointerY", {
  12761. /**
  12762. * Current on-screen Y position of the pointer
  12763. * @return {number} Y position of the pointer
  12764. */
  12765. get: function () {
  12766. return this._pointerY;
  12767. },
  12768. enumerable: true,
  12769. configurable: true
  12770. });
  12771. Scene.prototype.getCachedMaterial = function () {
  12772. return this._cachedMaterial;
  12773. };
  12774. Scene.prototype.getBoundingBoxRenderer = function () {
  12775. return this._boundingBoxRenderer;
  12776. };
  12777. Scene.prototype.getOutlineRenderer = function () {
  12778. return this._outlineRenderer;
  12779. };
  12780. Scene.prototype.getEngine = function () {
  12781. return this._engine;
  12782. };
  12783. Scene.prototype.getTotalVertices = function () {
  12784. return this._totalVertices;
  12785. };
  12786. Scene.prototype.getActiveIndices = function () {
  12787. return this._activeIndices;
  12788. };
  12789. Scene.prototype.getActiveParticles = function () {
  12790. return this._activeParticles;
  12791. };
  12792. Scene.prototype.getActiveBones = function () {
  12793. return this._activeBones;
  12794. };
  12795. // Stats
  12796. Scene.prototype.getLastFrameDuration = function () {
  12797. return this._lastFrameDuration;
  12798. };
  12799. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12800. return this._evaluateActiveMeshesDuration;
  12801. };
  12802. Scene.prototype.getActiveMeshes = function () {
  12803. return this._activeMeshes;
  12804. };
  12805. Scene.prototype.getRenderTargetsDuration = function () {
  12806. return this._renderTargetsDuration;
  12807. };
  12808. Scene.prototype.getRenderDuration = function () {
  12809. return this._renderDuration;
  12810. };
  12811. Scene.prototype.getParticlesDuration = function () {
  12812. return this._particlesDuration;
  12813. };
  12814. Scene.prototype.getSpritesDuration = function () {
  12815. return this._spritesDuration;
  12816. };
  12817. Scene.prototype.getAnimationRatio = function () {
  12818. return this._animationRatio;
  12819. };
  12820. Scene.prototype.getRenderId = function () {
  12821. return this._renderId;
  12822. };
  12823. Scene.prototype.incrementRenderId = function () {
  12824. this._renderId++;
  12825. };
  12826. Scene.prototype._updatePointerPosition = function (evt) {
  12827. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12828. this._pointerX = evt.clientX - canvasRect.left;
  12829. this._pointerY = evt.clientY - canvasRect.top;
  12830. this._unTranslatedPointerX = this._pointerX;
  12831. this._unTranslatedPointerY = this._pointerY;
  12832. if (this.cameraToUseForPointers) {
  12833. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12834. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12835. }
  12836. };
  12837. // Pointers handling
  12838. Scene.prototype.attachControl = function () {
  12839. var _this = this;
  12840. var spritePredicate = function (sprite) {
  12841. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12842. };
  12843. this._onPointerMove = function (evt) {
  12844. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12845. return;
  12846. }
  12847. var canvas = _this._engine.getRenderingCanvas();
  12848. _this._updatePointerPosition(evt);
  12849. // Meshes
  12850. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  12851. if (pickResult.hit && pickResult.pickedMesh) {
  12852. _this.setPointerOverSprite(null);
  12853. _this.setPointerOverMesh(pickResult.pickedMesh);
  12854. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12855. canvas.style.cursor = "pointer";
  12856. }
  12857. else {
  12858. canvas.style.cursor = "";
  12859. }
  12860. }
  12861. else {
  12862. _this.setPointerOverMesh(null);
  12863. // Sprites
  12864. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12865. if (pickResult.hit && pickResult.pickedSprite) {
  12866. canvas.style.cursor = "pointer";
  12867. _this.setPointerOverSprite(pickResult.pickedSprite);
  12868. }
  12869. else {
  12870. _this.setPointerOverSprite(null);
  12871. // Restore pointer
  12872. canvas.style.cursor = "";
  12873. }
  12874. }
  12875. if (_this.onPointerMove) {
  12876. _this.onPointerMove(evt, pickResult);
  12877. }
  12878. };
  12879. this._onPointerDown = function (evt) {
  12880. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12881. return;
  12882. }
  12883. _this._updatePointerPosition(evt);
  12884. _this._startingPointerPosition.x = _this._pointerX;
  12885. _this._startingPointerPosition.y = _this._pointerY;
  12886. _this._startingPointerTime = new Date().getTime();
  12887. var predicate = null;
  12888. // Meshes
  12889. _this._pickedDownMesh = null;
  12890. if (!_this.onPointerDown && !_this.onPointerPick) {
  12891. predicate = function (mesh) {
  12892. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12893. };
  12894. }
  12895. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  12896. if (pickResult.hit && pickResult.pickedMesh) {
  12897. if (pickResult.pickedMesh.actionManager) {
  12898. _this._pickedDownMesh = pickResult.pickedMesh;
  12899. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12900. switch (evt.button) {
  12901. case 0:
  12902. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12903. break;
  12904. case 1:
  12905. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12906. break;
  12907. case 2:
  12908. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12909. break;
  12910. }
  12911. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12912. }
  12913. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12914. var that = _this;
  12915. window.setTimeout(function () {
  12916. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12917. if (pickResult.hit && pickResult.pickedMesh) {
  12918. if (pickResult.pickedMesh.actionManager) {
  12919. 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)) {
  12920. that._startingPointerTime = 0;
  12921. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12922. }
  12923. }
  12924. }
  12925. }, BABYLON.ActionManager.LongPressDelay);
  12926. }
  12927. }
  12928. }
  12929. if (_this.onPointerDown) {
  12930. _this.onPointerDown(evt, pickResult);
  12931. }
  12932. // Sprites
  12933. _this._pickedDownSprite = null;
  12934. if (_this.spriteManagers.length > 0) {
  12935. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12936. if (pickResult.hit && pickResult.pickedSprite) {
  12937. if (pickResult.pickedSprite.actionManager) {
  12938. _this._pickedDownSprite = pickResult.pickedSprite;
  12939. switch (evt.button) {
  12940. case 0:
  12941. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12942. break;
  12943. case 1:
  12944. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12945. break;
  12946. case 2:
  12947. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12948. break;
  12949. }
  12950. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12951. }
  12952. }
  12953. }
  12954. };
  12955. this._onPointerUp = function (evt) {
  12956. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12957. return;
  12958. }
  12959. var predicate = null;
  12960. _this._updatePointerPosition(evt);
  12961. if (!_this.onPointerUp && !_this.onPointerPick) {
  12962. predicate = function (mesh) {
  12963. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12964. };
  12965. }
  12966. // Meshes
  12967. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, predicate, false, _this.cameraToUseForPointers);
  12968. if (pickResult.hit && pickResult.pickedMesh) {
  12969. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  12970. _this.onPointerPick(evt, pickResult);
  12971. }
  12972. if (pickResult.pickedMesh.actionManager) {
  12973. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12974. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12975. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12976. }
  12977. }
  12978. }
  12979. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  12980. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  12981. }
  12982. if (_this.onPointerUp) {
  12983. _this.onPointerUp(evt, pickResult);
  12984. }
  12985. _this._startingPointerTime = 0;
  12986. // Sprites
  12987. if (_this.spriteManagers.length > 0) {
  12988. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12989. if (pickResult.hit && pickResult.pickedSprite) {
  12990. if (pickResult.pickedSprite.actionManager) {
  12991. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12992. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12993. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12994. }
  12995. }
  12996. }
  12997. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  12998. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  12999. }
  13000. }
  13001. };
  13002. this._onKeyDown = function (evt) {
  13003. if (_this.actionManager) {
  13004. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13005. }
  13006. };
  13007. this._onKeyUp = function (evt) {
  13008. if (_this.actionManager) {
  13009. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13010. }
  13011. };
  13012. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13013. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13014. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13015. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13016. // Wheel
  13017. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13018. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13019. BABYLON.Tools.RegisterTopRootEvents([
  13020. { name: "keydown", handler: this._onKeyDown },
  13021. { name: "keyup", handler: this._onKeyUp }
  13022. ]);
  13023. };
  13024. Scene.prototype.detachControl = function () {
  13025. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13026. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13027. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13028. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13029. // Wheel
  13030. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13031. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13032. BABYLON.Tools.UnregisterTopRootEvents([
  13033. { name: "keydown", handler: this._onKeyDown },
  13034. { name: "keyup", handler: this._onKeyUp }
  13035. ]);
  13036. };
  13037. // Ready
  13038. Scene.prototype.isReady = function () {
  13039. if (this._pendingData.length > 0) {
  13040. return false;
  13041. }
  13042. var index;
  13043. for (index = 0; index < this._geometries.length; index++) {
  13044. var geometry = this._geometries[index];
  13045. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13046. return false;
  13047. }
  13048. }
  13049. for (index = 0; index < this.meshes.length; index++) {
  13050. var mesh = this.meshes[index];
  13051. if (!mesh.isReady()) {
  13052. return false;
  13053. }
  13054. var mat = mesh.material;
  13055. if (mat) {
  13056. if (!mat.isReady(mesh)) {
  13057. return false;
  13058. }
  13059. }
  13060. }
  13061. return true;
  13062. };
  13063. Scene.prototype.resetCachedMaterial = function () {
  13064. this._cachedMaterial = null;
  13065. };
  13066. Scene.prototype.registerBeforeRender = function (func) {
  13067. this._onBeforeRenderCallbacks.push(func);
  13068. };
  13069. Scene.prototype.unregisterBeforeRender = function (func) {
  13070. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13071. if (index > -1) {
  13072. this._onBeforeRenderCallbacks.splice(index, 1);
  13073. }
  13074. };
  13075. Scene.prototype.registerAfterRender = function (func) {
  13076. this._onAfterRenderCallbacks.push(func);
  13077. };
  13078. Scene.prototype.unregisterAfterRender = function (func) {
  13079. var index = this._onAfterRenderCallbacks.indexOf(func);
  13080. if (index > -1) {
  13081. this._onAfterRenderCallbacks.splice(index, 1);
  13082. }
  13083. };
  13084. Scene.prototype._addPendingData = function (data) {
  13085. this._pendingData.push(data);
  13086. };
  13087. Scene.prototype._removePendingData = function (data) {
  13088. var index = this._pendingData.indexOf(data);
  13089. if (index !== -1) {
  13090. this._pendingData.splice(index, 1);
  13091. }
  13092. };
  13093. Scene.prototype.getWaitingItemsCount = function () {
  13094. return this._pendingData.length;
  13095. };
  13096. /**
  13097. * Registers a function to be executed when the scene is ready.
  13098. * @param {Function} func - the function to be executed.
  13099. */
  13100. Scene.prototype.executeWhenReady = function (func) {
  13101. var _this = this;
  13102. this._onReadyCallbacks.push(func);
  13103. if (this._executeWhenReadyTimeoutId !== -1) {
  13104. return;
  13105. }
  13106. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13107. _this._checkIsReady();
  13108. }, 150);
  13109. };
  13110. Scene.prototype._checkIsReady = function () {
  13111. var _this = this;
  13112. if (this.isReady()) {
  13113. this._onReadyCallbacks.forEach(function (func) {
  13114. func();
  13115. });
  13116. this._onReadyCallbacks = [];
  13117. this._executeWhenReadyTimeoutId = -1;
  13118. return;
  13119. }
  13120. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13121. _this._checkIsReady();
  13122. }, 150);
  13123. };
  13124. // Animations
  13125. /**
  13126. * Will start the animation sequence of a given target
  13127. * @param target - the target
  13128. * @param {number} from - from which frame should animation start
  13129. * @param {number} to - till which frame should animation run.
  13130. * @param {boolean} [loop] - should the animation loop
  13131. * @param {number} [speedRatio] - the speed in which to run the animation
  13132. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13133. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13134. * @return {BABYLON.Animatable} the animatable object created for this animation
  13135. * @see BABYLON.Animatable
  13136. * @see http://doc.babylonjs.com/page.php?p=22081
  13137. */
  13138. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13139. if (speedRatio === void 0) { speedRatio = 1.0; }
  13140. this.stopAnimation(target);
  13141. if (!animatable) {
  13142. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13143. }
  13144. // Local animations
  13145. if (target.animations) {
  13146. animatable.appendAnimations(target, target.animations);
  13147. }
  13148. // Children animations
  13149. if (target.getAnimatables) {
  13150. var animatables = target.getAnimatables();
  13151. for (var index = 0; index < animatables.length; index++) {
  13152. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13153. }
  13154. }
  13155. return animatable;
  13156. };
  13157. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13158. if (speedRatio === undefined) {
  13159. speedRatio = 1.0;
  13160. }
  13161. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13162. return animatable;
  13163. };
  13164. Scene.prototype.getAnimatableByTarget = function (target) {
  13165. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13166. if (this._activeAnimatables[index].target === target) {
  13167. return this._activeAnimatables[index];
  13168. }
  13169. }
  13170. return null;
  13171. };
  13172. Object.defineProperty(Scene.prototype, "Animatables", {
  13173. get: function () {
  13174. return this._activeAnimatables;
  13175. },
  13176. enumerable: true,
  13177. configurable: true
  13178. });
  13179. /**
  13180. * Will stop the animation of the given target
  13181. * @param target - the target
  13182. * @see beginAnimation
  13183. */
  13184. Scene.prototype.stopAnimation = function (target) {
  13185. var animatable = this.getAnimatableByTarget(target);
  13186. if (animatable) {
  13187. animatable.stop();
  13188. }
  13189. };
  13190. Scene.prototype._animate = function () {
  13191. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13192. return;
  13193. }
  13194. if (!this._animationStartDate) {
  13195. if (this._pendingData.length > 0) {
  13196. return;
  13197. }
  13198. this._animationStartDate = BABYLON.Tools.Now;
  13199. }
  13200. // Getting time
  13201. var now = BABYLON.Tools.Now;
  13202. var delay = now - this._animationStartDate;
  13203. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13204. this._activeAnimatables[index]._animate(delay);
  13205. }
  13206. };
  13207. // Matrix
  13208. Scene.prototype.getViewMatrix = function () {
  13209. return this._viewMatrix;
  13210. };
  13211. Scene.prototype.getProjectionMatrix = function () {
  13212. return this._projectionMatrix;
  13213. };
  13214. Scene.prototype.getTransformMatrix = function () {
  13215. return this._transformMatrix;
  13216. };
  13217. Scene.prototype.setTransformMatrix = function (view, projection) {
  13218. this._viewMatrix = view;
  13219. this._projectionMatrix = projection;
  13220. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13221. };
  13222. // Methods
  13223. Scene.prototype.addMesh = function (newMesh) {
  13224. newMesh.uniqueId = this._uniqueIdCounter++;
  13225. var position = this.meshes.push(newMesh);
  13226. //notify the collision coordinator
  13227. this.collisionCoordinator.onMeshAdded(newMesh);
  13228. if (this.onNewMeshAdded) {
  13229. this.onNewMeshAdded(newMesh, position, this);
  13230. }
  13231. };
  13232. Scene.prototype.removeMesh = function (toRemove) {
  13233. var index = this.meshes.indexOf(toRemove);
  13234. if (index !== -1) {
  13235. // Remove from the scene if mesh found
  13236. this.meshes.splice(index, 1);
  13237. }
  13238. //notify the collision coordinator
  13239. this.collisionCoordinator.onMeshRemoved(toRemove);
  13240. if (this.onMeshRemoved) {
  13241. this.onMeshRemoved(toRemove);
  13242. }
  13243. return index;
  13244. };
  13245. Scene.prototype.removeSkeleton = function (toRemove) {
  13246. var index = this.skeletons.indexOf(toRemove);
  13247. if (index !== -1) {
  13248. // Remove from the scene if mesh found
  13249. this.skeletons.splice(index, 1);
  13250. }
  13251. return index;
  13252. };
  13253. Scene.prototype.removeLight = function (toRemove) {
  13254. var index = this.lights.indexOf(toRemove);
  13255. if (index !== -1) {
  13256. // Remove from the scene if mesh found
  13257. this.lights.splice(index, 1);
  13258. }
  13259. if (this.onLightRemoved) {
  13260. this.onLightRemoved(toRemove);
  13261. }
  13262. return index;
  13263. };
  13264. Scene.prototype.removeCamera = function (toRemove) {
  13265. var index = this.cameras.indexOf(toRemove);
  13266. if (index !== -1) {
  13267. // Remove from the scene if mesh found
  13268. this.cameras.splice(index, 1);
  13269. }
  13270. // Remove from activeCameras
  13271. var index2 = this.activeCameras.indexOf(toRemove);
  13272. if (index2 !== -1) {
  13273. // Remove from the scene if mesh found
  13274. this.activeCameras.splice(index2, 1);
  13275. }
  13276. // Reset the activeCamera
  13277. if (this.activeCamera === toRemove) {
  13278. if (this.cameras.length > 0) {
  13279. this.activeCamera = this.cameras[0];
  13280. }
  13281. else {
  13282. this.activeCamera = null;
  13283. }
  13284. }
  13285. if (this.onCameraRemoved) {
  13286. this.onCameraRemoved(toRemove);
  13287. }
  13288. return index;
  13289. };
  13290. Scene.prototype.addLight = function (newLight) {
  13291. newLight.uniqueId = this._uniqueIdCounter++;
  13292. var position = this.lights.push(newLight);
  13293. if (this.onNewLightAdded) {
  13294. this.onNewLightAdded(newLight, position, this);
  13295. }
  13296. };
  13297. Scene.prototype.addCamera = function (newCamera) {
  13298. newCamera.uniqueId = this._uniqueIdCounter++;
  13299. var position = this.cameras.push(newCamera);
  13300. if (this.onNewCameraAdded) {
  13301. this.onNewCameraAdded(newCamera, position, this);
  13302. }
  13303. };
  13304. /**
  13305. * Switch active camera
  13306. * @param {Camera} newCamera - new active camera
  13307. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13308. */
  13309. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13310. if (attachControl === void 0) { attachControl = true; }
  13311. var canvas = this._engine.getRenderingCanvas();
  13312. this.activeCamera.detachControl(canvas);
  13313. this.activeCamera = newCamera;
  13314. if (attachControl) {
  13315. newCamera.attachControl(canvas);
  13316. }
  13317. };
  13318. /**
  13319. * sets the active camera of the scene using its ID
  13320. * @param {string} id - the camera's ID
  13321. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13322. * @see activeCamera
  13323. */
  13324. Scene.prototype.setActiveCameraByID = function (id) {
  13325. var camera = this.getCameraByID(id);
  13326. if (camera) {
  13327. this.activeCamera = camera;
  13328. return camera;
  13329. }
  13330. return null;
  13331. };
  13332. /**
  13333. * sets the active camera of the scene using its name
  13334. * @param {string} name - the camera's name
  13335. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13336. * @see activeCamera
  13337. */
  13338. Scene.prototype.setActiveCameraByName = function (name) {
  13339. var camera = this.getCameraByName(name);
  13340. if (camera) {
  13341. this.activeCamera = camera;
  13342. return camera;
  13343. }
  13344. return null;
  13345. };
  13346. /**
  13347. * get a material using its id
  13348. * @param {string} the material's ID
  13349. * @return {BABYLON.Material|null} the material or null if none found.
  13350. */
  13351. Scene.prototype.getMaterialByID = function (id) {
  13352. for (var index = 0; index < this.materials.length; index++) {
  13353. if (this.materials[index].id === id) {
  13354. return this.materials[index];
  13355. }
  13356. }
  13357. return null;
  13358. };
  13359. /**
  13360. * get a material using its name
  13361. * @param {string} the material's name
  13362. * @return {BABYLON.Material|null} the material or null if none found.
  13363. */
  13364. Scene.prototype.getMaterialByName = function (name) {
  13365. for (var index = 0; index < this.materials.length; index++) {
  13366. if (this.materials[index].name === name) {
  13367. return this.materials[index];
  13368. }
  13369. }
  13370. return null;
  13371. };
  13372. Scene.prototype.getLensFlareSystemByName = function (name) {
  13373. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13374. if (this.lensFlareSystems[index].name === name) {
  13375. return this.lensFlareSystems[index];
  13376. }
  13377. }
  13378. return null;
  13379. };
  13380. Scene.prototype.getCameraByID = function (id) {
  13381. for (var index = 0; index < this.cameras.length; index++) {
  13382. if (this.cameras[index].id === id) {
  13383. return this.cameras[index];
  13384. }
  13385. }
  13386. return null;
  13387. };
  13388. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13389. for (var index = 0; index < this.cameras.length; index++) {
  13390. if (this.cameras[index].uniqueId === uniqueId) {
  13391. return this.cameras[index];
  13392. }
  13393. }
  13394. return null;
  13395. };
  13396. /**
  13397. * get a camera using its name
  13398. * @param {string} the camera's name
  13399. * @return {BABYLON.Camera|null} the camera or null if none found.
  13400. */
  13401. Scene.prototype.getCameraByName = function (name) {
  13402. for (var index = 0; index < this.cameras.length; index++) {
  13403. if (this.cameras[index].name === name) {
  13404. return this.cameras[index];
  13405. }
  13406. }
  13407. return null;
  13408. };
  13409. /**
  13410. * get a bone using its id
  13411. * @param {string} the bone's id
  13412. * @return {BABYLON.Bone|null} the bone or null if not found
  13413. */
  13414. Scene.prototype.getBoneByID = function (id) {
  13415. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13416. var skeleton = this.skeletons[skeletonIndex];
  13417. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13418. if (skeleton.bones[boneIndex].id === id) {
  13419. return skeleton.bones[boneIndex];
  13420. }
  13421. }
  13422. }
  13423. return null;
  13424. };
  13425. /**
  13426. * get a bone using its id
  13427. * @param {string} the bone's name
  13428. * @return {BABYLON.Bone|null} the bone or null if not found
  13429. */
  13430. Scene.prototype.getBoneByName = function (name) {
  13431. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13432. var skeleton = this.skeletons[skeletonIndex];
  13433. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13434. if (skeleton.bones[boneIndex].name === name) {
  13435. return skeleton.bones[boneIndex];
  13436. }
  13437. }
  13438. }
  13439. return null;
  13440. };
  13441. /**
  13442. * get a light node using its name
  13443. * @param {string} the light's name
  13444. * @return {BABYLON.Light|null} the light or null if none found.
  13445. */
  13446. Scene.prototype.getLightByName = function (name) {
  13447. for (var index = 0; index < this.lights.length; index++) {
  13448. if (this.lights[index].name === name) {
  13449. return this.lights[index];
  13450. }
  13451. }
  13452. return null;
  13453. };
  13454. /**
  13455. * get a light node using its ID
  13456. * @param {string} the light's id
  13457. * @return {BABYLON.Light|null} the light or null if none found.
  13458. */
  13459. Scene.prototype.getLightByID = function (id) {
  13460. for (var index = 0; index < this.lights.length; index++) {
  13461. if (this.lights[index].id === id) {
  13462. return this.lights[index];
  13463. }
  13464. }
  13465. return null;
  13466. };
  13467. /**
  13468. * get a light node using its scene-generated unique ID
  13469. * @param {number} the light's unique id
  13470. * @return {BABYLON.Light|null} the light or null if none found.
  13471. */
  13472. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13473. for (var index = 0; index < this.lights.length; index++) {
  13474. if (this.lights[index].uniqueId === uniqueId) {
  13475. return this.lights[index];
  13476. }
  13477. }
  13478. return null;
  13479. };
  13480. /**
  13481. * get a particle system by id
  13482. * @param id {number} the particle system id
  13483. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13484. */
  13485. Scene.prototype.getParticleSystemByID = function (id) {
  13486. for (var index = 0; index < this.particleSystems.length; index++) {
  13487. if (this.particleSystems[index].id === id) {
  13488. return this.particleSystems[index];
  13489. }
  13490. }
  13491. return null;
  13492. };
  13493. /**
  13494. * get a geometry using its ID
  13495. * @param {string} the geometry's id
  13496. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13497. */
  13498. Scene.prototype.getGeometryByID = function (id) {
  13499. for (var index = 0; index < this._geometries.length; index++) {
  13500. if (this._geometries[index].id === id) {
  13501. return this._geometries[index];
  13502. }
  13503. }
  13504. return null;
  13505. };
  13506. /**
  13507. * add a new geometry to this scene.
  13508. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13509. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13510. * @return {boolean} was the geometry added or not
  13511. */
  13512. Scene.prototype.pushGeometry = function (geometry, force) {
  13513. if (!force && this.getGeometryByID(geometry.id)) {
  13514. return false;
  13515. }
  13516. this._geometries.push(geometry);
  13517. //notify the collision coordinator
  13518. this.collisionCoordinator.onGeometryAdded(geometry);
  13519. if (this.onGeometryAdded) {
  13520. this.onGeometryAdded(geometry);
  13521. }
  13522. return true;
  13523. };
  13524. /**
  13525. * Removes an existing geometry
  13526. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13527. * @return {boolean} was the geometry removed or not
  13528. */
  13529. Scene.prototype.removeGeometry = function (geometry) {
  13530. var index = this._geometries.indexOf(geometry);
  13531. if (index > -1) {
  13532. this._geometries.splice(index, 1);
  13533. //notify the collision coordinator
  13534. this.collisionCoordinator.onGeometryDeleted(geometry);
  13535. if (this.onGeometryRemoved) {
  13536. this.onGeometryRemoved(geometry);
  13537. }
  13538. return true;
  13539. }
  13540. return false;
  13541. };
  13542. Scene.prototype.getGeometries = function () {
  13543. return this._geometries;
  13544. };
  13545. /**
  13546. * Get the first added mesh found of a given ID
  13547. * @param {string} id - the id to search for
  13548. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13549. */
  13550. Scene.prototype.getMeshByID = function (id) {
  13551. for (var index = 0; index < this.meshes.length; index++) {
  13552. if (this.meshes[index].id === id) {
  13553. return this.meshes[index];
  13554. }
  13555. }
  13556. return null;
  13557. };
  13558. /**
  13559. * Get a mesh with its auto-generated unique id
  13560. * @param {number} uniqueId - the unique id to search for
  13561. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13562. */
  13563. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13564. for (var index = 0; index < this.meshes.length; index++) {
  13565. if (this.meshes[index].uniqueId === uniqueId) {
  13566. return this.meshes[index];
  13567. }
  13568. }
  13569. return null;
  13570. };
  13571. /**
  13572. * Get a the last added mesh found of a given ID
  13573. * @param {string} id - the id to search for
  13574. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13575. */
  13576. Scene.prototype.getLastMeshByID = function (id) {
  13577. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13578. if (this.meshes[index].id === id) {
  13579. return this.meshes[index];
  13580. }
  13581. }
  13582. return null;
  13583. };
  13584. /**
  13585. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13586. * @param {string} id - the id to search for
  13587. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13588. */
  13589. Scene.prototype.getLastEntryByID = function (id) {
  13590. var index;
  13591. for (index = this.meshes.length - 1; index >= 0; index--) {
  13592. if (this.meshes[index].id === id) {
  13593. return this.meshes[index];
  13594. }
  13595. }
  13596. for (index = this.cameras.length - 1; index >= 0; index--) {
  13597. if (this.cameras[index].id === id) {
  13598. return this.cameras[index];
  13599. }
  13600. }
  13601. for (index = this.lights.length - 1; index >= 0; index--) {
  13602. if (this.lights[index].id === id) {
  13603. return this.lights[index];
  13604. }
  13605. }
  13606. return null;
  13607. };
  13608. Scene.prototype.getNodeByID = function (id) {
  13609. var mesh = this.getMeshByID(id);
  13610. if (mesh) {
  13611. return mesh;
  13612. }
  13613. var light = this.getLightByID(id);
  13614. if (light) {
  13615. return light;
  13616. }
  13617. var camera = this.getCameraByID(id);
  13618. if (camera) {
  13619. return camera;
  13620. }
  13621. var bone = this.getBoneByID(id);
  13622. return bone;
  13623. };
  13624. Scene.prototype.getNodeByName = function (name) {
  13625. var mesh = this.getMeshByName(name);
  13626. if (mesh) {
  13627. return mesh;
  13628. }
  13629. var light = this.getLightByName(name);
  13630. if (light) {
  13631. return light;
  13632. }
  13633. var camera = this.getCameraByName(name);
  13634. if (camera) {
  13635. return camera;
  13636. }
  13637. var bone = this.getBoneByName(name);
  13638. return bone;
  13639. };
  13640. Scene.prototype.getMeshByName = function (name) {
  13641. for (var index = 0; index < this.meshes.length; index++) {
  13642. if (this.meshes[index].name === name) {
  13643. return this.meshes[index];
  13644. }
  13645. }
  13646. return null;
  13647. };
  13648. Scene.prototype.getSoundByName = function (name) {
  13649. var index;
  13650. if (BABYLON.AudioEngine) {
  13651. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13652. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13653. return this.mainSoundTrack.soundCollection[index];
  13654. }
  13655. }
  13656. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13657. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13658. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13659. return this.soundTracks[sdIndex].soundCollection[index];
  13660. }
  13661. }
  13662. }
  13663. }
  13664. return null;
  13665. };
  13666. Scene.prototype.getLastSkeletonByID = function (id) {
  13667. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13668. if (this.skeletons[index].id === id) {
  13669. return this.skeletons[index];
  13670. }
  13671. }
  13672. return null;
  13673. };
  13674. Scene.prototype.getSkeletonById = function (id) {
  13675. for (var index = 0; index < this.skeletons.length; index++) {
  13676. if (this.skeletons[index].id === id) {
  13677. return this.skeletons[index];
  13678. }
  13679. }
  13680. return null;
  13681. };
  13682. Scene.prototype.getSkeletonByName = function (name) {
  13683. for (var index = 0; index < this.skeletons.length; index++) {
  13684. if (this.skeletons[index].name === name) {
  13685. return this.skeletons[index];
  13686. }
  13687. }
  13688. return null;
  13689. };
  13690. Scene.prototype.isActiveMesh = function (mesh) {
  13691. return (this._activeMeshes.indexOf(mesh) !== -1);
  13692. };
  13693. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13694. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13695. var material = subMesh.getMaterial();
  13696. if (mesh.showSubMeshesBoundingBox) {
  13697. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13698. }
  13699. if (material) {
  13700. // Render targets
  13701. if (material.getRenderTargetTextures) {
  13702. if (this._processedMaterials.indexOf(material) === -1) {
  13703. this._processedMaterials.push(material);
  13704. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13705. }
  13706. }
  13707. // Dispatch
  13708. this._activeIndices += subMesh.indexCount;
  13709. this._renderingManager.dispatch(subMesh);
  13710. }
  13711. }
  13712. };
  13713. Scene.prototype._evaluateActiveMeshes = function () {
  13714. this.activeCamera._activeMeshes.reset();
  13715. this._activeMeshes.reset();
  13716. this._renderingManager.reset();
  13717. this._processedMaterials.reset();
  13718. this._activeParticleSystems.reset();
  13719. this._activeSkeletons.reset();
  13720. this._softwareSkinnedMeshes.reset();
  13721. this._boundingBoxRenderer.reset();
  13722. this._edgesRenderers.reset();
  13723. if (!this._frustumPlanes) {
  13724. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13725. }
  13726. else {
  13727. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13728. }
  13729. // Meshes
  13730. var meshes;
  13731. var len;
  13732. if (this._selectionOctree) {
  13733. var selection = this._selectionOctree.select(this._frustumPlanes);
  13734. meshes = selection.data;
  13735. len = selection.length;
  13736. }
  13737. else {
  13738. len = this.meshes.length;
  13739. meshes = this.meshes;
  13740. }
  13741. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13742. var mesh = meshes[meshIndex];
  13743. if (mesh.isBlocked) {
  13744. continue;
  13745. }
  13746. this._totalVertices += mesh.getTotalVertices();
  13747. if (!mesh.isReady() || !mesh.isEnabled()) {
  13748. continue;
  13749. }
  13750. mesh.computeWorldMatrix();
  13751. // Intersections
  13752. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13753. this._meshesForIntersections.pushNoDuplicate(mesh);
  13754. }
  13755. // Switch to current LOD
  13756. var meshLOD = mesh.getLOD(this.activeCamera);
  13757. if (!meshLOD) {
  13758. continue;
  13759. }
  13760. mesh._preActivate();
  13761. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13762. this._activeMeshes.push(mesh);
  13763. this.activeCamera._activeMeshes.push(mesh);
  13764. mesh._activate(this._renderId);
  13765. this._activeMesh(meshLOD);
  13766. }
  13767. }
  13768. // Particle systems
  13769. var beforeParticlesDate = BABYLON.Tools.Now;
  13770. if (this.particlesEnabled) {
  13771. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13772. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13773. var particleSystem = this.particleSystems[particleIndex];
  13774. if (!particleSystem.isStarted()) {
  13775. continue;
  13776. }
  13777. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13778. this._activeParticleSystems.push(particleSystem);
  13779. particleSystem.animate();
  13780. }
  13781. }
  13782. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13783. }
  13784. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13785. };
  13786. Scene.prototype._activeMesh = function (mesh) {
  13787. if (mesh.skeleton && this.skeletonsEnabled) {
  13788. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13789. if (!mesh.computeBonesUsingShaders) {
  13790. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13791. }
  13792. }
  13793. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13794. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13795. }
  13796. if (mesh._edgesRenderer) {
  13797. this._edgesRenderers.push(mesh._edgesRenderer);
  13798. }
  13799. if (mesh && mesh.subMeshes) {
  13800. // Submeshes Octrees
  13801. var len;
  13802. var subMeshes;
  13803. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13804. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13805. len = intersections.length;
  13806. subMeshes = intersections.data;
  13807. }
  13808. else {
  13809. subMeshes = mesh.subMeshes;
  13810. len = subMeshes.length;
  13811. }
  13812. for (var subIndex = 0; subIndex < len; subIndex++) {
  13813. var subMesh = subMeshes[subIndex];
  13814. this._evaluateSubMesh(subMesh, mesh);
  13815. }
  13816. }
  13817. };
  13818. Scene.prototype.updateTransformMatrix = function (force) {
  13819. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13820. };
  13821. Scene.prototype._renderForCamera = function (camera) {
  13822. var engine = this._engine;
  13823. this.activeCamera = camera;
  13824. if (!this.activeCamera)
  13825. throw new Error("Active camera not set");
  13826. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13827. // Viewport
  13828. engine.setViewport(this.activeCamera.viewport);
  13829. // Camera
  13830. this.resetCachedMaterial();
  13831. this._renderId++;
  13832. this.updateTransformMatrix();
  13833. if (this.beforeCameraRender) {
  13834. this.beforeCameraRender(this.activeCamera);
  13835. }
  13836. // Meshes
  13837. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13838. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13839. this._evaluateActiveMeshes();
  13840. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13841. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13842. // Skeletons
  13843. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13844. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13845. skeleton.prepare();
  13846. }
  13847. // Software skinning
  13848. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13849. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13850. mesh.applySkeleton(mesh.skeleton);
  13851. }
  13852. // Render targets
  13853. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13854. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13855. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13856. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13857. var renderTarget = this._renderTargets.data[renderIndex];
  13858. if (renderTarget._shouldRender()) {
  13859. this._renderId++;
  13860. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13861. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13862. }
  13863. }
  13864. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13865. this._renderId++;
  13866. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13867. }
  13868. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13869. // Prepare Frame
  13870. this.postProcessManager._prepareFrame();
  13871. var beforeRenderDate = BABYLON.Tools.Now;
  13872. // Backgrounds
  13873. var layerIndex;
  13874. var layer;
  13875. if (this.layers.length) {
  13876. engine.setDepthBuffer(false);
  13877. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13878. layer = this.layers[layerIndex];
  13879. if (layer.isBackground) {
  13880. layer.render();
  13881. }
  13882. }
  13883. engine.setDepthBuffer(true);
  13884. }
  13885. // Render
  13886. BABYLON.Tools.StartPerformanceCounter("Main render");
  13887. this._renderingManager.render(null, null, true, true);
  13888. BABYLON.Tools.EndPerformanceCounter("Main render");
  13889. // Bounding boxes
  13890. this._boundingBoxRenderer.render();
  13891. // Edges
  13892. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13893. this._edgesRenderers.data[edgesRendererIndex].render();
  13894. }
  13895. // Lens flares
  13896. if (this.lensFlaresEnabled) {
  13897. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13898. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13899. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13900. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13901. lensFlareSystem.render();
  13902. }
  13903. }
  13904. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13905. }
  13906. // Foregrounds
  13907. if (this.layers.length) {
  13908. engine.setDepthBuffer(false);
  13909. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13910. layer = this.layers[layerIndex];
  13911. if (!layer.isBackground) {
  13912. layer.render();
  13913. }
  13914. }
  13915. engine.setDepthBuffer(true);
  13916. }
  13917. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13918. // Finalize frame
  13919. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13920. // Update camera
  13921. this.activeCamera._updateFromScene();
  13922. // Reset some special arrays
  13923. this._renderTargets.reset();
  13924. if (this.afterCameraRender) {
  13925. this.afterCameraRender(this.activeCamera);
  13926. }
  13927. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13928. };
  13929. Scene.prototype._processSubCameras = function (camera) {
  13930. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13931. this._renderForCamera(camera);
  13932. return;
  13933. }
  13934. // rig cameras
  13935. for (var index = 0; index < camera._rigCameras.length; index++) {
  13936. this._renderForCamera(camera._rigCameras[index]);
  13937. }
  13938. this.activeCamera = camera;
  13939. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13940. // Update camera
  13941. this.activeCamera._updateFromScene();
  13942. };
  13943. Scene.prototype._checkIntersections = function () {
  13944. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13945. var sourceMesh = this._meshesForIntersections.data[index];
  13946. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13947. var action = sourceMesh.actionManager.actions[actionIndex];
  13948. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13949. var parameters = action.getTriggerParameter();
  13950. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13951. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13952. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13953. if (areIntersecting && currentIntersectionInProgress === -1) {
  13954. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13955. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13956. sourceMesh._intersectionsInProgress.push(otherMesh);
  13957. }
  13958. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13959. sourceMesh._intersectionsInProgress.push(otherMesh);
  13960. }
  13961. }
  13962. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13963. //They intersected, and now they don't.
  13964. //is this trigger an exit trigger? execute an event.
  13965. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13966. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13967. }
  13968. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13969. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13970. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13971. }
  13972. }
  13973. }
  13974. }
  13975. }
  13976. };
  13977. Scene.prototype.render = function () {
  13978. var startDate = BABYLON.Tools.Now;
  13979. this._particlesDuration = 0;
  13980. this._spritesDuration = 0;
  13981. this._activeParticles = 0;
  13982. this._renderDuration = 0;
  13983. this._renderTargetsDuration = 0;
  13984. this._evaluateActiveMeshesDuration = 0;
  13985. this._totalVertices = 0;
  13986. this._activeIndices = 0;
  13987. this._activeBones = 0;
  13988. this.getEngine().resetDrawCalls();
  13989. this._meshesForIntersections.reset();
  13990. this.resetCachedMaterial();
  13991. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13992. // Actions
  13993. if (this.actionManager) {
  13994. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13995. }
  13996. //Simplification Queue
  13997. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13998. this.simplificationQueue.executeNext();
  13999. }
  14000. // Animations
  14001. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  14002. this._animationRatio = deltaTime * (60.0 / 1000.0);
  14003. this._animate();
  14004. // Physics
  14005. if (this._physicsEngine) {
  14006. BABYLON.Tools.StartPerformanceCounter("Physics");
  14007. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  14008. BABYLON.Tools.EndPerformanceCounter("Physics");
  14009. }
  14010. // Before render
  14011. if (this.beforeRender) {
  14012. this.beforeRender();
  14013. }
  14014. var callbackIndex;
  14015. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14016. this._onBeforeRenderCallbacks[callbackIndex]();
  14017. }
  14018. // Customs render targets
  14019. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14020. var engine = this.getEngine();
  14021. var currentActiveCamera = this.activeCamera;
  14022. if (this.renderTargetsEnabled) {
  14023. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14024. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  14025. var renderTarget = this.customRenderTargets[customIndex];
  14026. if (renderTarget._shouldRender()) {
  14027. this._renderId++;
  14028. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14029. if (!this.activeCamera)
  14030. throw new Error("Active camera not set");
  14031. // Viewport
  14032. engine.setViewport(this.activeCamera.viewport);
  14033. // Camera
  14034. this.updateTransformMatrix();
  14035. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14036. }
  14037. }
  14038. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14039. this._renderId++;
  14040. }
  14041. if (this.customRenderTargets.length > 0) {
  14042. engine.restoreDefaultFramebuffer();
  14043. }
  14044. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14045. this.activeCamera = currentActiveCamera;
  14046. // Procedural textures
  14047. if (this.proceduralTexturesEnabled) {
  14048. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14049. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14050. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14051. if (proceduralTexture._shouldRender()) {
  14052. proceduralTexture.render();
  14053. }
  14054. }
  14055. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14056. }
  14057. // Clear
  14058. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14059. // Shadows
  14060. if (this.shadowsEnabled) {
  14061. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14062. var light = this.lights[lightIndex];
  14063. var shadowGenerator = light.getShadowGenerator();
  14064. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14065. this._renderTargets.push(shadowGenerator.getShadowMap());
  14066. }
  14067. }
  14068. }
  14069. // Depth renderer
  14070. if (this._depthRenderer) {
  14071. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14072. }
  14073. // RenderPipeline
  14074. this.postProcessRenderPipelineManager.update();
  14075. // Multi-cameras?
  14076. if (this.activeCameras.length > 0) {
  14077. var currentRenderId = this._renderId;
  14078. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14079. this._renderId = currentRenderId;
  14080. if (cameraIndex > 0) {
  14081. this._engine.clear(0, false, true);
  14082. }
  14083. this._processSubCameras(this.activeCameras[cameraIndex]);
  14084. }
  14085. }
  14086. else {
  14087. if (!this.activeCamera) {
  14088. throw new Error("No camera defined");
  14089. }
  14090. this._processSubCameras(this.activeCamera);
  14091. }
  14092. // Intersection checks
  14093. this._checkIntersections();
  14094. // Update the audio listener attached to the camera
  14095. if (BABYLON.AudioEngine) {
  14096. this._updateAudioParameters();
  14097. }
  14098. // After render
  14099. if (this.afterRender) {
  14100. this.afterRender();
  14101. }
  14102. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14103. this._onAfterRenderCallbacks[callbackIndex]();
  14104. }
  14105. // Cleaning
  14106. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14107. this._toBeDisposed.data[index].dispose();
  14108. this._toBeDisposed[index] = null;
  14109. }
  14110. this._toBeDisposed.reset();
  14111. if (this.dumpNextRenderTargets) {
  14112. this.dumpNextRenderTargets = false;
  14113. }
  14114. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14115. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14116. };
  14117. Scene.prototype._updateAudioParameters = function () {
  14118. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14119. return;
  14120. }
  14121. var listeningCamera;
  14122. var audioEngine = BABYLON.Engine.audioEngine;
  14123. if (this.activeCameras.length > 0) {
  14124. listeningCamera = this.activeCameras[0];
  14125. }
  14126. else {
  14127. listeningCamera = this.activeCamera;
  14128. }
  14129. if (listeningCamera && audioEngine.canUseWebAudio) {
  14130. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14131. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14132. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14133. cameraDirection.normalize();
  14134. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14135. var i;
  14136. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14137. var sound = this.mainSoundTrack.soundCollection[i];
  14138. if (sound.useCustomAttenuation) {
  14139. sound.updateDistanceFromListener();
  14140. }
  14141. }
  14142. for (i = 0; i < this.soundTracks.length; i++) {
  14143. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14144. sound = this.soundTracks[i].soundCollection[j];
  14145. if (sound.useCustomAttenuation) {
  14146. sound.updateDistanceFromListener();
  14147. }
  14148. }
  14149. }
  14150. }
  14151. };
  14152. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14153. // Audio
  14154. get: function () {
  14155. return this._audioEnabled;
  14156. },
  14157. set: function (value) {
  14158. this._audioEnabled = value;
  14159. if (BABYLON.AudioEngine) {
  14160. if (this._audioEnabled) {
  14161. this._enableAudio();
  14162. }
  14163. else {
  14164. this._disableAudio();
  14165. }
  14166. }
  14167. },
  14168. enumerable: true,
  14169. configurable: true
  14170. });
  14171. Scene.prototype._disableAudio = function () {
  14172. var i;
  14173. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14174. this.mainSoundTrack.soundCollection[i].pause();
  14175. }
  14176. for (i = 0; i < this.soundTracks.length; i++) {
  14177. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14178. this.soundTracks[i].soundCollection[j].pause();
  14179. }
  14180. }
  14181. };
  14182. Scene.prototype._enableAudio = function () {
  14183. var i;
  14184. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14185. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14186. this.mainSoundTrack.soundCollection[i].play();
  14187. }
  14188. }
  14189. for (i = 0; i < this.soundTracks.length; i++) {
  14190. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14191. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14192. this.soundTracks[i].soundCollection[j].play();
  14193. }
  14194. }
  14195. }
  14196. };
  14197. Object.defineProperty(Scene.prototype, "headphone", {
  14198. get: function () {
  14199. return this._headphone;
  14200. },
  14201. set: function (value) {
  14202. this._headphone = value;
  14203. if (BABYLON.AudioEngine) {
  14204. if (this._headphone) {
  14205. this._switchAudioModeForHeadphones();
  14206. }
  14207. else {
  14208. this._switchAudioModeForNormalSpeakers();
  14209. }
  14210. }
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Scene.prototype._switchAudioModeForHeadphones = function () {
  14216. this.mainSoundTrack.switchPanningModelToHRTF();
  14217. for (var i = 0; i < this.soundTracks.length; i++) {
  14218. this.soundTracks[i].switchPanningModelToHRTF();
  14219. }
  14220. };
  14221. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14222. this.mainSoundTrack.switchPanningModelToEqualPower();
  14223. for (var i = 0; i < this.soundTracks.length; i++) {
  14224. this.soundTracks[i].switchPanningModelToEqualPower();
  14225. }
  14226. };
  14227. Scene.prototype.enableDepthRenderer = function () {
  14228. if (this._depthRenderer) {
  14229. return this._depthRenderer;
  14230. }
  14231. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14232. return this._depthRenderer;
  14233. };
  14234. Scene.prototype.disableDepthRenderer = function () {
  14235. if (!this._depthRenderer) {
  14236. return;
  14237. }
  14238. this._depthRenderer.dispose();
  14239. this._depthRenderer = null;
  14240. };
  14241. Scene.prototype.freezeMaterials = function () {
  14242. for (var i = 0; i < this.materials.length; i++) {
  14243. this.materials[i].freeze();
  14244. }
  14245. };
  14246. Scene.prototype.unfreezeMaterials = function () {
  14247. for (var i = 0; i < this.materials.length; i++) {
  14248. this.materials[i].unfreeze();
  14249. }
  14250. };
  14251. Scene.prototype.dispose = function () {
  14252. this.beforeRender = null;
  14253. this.afterRender = null;
  14254. this.skeletons = [];
  14255. this._boundingBoxRenderer.dispose();
  14256. if (this._depthRenderer) {
  14257. this._depthRenderer.dispose();
  14258. }
  14259. // Debug layer
  14260. this.debugLayer.hide();
  14261. // Events
  14262. if (this.onDispose) {
  14263. this.onDispose();
  14264. }
  14265. this._onBeforeRenderCallbacks = [];
  14266. this._onAfterRenderCallbacks = [];
  14267. this.detachControl();
  14268. // Release sounds & sounds tracks
  14269. if (BABYLON.AudioEngine) {
  14270. this.disposeSounds();
  14271. }
  14272. // Detach cameras
  14273. var canvas = this._engine.getRenderingCanvas();
  14274. var index;
  14275. for (index = 0; index < this.cameras.length; index++) {
  14276. this.cameras[index].detachControl(canvas);
  14277. }
  14278. // Release lights
  14279. while (this.lights.length) {
  14280. this.lights[0].dispose();
  14281. }
  14282. // Release meshes
  14283. while (this.meshes.length) {
  14284. this.meshes[0].dispose(true);
  14285. }
  14286. // Release cameras
  14287. while (this.cameras.length) {
  14288. this.cameras[0].dispose();
  14289. }
  14290. // Release materials
  14291. while (this.materials.length) {
  14292. this.materials[0].dispose();
  14293. }
  14294. // Release particles
  14295. while (this.particleSystems.length) {
  14296. this.particleSystems[0].dispose();
  14297. }
  14298. // Release sprites
  14299. while (this.spriteManagers.length) {
  14300. this.spriteManagers[0].dispose();
  14301. }
  14302. // Release layers
  14303. while (this.layers.length) {
  14304. this.layers[0].dispose();
  14305. }
  14306. // Release textures
  14307. while (this.textures.length) {
  14308. this.textures[0].dispose();
  14309. }
  14310. // Post-processes
  14311. this.postProcessManager.dispose();
  14312. // Physics
  14313. if (this._physicsEngine) {
  14314. this.disablePhysicsEngine();
  14315. }
  14316. // Remove from engine
  14317. index = this._engine.scenes.indexOf(this);
  14318. if (index > -1) {
  14319. this._engine.scenes.splice(index, 1);
  14320. }
  14321. this._engine.wipeCaches();
  14322. };
  14323. // Release sounds & sounds tracks
  14324. Scene.prototype.disposeSounds = function () {
  14325. this.mainSoundTrack.dispose();
  14326. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14327. this.soundTracks[scIndex].dispose();
  14328. }
  14329. };
  14330. // Octrees
  14331. Scene.prototype.getWorldExtends = function () {
  14332. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14333. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14334. for (var index = 0; index < this.meshes.length; index++) {
  14335. var mesh = this.meshes[index];
  14336. mesh.computeWorldMatrix(true);
  14337. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14338. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14339. BABYLON.Tools.CheckExtends(minBox, min, max);
  14340. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14341. }
  14342. return {
  14343. min: min,
  14344. max: max
  14345. };
  14346. };
  14347. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14348. if (maxCapacity === void 0) { maxCapacity = 64; }
  14349. if (maxDepth === void 0) { maxDepth = 2; }
  14350. if (!this._selectionOctree) {
  14351. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14352. }
  14353. var worldExtends = this.getWorldExtends();
  14354. // Update octree
  14355. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14356. return this._selectionOctree;
  14357. };
  14358. // Picking
  14359. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14360. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14361. var engine = this._engine;
  14362. if (!camera) {
  14363. if (!this.activeCamera)
  14364. throw new Error("Active camera not set");
  14365. camera = this.activeCamera;
  14366. }
  14367. var cameraViewport = camera.viewport;
  14368. var viewport = cameraViewport.toGlobal(engine);
  14369. // Moving coordinates to local viewport world
  14370. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14371. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14372. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14373. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14374. };
  14375. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14376. var engine = this._engine;
  14377. if (!camera) {
  14378. if (!this.activeCamera)
  14379. throw new Error("Active camera not set");
  14380. camera = this.activeCamera;
  14381. }
  14382. var cameraViewport = camera.viewport;
  14383. var viewport = cameraViewport.toGlobal(engine);
  14384. var identity = BABYLON.Matrix.Identity();
  14385. // Moving coordinates to local viewport world
  14386. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14387. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14388. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14389. };
  14390. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14391. var pickingInfo = null;
  14392. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14393. var mesh = this.meshes[meshIndex];
  14394. if (predicate) {
  14395. if (!predicate(mesh)) {
  14396. continue;
  14397. }
  14398. }
  14399. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14400. continue;
  14401. }
  14402. var world = mesh.getWorldMatrix();
  14403. var ray = rayFunction(world);
  14404. var result = mesh.intersects(ray, fastCheck);
  14405. if (!result || !result.hit)
  14406. continue;
  14407. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14408. continue;
  14409. pickingInfo = result;
  14410. if (fastCheck) {
  14411. break;
  14412. }
  14413. }
  14414. return pickingInfo || new BABYLON.PickingInfo();
  14415. };
  14416. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14417. var pickingInfo = null;
  14418. camera = camera || this.activeCamera;
  14419. if (this.spriteManagers.length > 0) {
  14420. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14421. var spriteManager = this.spriteManagers[spriteIndex];
  14422. if (!spriteManager.isPickable) {
  14423. continue;
  14424. }
  14425. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14426. if (!result || !result.hit)
  14427. continue;
  14428. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14429. continue;
  14430. pickingInfo = result;
  14431. if (fastCheck) {
  14432. break;
  14433. }
  14434. }
  14435. }
  14436. return pickingInfo || new BABYLON.PickingInfo();
  14437. };
  14438. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14439. var _this = this;
  14440. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14441. /// <param name="x">X position on screen</param>
  14442. /// <param name="y">Y position on screen</param>
  14443. /// <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>
  14444. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14445. /// <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>
  14446. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14447. };
  14448. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14449. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14450. /// <param name="x">X position on screen</param>
  14451. /// <param name="y">Y position on screen</param>
  14452. /// <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>
  14453. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14454. /// <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>
  14455. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14456. };
  14457. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14458. var _this = this;
  14459. return this._internalPick(function (world) {
  14460. if (!_this._pickWithRayInverseMatrix) {
  14461. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14462. }
  14463. world.invertToRef(_this._pickWithRayInverseMatrix);
  14464. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14465. }, predicate, fastCheck);
  14466. };
  14467. Scene.prototype.setPointerOverMesh = function (mesh) {
  14468. if (this._pointerOverMesh === mesh) {
  14469. return;
  14470. }
  14471. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14472. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14473. }
  14474. this._pointerOverMesh = mesh;
  14475. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14476. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14477. }
  14478. };
  14479. Scene.prototype.getPointerOverMesh = function () {
  14480. return this._pointerOverMesh;
  14481. };
  14482. Scene.prototype.setPointerOverSprite = function (sprite) {
  14483. if (this._pointerOverSprite === sprite) {
  14484. return;
  14485. }
  14486. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14487. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14488. }
  14489. this._pointerOverSprite = sprite;
  14490. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14491. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14492. }
  14493. };
  14494. Scene.prototype.getPointerOverSprite = function () {
  14495. return this._pointerOverSprite;
  14496. };
  14497. // Physics
  14498. Scene.prototype.getPhysicsEngine = function () {
  14499. return this._physicsEngine;
  14500. };
  14501. /**
  14502. * Enables physics to the current scene
  14503. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14504. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14505. * @return {boolean} was the physics engine initialized
  14506. */
  14507. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14508. if (this._physicsEngine) {
  14509. return true;
  14510. }
  14511. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14512. if (!this._physicsEngine.isSupported()) {
  14513. this._physicsEngine = null;
  14514. return false;
  14515. }
  14516. this._physicsEngine._initialize(gravity);
  14517. return true;
  14518. };
  14519. Scene.prototype.disablePhysicsEngine = function () {
  14520. if (!this._physicsEngine) {
  14521. return;
  14522. }
  14523. this._physicsEngine.dispose();
  14524. this._physicsEngine = undefined;
  14525. };
  14526. Scene.prototype.isPhysicsEnabled = function () {
  14527. return this._physicsEngine !== undefined;
  14528. };
  14529. /**
  14530. * Sets the gravity of the physics engine (and NOT of the scene)
  14531. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14532. */
  14533. Scene.prototype.setGravity = function (gravity) {
  14534. if (!this._physicsEngine) {
  14535. return;
  14536. }
  14537. this._physicsEngine._setGravity(gravity);
  14538. };
  14539. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14540. if (parts.parts) {
  14541. options = parts;
  14542. parts = parts.parts;
  14543. }
  14544. if (!this._physicsEngine) {
  14545. return null;
  14546. }
  14547. for (var index = 0; index < parts.length; index++) {
  14548. var mesh = parts[index].mesh;
  14549. mesh._physicImpostor = parts[index].impostor;
  14550. mesh._physicsMass = options.mass / parts.length;
  14551. mesh._physicsFriction = options.friction;
  14552. mesh._physicRestitution = options.restitution;
  14553. }
  14554. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14555. };
  14556. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14557. for (var index = 0; index < compound.parts.length; index++) {
  14558. var mesh = compound.parts[index].mesh;
  14559. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14560. this._physicsEngine._unregisterMesh(mesh);
  14561. }
  14562. };
  14563. // Misc.
  14564. Scene.prototype.createDefaultCameraOrLight = function () {
  14565. // Light
  14566. if (this.lights.length === 0) {
  14567. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14568. }
  14569. // Camera
  14570. if (!this.activeCamera) {
  14571. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14572. // Compute position
  14573. var worldExtends = this.getWorldExtends();
  14574. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14575. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14576. camera.setTarget(worldCenter);
  14577. this.activeCamera = camera;
  14578. }
  14579. };
  14580. // Tags
  14581. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14582. if (tagsQuery === undefined) {
  14583. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14584. return list;
  14585. }
  14586. var listByTags = [];
  14587. forEach = forEach || (function (item) { return; });
  14588. for (var i in list) {
  14589. var item = list[i];
  14590. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14591. listByTags.push(item);
  14592. forEach(item);
  14593. }
  14594. }
  14595. return listByTags;
  14596. };
  14597. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14598. return this._getByTags(this.meshes, tagsQuery, forEach);
  14599. };
  14600. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14601. return this._getByTags(this.cameras, tagsQuery, forEach);
  14602. };
  14603. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14604. return this._getByTags(this.lights, tagsQuery, forEach);
  14605. };
  14606. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14607. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14608. };
  14609. // Statics
  14610. Scene._FOGMODE_NONE = 0;
  14611. Scene._FOGMODE_EXP = 1;
  14612. Scene._FOGMODE_EXP2 = 2;
  14613. Scene._FOGMODE_LINEAR = 3;
  14614. Scene.MinDeltaTime = 1.0;
  14615. Scene.MaxDeltaTime = 1000.0;
  14616. return Scene;
  14617. })();
  14618. BABYLON.Scene = Scene;
  14619. })(BABYLON || (BABYLON = {}));
  14620. var BABYLON;
  14621. (function (BABYLON) {
  14622. var VertexBuffer = (function () {
  14623. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14624. if (engine instanceof BABYLON.Mesh) {
  14625. this._engine = engine.getScene().getEngine();
  14626. }
  14627. else {
  14628. this._engine = engine;
  14629. }
  14630. this._updatable = updatable;
  14631. this._data = data;
  14632. if (!postponeInternalCreation) {
  14633. this.create();
  14634. }
  14635. this._kind = kind;
  14636. if (stride) {
  14637. this._strideSize = stride;
  14638. return;
  14639. }
  14640. // Deduce stride from kind
  14641. switch (kind) {
  14642. case VertexBuffer.PositionKind:
  14643. this._strideSize = 3;
  14644. break;
  14645. case VertexBuffer.NormalKind:
  14646. this._strideSize = 3;
  14647. break;
  14648. case VertexBuffer.UVKind:
  14649. case VertexBuffer.UV2Kind:
  14650. case VertexBuffer.UV3Kind:
  14651. case VertexBuffer.UV4Kind:
  14652. case VertexBuffer.UV5Kind:
  14653. case VertexBuffer.UV6Kind:
  14654. this._strideSize = 2;
  14655. break;
  14656. case VertexBuffer.ColorKind:
  14657. this._strideSize = 4;
  14658. break;
  14659. case VertexBuffer.MatricesIndicesKind:
  14660. case VertexBuffer.MatricesIndicesExtraKind:
  14661. this._strideSize = 4;
  14662. break;
  14663. case VertexBuffer.MatricesWeightsKind:
  14664. case VertexBuffer.MatricesWeightsExtraKind:
  14665. this._strideSize = 4;
  14666. break;
  14667. }
  14668. }
  14669. // Properties
  14670. VertexBuffer.prototype.isUpdatable = function () {
  14671. return this._updatable;
  14672. };
  14673. VertexBuffer.prototype.getData = function () {
  14674. return this._data;
  14675. };
  14676. VertexBuffer.prototype.getBuffer = function () {
  14677. return this._buffer;
  14678. };
  14679. VertexBuffer.prototype.getStrideSize = function () {
  14680. return this._strideSize;
  14681. };
  14682. // Methods
  14683. VertexBuffer.prototype.create = function (data) {
  14684. if (!data && this._buffer) {
  14685. return; // nothing to do
  14686. }
  14687. data = data || this._data;
  14688. if (!this._buffer) {
  14689. if (this._updatable) {
  14690. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14691. }
  14692. else {
  14693. this._buffer = this._engine.createVertexBuffer(data);
  14694. }
  14695. }
  14696. if (this._updatable) {
  14697. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14698. this._data = data;
  14699. }
  14700. };
  14701. VertexBuffer.prototype.update = function (data) {
  14702. this.create(data);
  14703. };
  14704. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14705. if (!this._buffer) {
  14706. return;
  14707. }
  14708. if (this._updatable) {
  14709. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14710. this._data = null;
  14711. }
  14712. };
  14713. VertexBuffer.prototype.dispose = function () {
  14714. if (!this._buffer) {
  14715. return;
  14716. }
  14717. if (this._engine._releaseBuffer(this._buffer)) {
  14718. this._buffer = null;
  14719. }
  14720. };
  14721. Object.defineProperty(VertexBuffer, "PositionKind", {
  14722. get: function () {
  14723. return VertexBuffer._PositionKind;
  14724. },
  14725. enumerable: true,
  14726. configurable: true
  14727. });
  14728. Object.defineProperty(VertexBuffer, "NormalKind", {
  14729. get: function () {
  14730. return VertexBuffer._NormalKind;
  14731. },
  14732. enumerable: true,
  14733. configurable: true
  14734. });
  14735. Object.defineProperty(VertexBuffer, "UVKind", {
  14736. get: function () {
  14737. return VertexBuffer._UVKind;
  14738. },
  14739. enumerable: true,
  14740. configurable: true
  14741. });
  14742. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14743. get: function () {
  14744. return VertexBuffer._UV2Kind;
  14745. },
  14746. enumerable: true,
  14747. configurable: true
  14748. });
  14749. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14750. get: function () {
  14751. return VertexBuffer._UV3Kind;
  14752. },
  14753. enumerable: true,
  14754. configurable: true
  14755. });
  14756. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14757. get: function () {
  14758. return VertexBuffer._UV4Kind;
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14764. get: function () {
  14765. return VertexBuffer._UV5Kind;
  14766. },
  14767. enumerable: true,
  14768. configurable: true
  14769. });
  14770. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14771. get: function () {
  14772. return VertexBuffer._UV6Kind;
  14773. },
  14774. enumerable: true,
  14775. configurable: true
  14776. });
  14777. Object.defineProperty(VertexBuffer, "ColorKind", {
  14778. get: function () {
  14779. return VertexBuffer._ColorKind;
  14780. },
  14781. enumerable: true,
  14782. configurable: true
  14783. });
  14784. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14785. get: function () {
  14786. return VertexBuffer._MatricesIndicesKind;
  14787. },
  14788. enumerable: true,
  14789. configurable: true
  14790. });
  14791. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14792. get: function () {
  14793. return VertexBuffer._MatricesWeightsKind;
  14794. },
  14795. enumerable: true,
  14796. configurable: true
  14797. });
  14798. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14799. get: function () {
  14800. return VertexBuffer._MatricesIndicesExtraKind;
  14801. },
  14802. enumerable: true,
  14803. configurable: true
  14804. });
  14805. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14806. get: function () {
  14807. return VertexBuffer._MatricesWeightsExtraKind;
  14808. },
  14809. enumerable: true,
  14810. configurable: true
  14811. });
  14812. // Enums
  14813. VertexBuffer._PositionKind = "position";
  14814. VertexBuffer._NormalKind = "normal";
  14815. VertexBuffer._UVKind = "uv";
  14816. VertexBuffer._UV2Kind = "uv2";
  14817. VertexBuffer._UV3Kind = "uv3";
  14818. VertexBuffer._UV4Kind = "uv4";
  14819. VertexBuffer._UV5Kind = "uv5";
  14820. VertexBuffer._UV6Kind = "uv6";
  14821. VertexBuffer._ColorKind = "color";
  14822. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14823. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14824. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14825. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14826. return VertexBuffer;
  14827. })();
  14828. BABYLON.VertexBuffer = VertexBuffer;
  14829. })(BABYLON || (BABYLON = {}));
  14830. var BABYLON;
  14831. (function (BABYLON) {
  14832. /**
  14833. * Creates an instance based on a source mesh.
  14834. */
  14835. var InstancedMesh = (function (_super) {
  14836. __extends(InstancedMesh, _super);
  14837. function InstancedMesh(name, source) {
  14838. _super.call(this, name, source.getScene());
  14839. source.instances.push(this);
  14840. this._sourceMesh = source;
  14841. this.position.copyFrom(source.position);
  14842. this.rotation.copyFrom(source.rotation);
  14843. this.scaling.copyFrom(source.scaling);
  14844. if (source.rotationQuaternion) {
  14845. this.rotationQuaternion = source.rotationQuaternion.clone();
  14846. }
  14847. this.infiniteDistance = source.infiniteDistance;
  14848. this.setPivotMatrix(source.getPivotMatrix());
  14849. this.refreshBoundingInfo();
  14850. this._syncSubMeshes();
  14851. }
  14852. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14853. // Methods
  14854. get: function () {
  14855. return this._sourceMesh.receiveShadows;
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. Object.defineProperty(InstancedMesh.prototype, "material", {
  14861. get: function () {
  14862. return this._sourceMesh.material;
  14863. },
  14864. enumerable: true,
  14865. configurable: true
  14866. });
  14867. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14868. get: function () {
  14869. return this._sourceMesh.visibility;
  14870. },
  14871. enumerable: true,
  14872. configurable: true
  14873. });
  14874. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14875. get: function () {
  14876. return this._sourceMesh.skeleton;
  14877. },
  14878. enumerable: true,
  14879. configurable: true
  14880. });
  14881. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14882. get: function () {
  14883. return this._sourceMesh.renderingGroupId;
  14884. },
  14885. enumerable: true,
  14886. configurable: true
  14887. });
  14888. InstancedMesh.prototype.getTotalVertices = function () {
  14889. return this._sourceMesh.getTotalVertices();
  14890. };
  14891. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14892. get: function () {
  14893. return this._sourceMesh;
  14894. },
  14895. enumerable: true,
  14896. configurable: true
  14897. });
  14898. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14899. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14900. };
  14901. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14902. return this._sourceMesh.isVerticesDataPresent(kind);
  14903. };
  14904. InstancedMesh.prototype.getIndices = function () {
  14905. return this._sourceMesh.getIndices();
  14906. };
  14907. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14908. get: function () {
  14909. return this._sourceMesh._positions;
  14910. },
  14911. enumerable: true,
  14912. configurable: true
  14913. });
  14914. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14915. var meshBB = this._sourceMesh.getBoundingInfo();
  14916. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14917. this._updateBoundingInfo();
  14918. };
  14919. InstancedMesh.prototype._preActivate = function () {
  14920. if (this._currentLOD) {
  14921. this._currentLOD._preActivate();
  14922. }
  14923. };
  14924. InstancedMesh.prototype._activate = function (renderId) {
  14925. if (this._currentLOD) {
  14926. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14927. }
  14928. };
  14929. InstancedMesh.prototype.getLOD = function (camera) {
  14930. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14931. if (this._currentLOD === this.sourceMesh) {
  14932. return this;
  14933. }
  14934. return this._currentLOD;
  14935. };
  14936. InstancedMesh.prototype._syncSubMeshes = function () {
  14937. this.releaseSubMeshes();
  14938. if (this._sourceMesh.subMeshes) {
  14939. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14940. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14941. }
  14942. }
  14943. };
  14944. InstancedMesh.prototype._generatePointsArray = function () {
  14945. return this._sourceMesh._generatePointsArray();
  14946. };
  14947. // Clone
  14948. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14949. var result = this._sourceMesh.createInstance(name);
  14950. // Deep copy
  14951. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14952. // Bounding info
  14953. this.refreshBoundingInfo();
  14954. // Parent
  14955. if (newParent) {
  14956. result.parent = newParent;
  14957. }
  14958. if (!doNotCloneChildren) {
  14959. // Children
  14960. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14961. var mesh = this.getScene().meshes[index];
  14962. if (mesh.parent === this) {
  14963. mesh.clone(mesh.name, result);
  14964. }
  14965. }
  14966. }
  14967. result.computeWorldMatrix(true);
  14968. return result;
  14969. };
  14970. // Dispoe
  14971. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14972. // Remove from mesh
  14973. var index = this._sourceMesh.instances.indexOf(this);
  14974. this._sourceMesh.instances.splice(index, 1);
  14975. _super.prototype.dispose.call(this, doNotRecurse);
  14976. };
  14977. return InstancedMesh;
  14978. })(BABYLON.AbstractMesh);
  14979. BABYLON.InstancedMesh = InstancedMesh;
  14980. })(BABYLON || (BABYLON = {}));
  14981. var BABYLON;
  14982. (function (BABYLON) {
  14983. var _InstancesBatch = (function () {
  14984. function _InstancesBatch() {
  14985. this.mustReturn = false;
  14986. this.visibleInstances = new Array();
  14987. this.renderSelf = new Array();
  14988. }
  14989. return _InstancesBatch;
  14990. })();
  14991. BABYLON._InstancesBatch = _InstancesBatch;
  14992. var Mesh = (function (_super) {
  14993. __extends(Mesh, _super);
  14994. /**
  14995. * @constructor
  14996. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14997. * @param {Scene} scene - The scene to add this mesh to.
  14998. * @param {Node} parent - The parent of this mesh, if it has one
  14999. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  15000. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  15001. * When false, achieved by calling a clone(), also passing False.
  15002. * This will make creation of children, recursive.
  15003. */
  15004. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  15005. if (parent === void 0) { parent = null; }
  15006. _super.call(this, name, scene);
  15007. // Members
  15008. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15009. this.instances = new Array();
  15010. this._LODLevels = new Array();
  15011. this._onBeforeRenderCallbacks = new Array();
  15012. this._onAfterRenderCallbacks = new Array();
  15013. this._visibleInstances = {};
  15014. this._renderIdForInstances = new Array();
  15015. this._batchCache = new _InstancesBatch();
  15016. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  15017. this._sideOrientation = Mesh._DEFAULTSIDE;
  15018. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  15019. if (source) {
  15020. // Geometry
  15021. if (source._geometry) {
  15022. source._geometry.applyToMesh(this);
  15023. }
  15024. // Deep copy
  15025. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  15026. // Pivot
  15027. this.setPivotMatrix(source.getPivotMatrix());
  15028. this.id = name + "." + source.id;
  15029. // Material
  15030. this.material = source.material;
  15031. var index;
  15032. if (!doNotCloneChildren) {
  15033. // Children
  15034. for (index = 0; index < scene.meshes.length; index++) {
  15035. var mesh = scene.meshes[index];
  15036. if (mesh.parent === source) {
  15037. // doNotCloneChildren is always going to be False
  15038. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15039. }
  15040. }
  15041. }
  15042. // Particles
  15043. for (index = 0; index < scene.particleSystems.length; index++) {
  15044. var system = scene.particleSystems[index];
  15045. if (system.emitter === source) {
  15046. system.clone(system.name, this);
  15047. }
  15048. }
  15049. this.computeWorldMatrix(true);
  15050. }
  15051. // Parent
  15052. if (parent !== null) {
  15053. this.parent = parent;
  15054. }
  15055. }
  15056. Object.defineProperty(Mesh, "FRONTSIDE", {
  15057. get: function () {
  15058. return Mesh._FRONTSIDE;
  15059. },
  15060. enumerable: true,
  15061. configurable: true
  15062. });
  15063. Object.defineProperty(Mesh, "BACKSIDE", {
  15064. get: function () {
  15065. return Mesh._BACKSIDE;
  15066. },
  15067. enumerable: true,
  15068. configurable: true
  15069. });
  15070. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15071. get: function () {
  15072. return Mesh._DOUBLESIDE;
  15073. },
  15074. enumerable: true,
  15075. configurable: true
  15076. });
  15077. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15078. get: function () {
  15079. return Mesh._DEFAULTSIDE;
  15080. },
  15081. enumerable: true,
  15082. configurable: true
  15083. });
  15084. Object.defineProperty(Mesh, "NO_CAP", {
  15085. get: function () {
  15086. return Mesh._NO_CAP;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. Object.defineProperty(Mesh, "CAP_START", {
  15092. get: function () {
  15093. return Mesh._CAP_START;
  15094. },
  15095. enumerable: true,
  15096. configurable: true
  15097. });
  15098. Object.defineProperty(Mesh, "CAP_END", {
  15099. get: function () {
  15100. return Mesh._CAP_END;
  15101. },
  15102. enumerable: true,
  15103. configurable: true
  15104. });
  15105. Object.defineProperty(Mesh, "CAP_ALL", {
  15106. get: function () {
  15107. return Mesh._CAP_ALL;
  15108. },
  15109. enumerable: true,
  15110. configurable: true
  15111. });
  15112. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15113. // Methods
  15114. get: function () {
  15115. return this._LODLevels.length > 0;
  15116. },
  15117. enumerable: true,
  15118. configurable: true
  15119. });
  15120. Mesh.prototype._sortLODLevels = function () {
  15121. this._LODLevels.sort(function (a, b) {
  15122. if (a.distance < b.distance) {
  15123. return 1;
  15124. }
  15125. if (a.distance > b.distance) {
  15126. return -1;
  15127. }
  15128. return 0;
  15129. });
  15130. };
  15131. /**
  15132. * Add a mesh as LOD level triggered at the given distance.
  15133. * @param {number} distance - the distance from the center of the object to show this level
  15134. * @param {Mesh} mesh - the mesh to be added as LOD level
  15135. * @return {Mesh} this mesh (for chaining)
  15136. */
  15137. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15138. if (mesh && mesh._masterMesh) {
  15139. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15140. return this;
  15141. }
  15142. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15143. this._LODLevels.push(level);
  15144. if (mesh) {
  15145. mesh._masterMesh = this;
  15146. }
  15147. this._sortLODLevels();
  15148. return this;
  15149. };
  15150. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15151. for (var index = 0; index < this._LODLevels.length; index++) {
  15152. var level = this._LODLevels[index];
  15153. if (level.distance === distance) {
  15154. return level.mesh;
  15155. }
  15156. }
  15157. return null;
  15158. };
  15159. /**
  15160. * Remove a mesh from the LOD array
  15161. * @param {Mesh} mesh - the mesh to be removed.
  15162. * @return {Mesh} this mesh (for chaining)
  15163. */
  15164. Mesh.prototype.removeLODLevel = function (mesh) {
  15165. for (var index = 0; index < this._LODLevels.length; index++) {
  15166. if (this._LODLevels[index].mesh === mesh) {
  15167. this._LODLevels.splice(index, 1);
  15168. if (mesh) {
  15169. mesh._masterMesh = null;
  15170. }
  15171. }
  15172. }
  15173. this._sortLODLevels();
  15174. return this;
  15175. };
  15176. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15177. if (!this._LODLevels || this._LODLevels.length === 0) {
  15178. return this;
  15179. }
  15180. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15181. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15182. if (this.onLODLevelSelection) {
  15183. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15184. }
  15185. return this;
  15186. }
  15187. for (var index = 0; index < this._LODLevels.length; index++) {
  15188. var level = this._LODLevels[index];
  15189. if (level.distance < distanceToCamera) {
  15190. if (level.mesh) {
  15191. level.mesh._preActivate();
  15192. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15193. }
  15194. if (this.onLODLevelSelection) {
  15195. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15196. }
  15197. return level.mesh;
  15198. }
  15199. }
  15200. if (this.onLODLevelSelection) {
  15201. this.onLODLevelSelection(distanceToCamera, this, this);
  15202. }
  15203. return this;
  15204. };
  15205. Object.defineProperty(Mesh.prototype, "geometry", {
  15206. get: function () {
  15207. return this._geometry;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Mesh.prototype.getTotalVertices = function () {
  15213. if (!this._geometry) {
  15214. return 0;
  15215. }
  15216. return this._geometry.getTotalVertices();
  15217. };
  15218. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15219. if (!this._geometry) {
  15220. return null;
  15221. }
  15222. return this._geometry.getVerticesData(kind, copyWhenShared);
  15223. };
  15224. Mesh.prototype.getVertexBuffer = function (kind) {
  15225. if (!this._geometry) {
  15226. return undefined;
  15227. }
  15228. return this._geometry.getVertexBuffer(kind);
  15229. };
  15230. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15231. if (!this._geometry) {
  15232. if (this._delayInfo) {
  15233. return this._delayInfo.indexOf(kind) !== -1;
  15234. }
  15235. return false;
  15236. }
  15237. return this._geometry.isVerticesDataPresent(kind);
  15238. };
  15239. Mesh.prototype.getVerticesDataKinds = function () {
  15240. if (!this._geometry) {
  15241. var result = [];
  15242. if (this._delayInfo) {
  15243. for (var kind in this._delayInfo) {
  15244. result.push(kind);
  15245. }
  15246. }
  15247. return result;
  15248. }
  15249. return this._geometry.getVerticesDataKinds();
  15250. };
  15251. Mesh.prototype.getTotalIndices = function () {
  15252. if (!this._geometry) {
  15253. return 0;
  15254. }
  15255. return this._geometry.getTotalIndices();
  15256. };
  15257. Mesh.prototype.getIndices = function (copyWhenShared) {
  15258. if (!this._geometry) {
  15259. return [];
  15260. }
  15261. return this._geometry.getIndices(copyWhenShared);
  15262. };
  15263. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15264. get: function () {
  15265. return this._masterMesh !== null && this._masterMesh !== undefined;
  15266. },
  15267. enumerable: true,
  15268. configurable: true
  15269. });
  15270. Mesh.prototype.isReady = function () {
  15271. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15272. return false;
  15273. }
  15274. return _super.prototype.isReady.call(this);
  15275. };
  15276. Mesh.prototype.isDisposed = function () {
  15277. return this._isDisposed;
  15278. };
  15279. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15280. get: function () {
  15281. return this._sideOrientation;
  15282. },
  15283. set: function (sideO) {
  15284. this._sideOrientation = sideO;
  15285. },
  15286. enumerable: true,
  15287. configurable: true
  15288. });
  15289. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15290. get: function () {
  15291. return this._areNormalsFrozen;
  15292. },
  15293. enumerable: true,
  15294. configurable: true
  15295. });
  15296. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15297. Mesh.prototype.freezeNormals = function () {
  15298. this._areNormalsFrozen = true;
  15299. };
  15300. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15301. Mesh.prototype.unfreezeNormals = function () {
  15302. this._areNormalsFrozen = false;
  15303. };
  15304. // Methods
  15305. Mesh.prototype._preActivate = function () {
  15306. var sceneRenderId = this.getScene().getRenderId();
  15307. if (this._preActivateId === sceneRenderId) {
  15308. return;
  15309. }
  15310. this._preActivateId = sceneRenderId;
  15311. this._visibleInstances = null;
  15312. };
  15313. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15314. if (!this._visibleInstances) {
  15315. this._visibleInstances = {};
  15316. this._visibleInstances.defaultRenderId = renderId;
  15317. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15318. }
  15319. if (!this._visibleInstances[renderId]) {
  15320. this._visibleInstances[renderId] = new Array();
  15321. }
  15322. this._visibleInstances[renderId].push(instance);
  15323. };
  15324. Mesh.prototype.refreshBoundingInfo = function () {
  15325. if (this._boundingInfo.isLocked) {
  15326. return;
  15327. }
  15328. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15329. if (data) {
  15330. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15331. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15332. }
  15333. if (this.subMeshes) {
  15334. for (var index = 0; index < this.subMeshes.length; index++) {
  15335. this.subMeshes[index].refreshBoundingInfo();
  15336. }
  15337. }
  15338. this._updateBoundingInfo();
  15339. };
  15340. Mesh.prototype._createGlobalSubMesh = function () {
  15341. var totalVertices = this.getTotalVertices();
  15342. if (!totalVertices || !this.getIndices()) {
  15343. return null;
  15344. }
  15345. this.releaseSubMeshes();
  15346. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15347. };
  15348. Mesh.prototype.subdivide = function (count) {
  15349. if (count < 1) {
  15350. return;
  15351. }
  15352. var totalIndices = this.getTotalIndices();
  15353. var subdivisionSize = (totalIndices / count) | 0;
  15354. var offset = 0;
  15355. // Ensure that subdivisionSize is a multiple of 3
  15356. while (subdivisionSize % 3 !== 0) {
  15357. subdivisionSize++;
  15358. }
  15359. this.releaseSubMeshes();
  15360. for (var index = 0; index < count; index++) {
  15361. if (offset >= totalIndices) {
  15362. break;
  15363. }
  15364. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15365. offset += subdivisionSize;
  15366. }
  15367. this.synchronizeInstances();
  15368. };
  15369. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15370. if (!this._geometry) {
  15371. var vertexData = new BABYLON.VertexData();
  15372. vertexData.set(data, kind);
  15373. var scene = this.getScene();
  15374. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15375. }
  15376. else {
  15377. this._geometry.setVerticesData(kind, data, updatable, stride);
  15378. }
  15379. };
  15380. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15381. if (!this._geometry) {
  15382. return;
  15383. }
  15384. if (!makeItUnique) {
  15385. this._geometry.updateVerticesData(kind, data, updateExtends);
  15386. }
  15387. else {
  15388. this.makeGeometryUnique();
  15389. this.updateVerticesData(kind, data, updateExtends, false);
  15390. }
  15391. };
  15392. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15393. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15394. if (!this._geometry) {
  15395. return;
  15396. }
  15397. if (!makeItUnique) {
  15398. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15399. }
  15400. else {
  15401. this.makeGeometryUnique();
  15402. this.updateVerticesDataDirectly(kind, data, offset, false);
  15403. }
  15404. };
  15405. // Mesh positions update function :
  15406. // updates the mesh positions according to the positionFunction returned values.
  15407. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15408. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15409. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15410. if (computeNormals === void 0) { computeNormals = true; }
  15411. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15412. positionFunction(positions);
  15413. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15414. if (computeNormals) {
  15415. var indices = this.getIndices();
  15416. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15417. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15418. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15419. }
  15420. };
  15421. Mesh.prototype.makeGeometryUnique = function () {
  15422. if (!this._geometry) {
  15423. return;
  15424. }
  15425. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15426. geometry.applyToMesh(this);
  15427. };
  15428. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15429. if (!this._geometry) {
  15430. var vertexData = new BABYLON.VertexData();
  15431. vertexData.indices = indices;
  15432. var scene = this.getScene();
  15433. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15434. }
  15435. else {
  15436. this._geometry.setIndices(indices, totalVertices);
  15437. }
  15438. };
  15439. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15440. var engine = this.getScene().getEngine();
  15441. // Wireframe
  15442. var indexToBind;
  15443. if (this._unIndexed) {
  15444. indexToBind = null;
  15445. }
  15446. else {
  15447. switch (fillMode) {
  15448. case BABYLON.Material.PointFillMode:
  15449. indexToBind = null;
  15450. break;
  15451. case BABYLON.Material.WireFrameFillMode:
  15452. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15453. break;
  15454. default:
  15455. case BABYLON.Material.TriangleFillMode:
  15456. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15457. break;
  15458. }
  15459. }
  15460. // VBOs
  15461. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15462. };
  15463. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15464. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15465. return;
  15466. }
  15467. if (this.onBeforeDraw) {
  15468. this.onBeforeDraw();
  15469. }
  15470. var engine = this.getScene().getEngine();
  15471. // Draw order
  15472. switch (fillMode) {
  15473. case BABYLON.Material.PointFillMode:
  15474. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15475. break;
  15476. case BABYLON.Material.WireFrameFillMode:
  15477. if (this._unIndexed) {
  15478. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15479. }
  15480. else {
  15481. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15482. }
  15483. break;
  15484. default:
  15485. if (this._unIndexed) {
  15486. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15487. }
  15488. else {
  15489. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15490. }
  15491. }
  15492. };
  15493. Mesh.prototype.registerBeforeRender = function (func) {
  15494. this._onBeforeRenderCallbacks.push(func);
  15495. };
  15496. Mesh.prototype.unregisterBeforeRender = function (func) {
  15497. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15498. if (index > -1) {
  15499. this._onBeforeRenderCallbacks.splice(index, 1);
  15500. }
  15501. };
  15502. Mesh.prototype.registerAfterRender = function (func) {
  15503. this._onAfterRenderCallbacks.push(func);
  15504. };
  15505. Mesh.prototype.unregisterAfterRender = function (func) {
  15506. var index = this._onAfterRenderCallbacks.indexOf(func);
  15507. if (index > -1) {
  15508. this._onAfterRenderCallbacks.splice(index, 1);
  15509. }
  15510. };
  15511. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15512. var scene = this.getScene();
  15513. this._batchCache.mustReturn = false;
  15514. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15515. this._batchCache.visibleInstances[subMeshId] = null;
  15516. if (this._visibleInstances) {
  15517. var currentRenderId = scene.getRenderId();
  15518. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15519. var selfRenderId = this._renderId;
  15520. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15521. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15522. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15523. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15524. }
  15525. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15526. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15527. this._batchCache.mustReturn = true;
  15528. return this._batchCache;
  15529. }
  15530. if (currentRenderId !== selfRenderId) {
  15531. this._batchCache.renderSelf[subMeshId] = false;
  15532. }
  15533. }
  15534. this._renderIdForInstances[subMeshId] = currentRenderId;
  15535. }
  15536. return this._batchCache;
  15537. };
  15538. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15539. var visibleInstances = batch.visibleInstances[subMesh._id];
  15540. var matricesCount = visibleInstances.length + 1;
  15541. var bufferSize = matricesCount * 16 * 4;
  15542. while (this._instancesBufferSize < bufferSize) {
  15543. this._instancesBufferSize *= 2;
  15544. }
  15545. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15546. if (this._worldMatricesInstancesBuffer) {
  15547. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15548. }
  15549. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15550. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15551. }
  15552. var offset = 0;
  15553. var instancesCount = 0;
  15554. var world = this.getWorldMatrix();
  15555. if (batch.renderSelf[subMesh._id]) {
  15556. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15557. offset += 16;
  15558. instancesCount++;
  15559. }
  15560. if (visibleInstances) {
  15561. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15562. var instance = visibleInstances[instanceIndex];
  15563. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15564. offset += 16;
  15565. instancesCount++;
  15566. }
  15567. }
  15568. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15569. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15570. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15571. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15572. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15573. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15574. this._draw(subMesh, fillMode, instancesCount);
  15575. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15576. };
  15577. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15578. var scene = this.getScene();
  15579. var engine = scene.getEngine();
  15580. if (hardwareInstancedRendering) {
  15581. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15582. }
  15583. else {
  15584. if (batch.renderSelf[subMesh._id]) {
  15585. // Draw
  15586. if (onBeforeDraw) {
  15587. onBeforeDraw(false, this.getWorldMatrix());
  15588. }
  15589. this._draw(subMesh, fillMode);
  15590. }
  15591. if (batch.visibleInstances[subMesh._id]) {
  15592. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15593. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15594. // World
  15595. var world = instance.getWorldMatrix();
  15596. if (onBeforeDraw) {
  15597. onBeforeDraw(true, world);
  15598. }
  15599. // Draw
  15600. this._draw(subMesh, fillMode);
  15601. }
  15602. }
  15603. }
  15604. };
  15605. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15606. var scene = this.getScene();
  15607. // Managing instances
  15608. var batch = this._getInstancesRenderList(subMesh._id);
  15609. if (batch.mustReturn) {
  15610. return;
  15611. }
  15612. // Checking geometry state
  15613. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15614. return;
  15615. }
  15616. var callbackIndex;
  15617. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15618. this._onBeforeRenderCallbacks[callbackIndex](this);
  15619. }
  15620. var engine = scene.getEngine();
  15621. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15622. // Material
  15623. var effectiveMaterial = subMesh.getMaterial();
  15624. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15625. return;
  15626. }
  15627. // Outline - step 1
  15628. var savedDepthWrite = engine.getDepthWrite();
  15629. if (this.renderOutline) {
  15630. engine.setDepthWrite(false);
  15631. scene.getOutlineRenderer().render(subMesh, batch);
  15632. engine.setDepthWrite(savedDepthWrite);
  15633. }
  15634. effectiveMaterial._preBind();
  15635. var effect = effectiveMaterial.getEffect();
  15636. // Bind
  15637. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15638. this._bind(subMesh, effect, fillMode);
  15639. var world = this.getWorldMatrix();
  15640. effectiveMaterial.bind(world, this);
  15641. // Alpha mode
  15642. if (enableAlphaMode) {
  15643. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15644. }
  15645. // Draw
  15646. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15647. if (isInstance) {
  15648. effectiveMaterial.bindOnlyWorldMatrix(world);
  15649. }
  15650. });
  15651. // Unbind
  15652. effectiveMaterial.unbind();
  15653. // Outline - step 2
  15654. if (this.renderOutline && savedDepthWrite) {
  15655. engine.setDepthWrite(true);
  15656. engine.setColorWrite(false);
  15657. scene.getOutlineRenderer().render(subMesh, batch);
  15658. engine.setColorWrite(true);
  15659. }
  15660. // Overlay
  15661. if (this.renderOverlay) {
  15662. var currentMode = engine.getAlphaMode();
  15663. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15664. scene.getOutlineRenderer().render(subMesh, batch, true);
  15665. engine.setAlphaMode(currentMode);
  15666. }
  15667. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15668. this._onAfterRenderCallbacks[callbackIndex](this);
  15669. }
  15670. };
  15671. Mesh.prototype.getEmittedParticleSystems = function () {
  15672. var results = new Array();
  15673. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15674. var particleSystem = this.getScene().particleSystems[index];
  15675. if (particleSystem.emitter === this) {
  15676. results.push(particleSystem);
  15677. }
  15678. }
  15679. return results;
  15680. };
  15681. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15682. var results = new Array();
  15683. var descendants = this.getDescendants();
  15684. descendants.push(this);
  15685. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15686. var particleSystem = this.getScene().particleSystems[index];
  15687. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15688. results.push(particleSystem);
  15689. }
  15690. }
  15691. return results;
  15692. };
  15693. Mesh.prototype.getChildren = function () {
  15694. var results = [];
  15695. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15696. var mesh = this.getScene().meshes[index];
  15697. if (mesh.parent === this) {
  15698. results.push(mesh);
  15699. }
  15700. }
  15701. return results;
  15702. };
  15703. Mesh.prototype._checkDelayState = function () {
  15704. var _this = this;
  15705. var that = this;
  15706. var scene = this.getScene();
  15707. if (this._geometry) {
  15708. this._geometry.load(scene);
  15709. }
  15710. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15711. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15712. scene._addPendingData(that);
  15713. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15714. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15715. if (data instanceof ArrayBuffer) {
  15716. _this._delayLoadingFunction(data, _this);
  15717. }
  15718. else {
  15719. _this._delayLoadingFunction(JSON.parse(data), _this);
  15720. }
  15721. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15722. scene._removePendingData(_this);
  15723. }, function () { }, scene.database, getBinaryData);
  15724. }
  15725. };
  15726. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15727. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15728. return false;
  15729. }
  15730. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15731. return false;
  15732. }
  15733. this._checkDelayState();
  15734. return true;
  15735. };
  15736. Mesh.prototype.setMaterialByID = function (id) {
  15737. var materials = this.getScene().materials;
  15738. var index;
  15739. for (index = 0; index < materials.length; index++) {
  15740. if (materials[index].id === id) {
  15741. this.material = materials[index];
  15742. return;
  15743. }
  15744. }
  15745. // Multi
  15746. var multiMaterials = this.getScene().multiMaterials;
  15747. for (index = 0; index < multiMaterials.length; index++) {
  15748. if (multiMaterials[index].id === id) {
  15749. this.material = multiMaterials[index];
  15750. return;
  15751. }
  15752. }
  15753. };
  15754. Mesh.prototype.getAnimatables = function () {
  15755. var results = [];
  15756. if (this.material) {
  15757. results.push(this.material);
  15758. }
  15759. if (this.skeleton) {
  15760. results.push(this.skeleton);
  15761. }
  15762. return results;
  15763. };
  15764. // Geometry
  15765. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15766. // Position
  15767. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15768. return;
  15769. }
  15770. this._resetPointsArrayCache();
  15771. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15772. var temp = [];
  15773. var index;
  15774. for (index = 0; index < data.length; index += 3) {
  15775. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15776. }
  15777. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15778. // Normals
  15779. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15780. return;
  15781. }
  15782. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15783. temp = [];
  15784. for (index = 0; index < data.length; index += 3) {
  15785. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15786. }
  15787. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15788. // flip faces?
  15789. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15790. this.flipFaces();
  15791. }
  15792. };
  15793. // Will apply current transform to mesh and reset world matrix
  15794. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15795. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15796. this.scaling.copyFromFloats(1, 1, 1);
  15797. this.position.copyFromFloats(0, 0, 0);
  15798. this.rotation.copyFromFloats(0, 0, 0);
  15799. //only if quaternion is already set
  15800. if (this.rotationQuaternion) {
  15801. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15802. }
  15803. this._worldMatrix = BABYLON.Matrix.Identity();
  15804. };
  15805. // Cache
  15806. Mesh.prototype._resetPointsArrayCache = function () {
  15807. this._positions = null;
  15808. };
  15809. Mesh.prototype._generatePointsArray = function () {
  15810. if (this._positions)
  15811. return true;
  15812. this._positions = [];
  15813. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15814. if (!data) {
  15815. return false;
  15816. }
  15817. for (var index = 0; index < data.length; index += 3) {
  15818. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15819. }
  15820. return true;
  15821. };
  15822. // Clone
  15823. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15824. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15825. };
  15826. // Dispose
  15827. Mesh.prototype.dispose = function (doNotRecurse) {
  15828. if (this._geometry) {
  15829. this._geometry.releaseForMesh(this, true);
  15830. }
  15831. // Instances
  15832. if (this._worldMatricesInstancesBuffer) {
  15833. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15834. this._worldMatricesInstancesBuffer = null;
  15835. }
  15836. while (this.instances.length) {
  15837. this.instances[0].dispose();
  15838. }
  15839. _super.prototype.dispose.call(this, doNotRecurse);
  15840. };
  15841. // Geometric tools
  15842. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15843. var _this = this;
  15844. var scene = this.getScene();
  15845. var onload = function (img) {
  15846. // Getting height map data
  15847. var canvas = document.createElement("canvas");
  15848. var context = canvas.getContext("2d");
  15849. var heightMapWidth = img.width;
  15850. var heightMapHeight = img.height;
  15851. canvas.width = heightMapWidth;
  15852. canvas.height = heightMapHeight;
  15853. context.drawImage(img, 0, 0);
  15854. // Create VertexData from map data
  15855. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15856. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15857. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15858. //execute success callback, if set
  15859. if (onSuccess) {
  15860. onSuccess(_this);
  15861. }
  15862. };
  15863. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15864. };
  15865. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15866. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15867. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15868. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15869. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15870. return;
  15871. }
  15872. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15873. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15874. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15875. var position = BABYLON.Vector3.Zero();
  15876. var normal = BABYLON.Vector3.Zero();
  15877. var uv = BABYLON.Vector2.Zero();
  15878. for (var index = 0; index < positions.length; index += 3) {
  15879. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15880. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15881. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15882. // Compute height
  15883. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15884. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15885. var pos = (u + v * heightMapWidth) * 4;
  15886. var r = buffer[pos] / 255.0;
  15887. var g = buffer[pos + 1] / 255.0;
  15888. var b = buffer[pos + 2] / 255.0;
  15889. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15890. normal.normalize();
  15891. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15892. position = position.add(normal);
  15893. position.toArray(positions, index);
  15894. }
  15895. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15896. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15897. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15898. };
  15899. Mesh.prototype.convertToFlatShadedMesh = function () {
  15900. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15901. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15902. var kinds = this.getVerticesDataKinds();
  15903. var vbs = [];
  15904. var data = [];
  15905. var newdata = [];
  15906. var updatableNormals = false;
  15907. var kindIndex;
  15908. var kind;
  15909. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15910. kind = kinds[kindIndex];
  15911. var vertexBuffer = this.getVertexBuffer(kind);
  15912. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15913. updatableNormals = vertexBuffer.isUpdatable();
  15914. kinds.splice(kindIndex, 1);
  15915. kindIndex--;
  15916. continue;
  15917. }
  15918. vbs[kind] = vertexBuffer;
  15919. data[kind] = vbs[kind].getData();
  15920. newdata[kind] = [];
  15921. }
  15922. // Save previous submeshes
  15923. var previousSubmeshes = this.subMeshes.slice(0);
  15924. var indices = this.getIndices();
  15925. var totalIndices = this.getTotalIndices();
  15926. // Generating unique vertices per face
  15927. var index;
  15928. for (index = 0; index < totalIndices; index++) {
  15929. var vertexIndex = indices[index];
  15930. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15931. kind = kinds[kindIndex];
  15932. var stride = vbs[kind].getStrideSize();
  15933. for (var offset = 0; offset < stride; offset++) {
  15934. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15935. }
  15936. }
  15937. }
  15938. // Updating faces & normal
  15939. var normals = [];
  15940. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15941. for (index = 0; index < totalIndices; index += 3) {
  15942. indices[index] = index;
  15943. indices[index + 1] = index + 1;
  15944. indices[index + 2] = index + 2;
  15945. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15946. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15947. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15948. var p1p2 = p1.subtract(p2);
  15949. var p3p2 = p3.subtract(p2);
  15950. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15951. // Store same normals for every vertex
  15952. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15953. normals.push(normal.x);
  15954. normals.push(normal.y);
  15955. normals.push(normal.z);
  15956. }
  15957. }
  15958. this.setIndices(indices);
  15959. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15960. // Updating vertex buffers
  15961. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15962. kind = kinds[kindIndex];
  15963. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15964. }
  15965. // Updating submeshes
  15966. this.releaseSubMeshes();
  15967. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15968. var previousOne = previousSubmeshes[submeshIndex];
  15969. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15970. }
  15971. this.synchronizeInstances();
  15972. };
  15973. Mesh.prototype.convertToUnIndexedMesh = function () {
  15974. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15975. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15976. var kinds = this.getVerticesDataKinds();
  15977. var vbs = [];
  15978. var data = [];
  15979. var newdata = [];
  15980. var updatableNormals = false;
  15981. var kindIndex;
  15982. var kind;
  15983. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15984. kind = kinds[kindIndex];
  15985. var vertexBuffer = this.getVertexBuffer(kind);
  15986. vbs[kind] = vertexBuffer;
  15987. data[kind] = vbs[kind].getData();
  15988. newdata[kind] = [];
  15989. }
  15990. // Save previous submeshes
  15991. var previousSubmeshes = this.subMeshes.slice(0);
  15992. var indices = this.getIndices();
  15993. var totalIndices = this.getTotalIndices();
  15994. // Generating unique vertices per face
  15995. var index;
  15996. for (index = 0; index < totalIndices; index++) {
  15997. var vertexIndex = indices[index];
  15998. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15999. kind = kinds[kindIndex];
  16000. var stride = vbs[kind].getStrideSize();
  16001. for (var offset = 0; offset < stride; offset++) {
  16002. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16003. }
  16004. }
  16005. }
  16006. // Updating indices
  16007. for (index = 0; index < totalIndices; index += 3) {
  16008. indices[index] = index;
  16009. indices[index + 1] = index + 1;
  16010. indices[index + 2] = index + 2;
  16011. }
  16012. this.setIndices(indices);
  16013. // Updating vertex buffers
  16014. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16015. kind = kinds[kindIndex];
  16016. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16017. }
  16018. // Updating submeshes
  16019. this.releaseSubMeshes();
  16020. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16021. var previousOne = previousSubmeshes[submeshIndex];
  16022. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16023. }
  16024. this._unIndexed = true;
  16025. this.synchronizeInstances();
  16026. };
  16027. // will inverse faces orientations, and invert normals too if specified
  16028. Mesh.prototype.flipFaces = function (flipNormals) {
  16029. if (flipNormals === void 0) { flipNormals = false; }
  16030. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16031. var i;
  16032. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16033. for (i = 0; i < vertex_data.normals.length; i++) {
  16034. vertex_data.normals[i] *= -1;
  16035. }
  16036. }
  16037. var temp;
  16038. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16039. // reassign indices
  16040. temp = vertex_data.indices[i + 1];
  16041. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16042. vertex_data.indices[i + 2] = temp;
  16043. }
  16044. vertex_data.applyToMesh(this);
  16045. };
  16046. // Instances
  16047. Mesh.prototype.createInstance = function (name) {
  16048. return new BABYLON.InstancedMesh(name, this);
  16049. };
  16050. Mesh.prototype.synchronizeInstances = function () {
  16051. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16052. var instance = this.instances[instanceIndex];
  16053. instance._syncSubMeshes();
  16054. }
  16055. };
  16056. /**
  16057. * Simplify the mesh according to the given array of settings.
  16058. * Function will return immediately and will simplify async.
  16059. * @param settings a collection of simplification settings.
  16060. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16061. * @param type the type of simplification to run.
  16062. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16063. */
  16064. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16065. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16066. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16067. this.getScene().simplificationQueue.addTask({
  16068. settings: settings,
  16069. parallelProcessing: parallelProcessing,
  16070. mesh: this,
  16071. simplificationType: simplificationType,
  16072. successCallback: successCallback
  16073. });
  16074. };
  16075. /**
  16076. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16077. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16078. * This should be used together with the simplification to avoid disappearing triangles.
  16079. * @param successCallback an optional success callback to be called after the optimization finished.
  16080. */
  16081. Mesh.prototype.optimizeIndices = function (successCallback) {
  16082. var _this = this;
  16083. var indices = this.getIndices();
  16084. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16085. var vectorPositions = [];
  16086. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16087. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16088. }
  16089. var dupes = [];
  16090. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16091. var realPos = vectorPositions.length - 1 - iteration;
  16092. var testedPosition = vectorPositions[realPos];
  16093. for (var j = 0; j < realPos; ++j) {
  16094. var againstPosition = vectorPositions[j];
  16095. if (testedPosition.equals(againstPosition)) {
  16096. dupes[realPos] = j;
  16097. break;
  16098. }
  16099. }
  16100. }, function () {
  16101. for (var i = 0; i < indices.length; ++i) {
  16102. indices[i] = dupes[indices[i]] || indices[i];
  16103. }
  16104. //indices are now reordered
  16105. var originalSubMeshes = _this.subMeshes.slice(0);
  16106. _this.setIndices(indices);
  16107. _this.subMeshes = originalSubMeshes;
  16108. if (successCallback) {
  16109. successCallback(_this);
  16110. }
  16111. });
  16112. };
  16113. // Statics
  16114. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16115. var mesh = new Mesh(parsedMesh.name, scene);
  16116. mesh.id = parsedMesh.id;
  16117. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16118. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16119. if (parsedMesh.rotationQuaternion) {
  16120. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16121. }
  16122. else if (parsedMesh.rotation) {
  16123. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16124. }
  16125. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16126. if (parsedMesh.localMatrix) {
  16127. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16128. }
  16129. else if (parsedMesh.pivotMatrix) {
  16130. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16131. }
  16132. mesh.setEnabled(parsedMesh.isEnabled);
  16133. mesh.isVisible = parsedMesh.isVisible;
  16134. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16135. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16136. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16137. if (parsedMesh.applyFog !== undefined) {
  16138. mesh.applyFog = parsedMesh.applyFog;
  16139. }
  16140. if (parsedMesh.pickable !== undefined) {
  16141. mesh.isPickable = parsedMesh.pickable;
  16142. }
  16143. if (parsedMesh.alphaIndex !== undefined) {
  16144. mesh.alphaIndex = parsedMesh.alphaIndex;
  16145. }
  16146. mesh.receiveShadows = parsedMesh.receiveShadows;
  16147. mesh.billboardMode = parsedMesh.billboardMode;
  16148. if (parsedMesh.visibility !== undefined) {
  16149. mesh.visibility = parsedMesh.visibility;
  16150. }
  16151. mesh.checkCollisions = parsedMesh.checkCollisions;
  16152. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16153. // freezeWorldMatrix
  16154. if (parsedMesh.freezeWorldMatrix) {
  16155. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16156. }
  16157. // Parent
  16158. if (parsedMesh.parentId) {
  16159. mesh._waitingParentId = parsedMesh.parentId;
  16160. }
  16161. // Actions
  16162. if (parsedMesh.actions !== undefined) {
  16163. mesh._waitingActions = parsedMesh.actions;
  16164. }
  16165. // Geometry
  16166. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16167. if (parsedMesh.delayLoadingFile) {
  16168. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16169. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16170. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16171. if (parsedMesh._binaryInfo) {
  16172. mesh._binaryInfo = parsedMesh._binaryInfo;
  16173. }
  16174. mesh._delayInfo = [];
  16175. if (parsedMesh.hasUVs) {
  16176. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16177. }
  16178. if (parsedMesh.hasUVs2) {
  16179. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16180. }
  16181. if (parsedMesh.hasUVs3) {
  16182. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16183. }
  16184. if (parsedMesh.hasUVs4) {
  16185. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16186. }
  16187. if (parsedMesh.hasUVs5) {
  16188. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16189. }
  16190. if (parsedMesh.hasUVs6) {
  16191. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16192. }
  16193. if (parsedMesh.hasColors) {
  16194. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16195. }
  16196. if (parsedMesh.hasMatricesIndices) {
  16197. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16198. }
  16199. if (parsedMesh.hasMatricesWeights) {
  16200. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16201. }
  16202. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16203. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16204. mesh._checkDelayState();
  16205. }
  16206. }
  16207. else {
  16208. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16209. }
  16210. // Material
  16211. if (parsedMesh.materialId) {
  16212. mesh.setMaterialByID(parsedMesh.materialId);
  16213. }
  16214. else {
  16215. mesh.material = null;
  16216. }
  16217. // Skeleton
  16218. if (parsedMesh.skeletonId > -1) {
  16219. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16220. if (parsedMesh.numBoneInfluencers) {
  16221. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16222. }
  16223. }
  16224. // Physics
  16225. if (parsedMesh.physicsImpostor) {
  16226. if (!scene.isPhysicsEnabled()) {
  16227. scene.enablePhysics();
  16228. }
  16229. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  16230. }
  16231. // Animations
  16232. if (parsedMesh.animations) {
  16233. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16234. var parsedAnimation = parsedMesh.animations[animationIndex];
  16235. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16236. }
  16237. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16238. }
  16239. if (parsedMesh.autoAnimate) {
  16240. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  16241. }
  16242. // Layer Mask
  16243. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16244. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16245. }
  16246. else {
  16247. mesh.layerMask = 0x0FFFFFFF;
  16248. }
  16249. // Instances
  16250. if (parsedMesh.instances) {
  16251. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16252. var parsedInstance = parsedMesh.instances[index];
  16253. var instance = mesh.createInstance(parsedInstance.name);
  16254. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16255. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16256. if (parsedInstance.rotationQuaternion) {
  16257. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16258. }
  16259. else if (parsedInstance.rotation) {
  16260. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16261. }
  16262. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16263. instance.checkCollisions = mesh.checkCollisions;
  16264. if (parsedMesh.animations) {
  16265. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16266. parsedAnimation = parsedMesh.animations[animationIndex];
  16267. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16268. }
  16269. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16270. }
  16271. }
  16272. }
  16273. return mesh;
  16274. };
  16275. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16276. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16277. pathArray: pathArray,
  16278. closeArray: closeArray,
  16279. closePath: closePath,
  16280. offset: offset,
  16281. updatable: updatable,
  16282. sideOrientation: sideOrientation,
  16283. instance: instance
  16284. }, scene);
  16285. };
  16286. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16287. var options = {
  16288. radius: radius,
  16289. tessellation: tessellation,
  16290. sideOrientation: sideOrientation,
  16291. updatable: updatable
  16292. };
  16293. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16294. };
  16295. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16296. var options = {
  16297. size: size,
  16298. sideOrientation: sideOrientation,
  16299. updatable: updatable
  16300. };
  16301. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16302. };
  16303. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16304. var options = {
  16305. segments: segments,
  16306. diameterX: diameter,
  16307. diameterY: diameter,
  16308. diameterZ: diameter,
  16309. sideOrientation: sideOrientation,
  16310. updatable: updatable
  16311. };
  16312. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16313. };
  16314. // Cylinder and cone
  16315. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16316. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16317. if (scene !== undefined) {
  16318. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16319. updatable = scene;
  16320. }
  16321. scene = subdivisions;
  16322. subdivisions = 1;
  16323. }
  16324. var options = {
  16325. height: height,
  16326. diameterTop: diameterTop,
  16327. diameterBottom: diameterBottom,
  16328. tessellation: tessellation,
  16329. subdivisions: subdivisions,
  16330. sideOrientation: sideOrientation,
  16331. updatable: updatable
  16332. };
  16333. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16334. };
  16335. // Torus (Code from SharpDX.org)
  16336. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16337. var options = {
  16338. diameter: diameter,
  16339. thickness: thickness,
  16340. tessellation: tessellation,
  16341. sideOrientation: sideOrientation,
  16342. updatable: updatable
  16343. };
  16344. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16345. };
  16346. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16347. var options = {
  16348. radius: radius,
  16349. tube: tube,
  16350. radialSegments: radialSegments,
  16351. tubularSegments: tubularSegments,
  16352. p: p,
  16353. q: q,
  16354. sideOrientation: sideOrientation,
  16355. updatable: updatable
  16356. };
  16357. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16358. };
  16359. // Lines
  16360. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16361. var options = {
  16362. points: points,
  16363. updatable: updatable,
  16364. instance: instance
  16365. };
  16366. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16367. };
  16368. // Dashed Lines
  16369. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16370. var options = {
  16371. points: points,
  16372. dashSize: dashSize,
  16373. gapSize: gapSize,
  16374. dashNb: dashNb,
  16375. updatable: updatable
  16376. };
  16377. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16378. };
  16379. // Extrusion
  16380. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16381. var options = {
  16382. shape: shape,
  16383. path: path,
  16384. scale: scale,
  16385. rotation: rotation,
  16386. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16387. sideOrientation: sideOrientation,
  16388. instance: instance,
  16389. updatable: updatable
  16390. };
  16391. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16392. };
  16393. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16394. var options = {
  16395. shape: shape,
  16396. path: path,
  16397. scaleFunction: scaleFunction,
  16398. rotationFunction: rotationFunction,
  16399. ribbonCloseArray: ribbonCloseArray,
  16400. ribbonClosePath: ribbonClosePath,
  16401. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16402. sideOrientation: sideOrientation,
  16403. instance: instance,
  16404. updatable: updatable
  16405. };
  16406. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16407. };
  16408. // Lathe
  16409. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16410. var options = {
  16411. shape: shape,
  16412. radius: radius,
  16413. tessellation: tessellation,
  16414. sideOrientation: sideOrientation,
  16415. updatable: updatable
  16416. };
  16417. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16418. };
  16419. // Plane & ground
  16420. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16421. var options = {
  16422. size: size,
  16423. width: size,
  16424. height: size,
  16425. sideOrientation: sideOrientation,
  16426. updatable: updatable
  16427. };
  16428. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16429. };
  16430. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16431. var options = {
  16432. width: width,
  16433. height: height,
  16434. subdivisions: subdivisions,
  16435. updatable: updatable
  16436. };
  16437. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16438. };
  16439. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16440. var options = {
  16441. xmin: xmin,
  16442. zmin: zmin,
  16443. xmax: xmax,
  16444. zmax: zmax,
  16445. subdivisions: subdivisions,
  16446. precision: precision,
  16447. updatable: updatable
  16448. };
  16449. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16450. };
  16451. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16452. var options = {
  16453. width: width,
  16454. height: height,
  16455. subdivisions: subdivisions,
  16456. minHeight: minHeight,
  16457. maxHeight: maxHeight,
  16458. updatable: updatable,
  16459. onReady: onReady
  16460. };
  16461. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16462. };
  16463. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16464. var options = {
  16465. path: path,
  16466. radius: radius,
  16467. tessellation: tessellation,
  16468. radiusFunction: radiusFunction,
  16469. arc: 1,
  16470. cap: cap,
  16471. updatable: updatable,
  16472. sideOrientation: sideOrientation,
  16473. instance: instance
  16474. };
  16475. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16476. };
  16477. Mesh.CreatePolyhedron = function (name, options, scene) {
  16478. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16479. };
  16480. Mesh.CreateIcoSphere = function (name, options, scene) {
  16481. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16482. };
  16483. // Decals
  16484. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16485. var options = {
  16486. position: position,
  16487. normal: normal,
  16488. size: size,
  16489. angle: angle
  16490. };
  16491. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16492. };
  16493. // Skeletons
  16494. /**
  16495. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16496. */
  16497. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16498. var source;
  16499. if (!this._sourcePositions) {
  16500. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16501. this._sourcePositions = new Float32Array(source);
  16502. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16503. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16504. }
  16505. }
  16506. return this._sourcePositions;
  16507. };
  16508. /**
  16509. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16510. */
  16511. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16512. var source;
  16513. if (!this._sourceNormals) {
  16514. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16515. this._sourceNormals = new Float32Array(source);
  16516. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16517. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16518. }
  16519. }
  16520. return this._sourceNormals;
  16521. };
  16522. /**
  16523. * Update the vertex buffers by applying transformation from the bones
  16524. * @param {skeleton} skeleton to apply
  16525. */
  16526. Mesh.prototype.applySkeleton = function (skeleton) {
  16527. if (!this.geometry) {
  16528. return;
  16529. }
  16530. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16531. return;
  16532. }
  16533. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16534. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16535. return this;
  16536. }
  16537. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16538. return this;
  16539. }
  16540. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16541. return this;
  16542. }
  16543. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16544. return this;
  16545. }
  16546. if (!this._sourcePositions) {
  16547. this.setPositionsForCPUSkinning();
  16548. }
  16549. if (!this._sourceNormals) {
  16550. this.setNormalsForCPUSkinning();
  16551. }
  16552. // positionsData checks for not being Float32Array will only pass at most once
  16553. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16554. if (!(positionsData instanceof Float32Array)) {
  16555. positionsData = new Float32Array(positionsData);
  16556. }
  16557. // normalsData checks for not being Float32Array will only pass at most once
  16558. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16559. if (!(normalsData instanceof Float32Array)) {
  16560. normalsData = new Float32Array(normalsData);
  16561. }
  16562. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16563. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16564. var needExtras = this.numBoneInfluencers > 4;
  16565. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16566. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16567. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16568. var tempVector3 = BABYLON.Vector3.Zero();
  16569. var finalMatrix = new BABYLON.Matrix();
  16570. var tempMatrix = new BABYLON.Matrix();
  16571. var matWeightIdx = 0;
  16572. var inf;
  16573. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16574. var weight;
  16575. for (inf = 0; inf < 4; inf++) {
  16576. weight = matricesWeightsData[matWeightIdx + inf];
  16577. if (weight > 0) {
  16578. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16579. finalMatrix.addToSelf(tempMatrix);
  16580. }
  16581. else
  16582. break;
  16583. }
  16584. if (needExtras) {
  16585. for (inf = 0; inf < 4; inf++) {
  16586. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16587. if (weight > 0) {
  16588. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16589. finalMatrix.addToSelf(tempMatrix);
  16590. }
  16591. else
  16592. break;
  16593. }
  16594. }
  16595. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16596. tempVector3.toArray(positionsData, index);
  16597. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16598. tempVector3.toArray(normalsData, index);
  16599. finalMatrix.reset();
  16600. }
  16601. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16602. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16603. return this;
  16604. };
  16605. // Tools
  16606. Mesh.MinMax = function (meshes) {
  16607. var minVector = null;
  16608. var maxVector = null;
  16609. for (var i in meshes) {
  16610. var mesh = meshes[i];
  16611. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16612. if (!minVector) {
  16613. minVector = boundingBox.minimumWorld;
  16614. maxVector = boundingBox.maximumWorld;
  16615. continue;
  16616. }
  16617. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16618. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16619. }
  16620. return {
  16621. min: minVector,
  16622. max: maxVector
  16623. };
  16624. };
  16625. Mesh.Center = function (meshesOrMinMaxVector) {
  16626. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16627. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16628. };
  16629. /**
  16630. * Merge the array of meshes into a single mesh for performance reasons.
  16631. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16632. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16633. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16634. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16635. */
  16636. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16637. if (disposeSource === void 0) { disposeSource = true; }
  16638. var index;
  16639. if (!allow32BitsIndices) {
  16640. var totalVertices = 0;
  16641. // Counting vertices
  16642. for (index = 0; index < meshes.length; index++) {
  16643. if (meshes[index]) {
  16644. totalVertices += meshes[index].getTotalVertices();
  16645. if (totalVertices > 65536) {
  16646. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16647. return null;
  16648. }
  16649. }
  16650. }
  16651. }
  16652. // Merge
  16653. var vertexData;
  16654. var otherVertexData;
  16655. var source;
  16656. for (index = 0; index < meshes.length; index++) {
  16657. if (meshes[index]) {
  16658. meshes[index].computeWorldMatrix(true);
  16659. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16660. otherVertexData.transform(meshes[index].getWorldMatrix());
  16661. if (vertexData) {
  16662. vertexData.merge(otherVertexData);
  16663. }
  16664. else {
  16665. vertexData = otherVertexData;
  16666. source = meshes[index];
  16667. }
  16668. }
  16669. }
  16670. if (!meshSubclass) {
  16671. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16672. }
  16673. vertexData.applyToMesh(meshSubclass);
  16674. // Setting properties
  16675. meshSubclass.material = source.material;
  16676. meshSubclass.checkCollisions = source.checkCollisions;
  16677. // Cleaning
  16678. if (disposeSource) {
  16679. for (index = 0; index < meshes.length; index++) {
  16680. if (meshes[index]) {
  16681. meshes[index].dispose();
  16682. }
  16683. }
  16684. }
  16685. return meshSubclass;
  16686. };
  16687. // Consts
  16688. Mesh._FRONTSIDE = 0;
  16689. Mesh._BACKSIDE = 1;
  16690. Mesh._DOUBLESIDE = 2;
  16691. Mesh._DEFAULTSIDE = 0;
  16692. Mesh._NO_CAP = 0;
  16693. Mesh._CAP_START = 1;
  16694. Mesh._CAP_END = 2;
  16695. Mesh._CAP_ALL = 3;
  16696. return Mesh;
  16697. })(BABYLON.AbstractMesh);
  16698. BABYLON.Mesh = Mesh;
  16699. })(BABYLON || (BABYLON = {}));
  16700. var BABYLON;
  16701. (function (BABYLON) {
  16702. var SubMesh = (function () {
  16703. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16704. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16705. this.materialIndex = materialIndex;
  16706. this.verticesStart = verticesStart;
  16707. this.verticesCount = verticesCount;
  16708. this.indexStart = indexStart;
  16709. this.indexCount = indexCount;
  16710. this._renderId = 0;
  16711. this._mesh = mesh;
  16712. this._renderingMesh = renderingMesh || mesh;
  16713. mesh.subMeshes.push(this);
  16714. this._trianglePlanes = [];
  16715. this._id = mesh.subMeshes.length - 1;
  16716. if (createBoundingBox) {
  16717. this.refreshBoundingInfo();
  16718. mesh.computeWorldMatrix(true);
  16719. }
  16720. }
  16721. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16722. get: function () {
  16723. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16724. },
  16725. enumerable: true,
  16726. configurable: true
  16727. });
  16728. SubMesh.prototype.getBoundingInfo = function () {
  16729. if (this.IsGlobal) {
  16730. return this._mesh.getBoundingInfo();
  16731. }
  16732. return this._boundingInfo;
  16733. };
  16734. SubMesh.prototype.getMesh = function () {
  16735. return this._mesh;
  16736. };
  16737. SubMesh.prototype.getRenderingMesh = function () {
  16738. return this._renderingMesh;
  16739. };
  16740. SubMesh.prototype.getMaterial = function () {
  16741. var rootMaterial = this._renderingMesh.material;
  16742. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16743. var multiMaterial = rootMaterial;
  16744. return multiMaterial.getSubMaterial(this.materialIndex);
  16745. }
  16746. if (!rootMaterial) {
  16747. return this._mesh.getScene().defaultMaterial;
  16748. }
  16749. return rootMaterial;
  16750. };
  16751. // Methods
  16752. SubMesh.prototype.refreshBoundingInfo = function () {
  16753. this._lastColliderWorldVertices = null;
  16754. if (this.IsGlobal) {
  16755. return;
  16756. }
  16757. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16758. if (!data) {
  16759. this._boundingInfo = this._mesh._boundingInfo;
  16760. return;
  16761. }
  16762. var indices = this._renderingMesh.getIndices();
  16763. var extend;
  16764. //is this the only submesh?
  16765. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16766. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16767. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16768. }
  16769. else {
  16770. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16771. }
  16772. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16773. };
  16774. SubMesh.prototype._checkCollision = function (collider) {
  16775. return this.getBoundingInfo()._checkCollision(collider);
  16776. };
  16777. SubMesh.prototype.updateBoundingInfo = function (world) {
  16778. if (!this.getBoundingInfo()) {
  16779. this.refreshBoundingInfo();
  16780. }
  16781. this.getBoundingInfo().update(world);
  16782. };
  16783. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16784. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16785. };
  16786. SubMesh.prototype.render = function (enableAlphaMode) {
  16787. this._renderingMesh.render(this, enableAlphaMode);
  16788. };
  16789. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16790. if (!this._linesIndexBuffer) {
  16791. var linesIndices = [];
  16792. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16793. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16794. }
  16795. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16796. this.linesIndexCount = linesIndices.length;
  16797. }
  16798. return this._linesIndexBuffer;
  16799. };
  16800. SubMesh.prototype.canIntersects = function (ray) {
  16801. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16802. };
  16803. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16804. var intersectInfo = null;
  16805. // Triangles test
  16806. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16807. var p0 = positions[indices[index]];
  16808. var p1 = positions[indices[index + 1]];
  16809. var p2 = positions[indices[index + 2]];
  16810. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16811. if (currentIntersectInfo) {
  16812. if (currentIntersectInfo.distance < 0) {
  16813. continue;
  16814. }
  16815. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16816. intersectInfo = currentIntersectInfo;
  16817. intersectInfo.faceId = index / 3;
  16818. if (fastCheck) {
  16819. break;
  16820. }
  16821. }
  16822. }
  16823. }
  16824. return intersectInfo;
  16825. };
  16826. // Clone
  16827. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16828. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16829. if (!this.IsGlobal) {
  16830. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16831. }
  16832. return result;
  16833. };
  16834. // Dispose
  16835. SubMesh.prototype.dispose = function () {
  16836. if (this._linesIndexBuffer) {
  16837. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16838. this._linesIndexBuffer = null;
  16839. }
  16840. // Remove from mesh
  16841. var index = this._mesh.subMeshes.indexOf(this);
  16842. this._mesh.subMeshes.splice(index, 1);
  16843. };
  16844. // Statics
  16845. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16846. var minVertexIndex = Number.MAX_VALUE;
  16847. var maxVertexIndex = -Number.MAX_VALUE;
  16848. renderingMesh = renderingMesh || mesh;
  16849. var indices = renderingMesh.getIndices();
  16850. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16851. var vertexIndex = indices[index];
  16852. if (vertexIndex < minVertexIndex)
  16853. minVertexIndex = vertexIndex;
  16854. if (vertexIndex > maxVertexIndex)
  16855. maxVertexIndex = vertexIndex;
  16856. }
  16857. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16858. };
  16859. return SubMesh;
  16860. })();
  16861. BABYLON.SubMesh = SubMesh;
  16862. })(BABYLON || (BABYLON = {}));
  16863. var BABYLON;
  16864. (function (BABYLON) {
  16865. var MeshBuilder = (function () {
  16866. function MeshBuilder() {
  16867. }
  16868. MeshBuilder.CreateBox = function (name, options, scene) {
  16869. var box = new BABYLON.Mesh(name, scene);
  16870. var vertexData = BABYLON.VertexData.CreateBox(options);
  16871. vertexData.applyToMesh(box, options.updatable);
  16872. return box;
  16873. };
  16874. MeshBuilder.CreateSphere = function (name, options, scene) {
  16875. var sphere = new BABYLON.Mesh(name, scene);
  16876. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16877. vertexData.applyToMesh(sphere, options.updatable);
  16878. return sphere;
  16879. };
  16880. MeshBuilder.CreateDisc = function (name, options, scene) {
  16881. var disc = new BABYLON.Mesh(name, scene);
  16882. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16883. vertexData.applyToMesh(disc, options.updatable);
  16884. return disc;
  16885. };
  16886. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16887. var sphere = new BABYLON.Mesh(name, scene);
  16888. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16889. vertexData.applyToMesh(sphere, options.updatable);
  16890. return sphere;
  16891. };
  16892. ;
  16893. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16894. var pathArray = options.pathArray;
  16895. var closeArray = options.closeArray;
  16896. var closePath = options.closePath;
  16897. var offset = options.offset;
  16898. var sideOrientation = options.sideOrientation;
  16899. var instance = options.instance;
  16900. var updatable = options.updatable;
  16901. if (instance) {
  16902. // positionFunction : ribbon case
  16903. // only pathArray and sideOrientation parameters are taken into account for positions update
  16904. var positionFunction = function (positions) {
  16905. var minlg = pathArray[0].length;
  16906. var i = 0;
  16907. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16908. for (var si = 1; si <= ns; si++) {
  16909. for (var p = 0; p < pathArray.length; p++) {
  16910. var path = pathArray[p];
  16911. var l = path.length;
  16912. minlg = (minlg < l) ? minlg : l;
  16913. var j = 0;
  16914. while (j < minlg) {
  16915. positions[i] = path[j].x;
  16916. positions[i + 1] = path[j].y;
  16917. positions[i + 2] = path[j].z;
  16918. j++;
  16919. i += 3;
  16920. }
  16921. if (instance._closePath) {
  16922. positions[i] = path[0].x;
  16923. positions[i + 1] = path[0].y;
  16924. positions[i + 2] = path[0].z;
  16925. i += 3;
  16926. }
  16927. }
  16928. }
  16929. };
  16930. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16931. positionFunction(positions);
  16932. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16933. if (!(instance.areNormalsFrozen)) {
  16934. var indices = instance.getIndices();
  16935. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16936. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16937. if (instance._closePath) {
  16938. var indexFirst = 0;
  16939. var indexLast = 0;
  16940. for (var p = 0; p < pathArray.length; p++) {
  16941. indexFirst = instance._idx[p] * 3;
  16942. if (p + 1 < pathArray.length) {
  16943. indexLast = (instance._idx[p + 1] - 1) * 3;
  16944. }
  16945. else {
  16946. indexLast = normals.length - 3;
  16947. }
  16948. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16949. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16950. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16951. normals[indexLast] = normals[indexFirst];
  16952. normals[indexLast + 1] = normals[indexFirst + 1];
  16953. normals[indexLast + 2] = normals[indexFirst + 2];
  16954. }
  16955. }
  16956. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16957. }
  16958. return instance;
  16959. }
  16960. else {
  16961. var ribbon = new BABYLON.Mesh(name, scene);
  16962. ribbon.sideOrientation = sideOrientation;
  16963. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16964. if (closePath) {
  16965. ribbon._idx = vertexData._idx;
  16966. }
  16967. ribbon._closePath = closePath;
  16968. ribbon._closeArray = closeArray;
  16969. vertexData.applyToMesh(ribbon, updatable);
  16970. return ribbon;
  16971. }
  16972. };
  16973. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16974. var cylinder = new BABYLON.Mesh(name, scene);
  16975. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16976. vertexData.applyToMesh(cylinder, options.updatable);
  16977. return cylinder;
  16978. };
  16979. MeshBuilder.CreateTorus = function (name, options, scene) {
  16980. var torus = new BABYLON.Mesh(name, scene);
  16981. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16982. vertexData.applyToMesh(torus, options.updatable);
  16983. return torus;
  16984. };
  16985. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16986. var torusKnot = new BABYLON.Mesh(name, scene);
  16987. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16988. vertexData.applyToMesh(torusKnot, options.updatable);
  16989. return torusKnot;
  16990. };
  16991. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  16992. var instance = options.instance;
  16993. var lines = options.lines;
  16994. if (instance) {
  16995. var positionFunction = function (positions) {
  16996. var i = 0;
  16997. for (var l = 0; l < lines.length; l++) {
  16998. var points = lines[l];
  16999. for (var p = 0; p < points.length; p++) {
  17000. positions[i] = points[p].x;
  17001. positions[i + 1] = points[p].y;
  17002. positions[i + 2] = points[p].z;
  17003. i += 3;
  17004. }
  17005. }
  17006. };
  17007. instance.updateMeshPositions(positionFunction, false);
  17008. return instance;
  17009. }
  17010. // line system creation
  17011. var lineSystem = new BABYLON.LinesMesh(name, scene);
  17012. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  17013. vertexData.applyToMesh(lineSystem, options.updatable);
  17014. return lineSystem;
  17015. };
  17016. MeshBuilder.CreateLines = function (name, options, scene) {
  17017. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  17018. return lines;
  17019. };
  17020. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  17021. var points = options.points;
  17022. var instance = options.instance;
  17023. var gapSize = options.gapSize;
  17024. var dashNb = options.dashNb;
  17025. var dashSize = options.dashSize;
  17026. if (instance) {
  17027. var positionFunction = function (positions) {
  17028. var curvect = BABYLON.Vector3.Zero();
  17029. var nbSeg = positions.length / 6;
  17030. var lg = 0;
  17031. var nb = 0;
  17032. var shft = 0;
  17033. var dashshft = 0;
  17034. var curshft = 0;
  17035. var p = 0;
  17036. var i = 0;
  17037. var j = 0;
  17038. for (i = 0; i < points.length - 1; i++) {
  17039. points[i + 1].subtractToRef(points[i], curvect);
  17040. lg += curvect.length();
  17041. }
  17042. shft = lg / nbSeg;
  17043. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17044. for (i = 0; i < points.length - 1; i++) {
  17045. points[i + 1].subtractToRef(points[i], curvect);
  17046. nb = Math.floor(curvect.length() / shft);
  17047. curvect.normalize();
  17048. j = 0;
  17049. while (j < nb && p < positions.length) {
  17050. curshft = shft * j;
  17051. positions[p] = points[i].x + curshft * curvect.x;
  17052. positions[p + 1] = points[i].y + curshft * curvect.y;
  17053. positions[p + 2] = points[i].z + curshft * curvect.z;
  17054. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17055. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17056. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17057. p += 6;
  17058. j++;
  17059. }
  17060. }
  17061. while (p < positions.length) {
  17062. positions[p] = points[i].x;
  17063. positions[p + 1] = points[i].y;
  17064. positions[p + 2] = points[i].z;
  17065. p += 3;
  17066. }
  17067. };
  17068. instance.updateMeshPositions(positionFunction, false);
  17069. return instance;
  17070. }
  17071. // dashed lines creation
  17072. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17073. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17074. vertexData.applyToMesh(dashedLines, options.updatable);
  17075. dashedLines.dashSize = dashSize;
  17076. dashedLines.gapSize = gapSize;
  17077. return dashedLines;
  17078. };
  17079. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17080. var path = options.path;
  17081. var shape = options.shape;
  17082. var scale = options.scale || 1;
  17083. var rotation = options.rotation || 0;
  17084. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17085. var updatable = options.updatable;
  17086. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17087. var instance = options.instance;
  17088. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17089. };
  17090. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17091. var path = options.path;
  17092. var shape = options.shape;
  17093. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17094. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17095. var ribbonCloseArray = options.ribbonCloseArray || false;
  17096. var ribbonClosePath = options.ribbonClosePath || false;
  17097. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17098. var updatable = options.updatable;
  17099. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17100. var instance = options.instance;
  17101. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17102. };
  17103. MeshBuilder.CreateLathe = function (name, options, scene) {
  17104. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17105. var closed = (options.closed === undefined) ? true : options.closed;
  17106. var shape = options.shape;
  17107. var radius = options.radius || 1;
  17108. var tessellation = options.tessellation || 64;
  17109. var updatable = options.updatable;
  17110. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17111. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17112. var pi2 = Math.PI * 2;
  17113. var paths = new Array();
  17114. var i = 0;
  17115. var p = 0;
  17116. var step = pi2 / tessellation * arc;
  17117. var rotated;
  17118. var path = new Array();
  17119. ;
  17120. for (i = 0; i <= tessellation; i++) {
  17121. var path = [];
  17122. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17123. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17124. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17125. }
  17126. for (p = 0; p < shape.length; p++) {
  17127. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17128. path.push(rotated);
  17129. }
  17130. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17131. 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));
  17132. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17133. }
  17134. paths.push(path);
  17135. }
  17136. // lathe ribbon
  17137. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17138. return lathe;
  17139. };
  17140. MeshBuilder.CreatePlane = function (name, options, scene) {
  17141. var plane = new BABYLON.Mesh(name, scene);
  17142. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17143. vertexData.applyToMesh(plane, options.updatable);
  17144. if (options.sourcePlane) {
  17145. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17146. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17147. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17148. plane.rotate(vectorProduct, product);
  17149. }
  17150. return plane;
  17151. };
  17152. MeshBuilder.CreateGround = function (name, options, scene) {
  17153. var ground = new BABYLON.GroundMesh(name, scene);
  17154. ground._setReady(false);
  17155. ground._subdivisions = options.subdivisions || 1;
  17156. ground._width = options.width || 1;
  17157. ground._height = options.height || 1;
  17158. ground._maxX = ground._width / 2;
  17159. ground._maxZ = ground._height / 2;
  17160. ground._minX = -ground._maxX;
  17161. ground._minZ = -ground._maxZ;
  17162. var vertexData = BABYLON.VertexData.CreateGround(options);
  17163. vertexData.applyToMesh(ground, options.updatable);
  17164. ground._setReady(true);
  17165. return ground;
  17166. };
  17167. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17168. var tiledGround = new BABYLON.Mesh(name, scene);
  17169. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17170. vertexData.applyToMesh(tiledGround, options.updatable);
  17171. return tiledGround;
  17172. };
  17173. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17174. var width = options.width || 10;
  17175. var height = options.height || 10;
  17176. var subdivisions = options.subdivisions || 1;
  17177. var minHeight = options.minHeight;
  17178. var maxHeight = options.maxHeight || 10;
  17179. var updatable = options.updatable;
  17180. var onReady = options.onReady;
  17181. var ground = new BABYLON.GroundMesh(name, scene);
  17182. ground._subdivisions = subdivisions;
  17183. ground._width = width;
  17184. ground._height = height;
  17185. ground._maxX = ground._width / 2;
  17186. ground._maxZ = ground._height / 2;
  17187. ground._minX = -ground._maxX;
  17188. ground._minZ = -ground._maxZ;
  17189. ground._setReady(false);
  17190. var onload = function (img) {
  17191. // Getting height map data
  17192. var canvas = document.createElement("canvas");
  17193. var context = canvas.getContext("2d");
  17194. var bufferWidth = img.width;
  17195. var bufferHeight = img.height;
  17196. canvas.width = bufferWidth;
  17197. canvas.height = bufferHeight;
  17198. context.drawImage(img, 0, 0);
  17199. // Create VertexData from map data
  17200. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17201. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17202. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17203. width: width, height: height,
  17204. subdivisions: subdivisions,
  17205. minHeight: minHeight, maxHeight: maxHeight,
  17206. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17207. });
  17208. vertexData.applyToMesh(ground, updatable);
  17209. ground._setReady(true);
  17210. //execute ready callback, if set
  17211. if (onReady) {
  17212. onReady(ground);
  17213. }
  17214. };
  17215. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17216. return ground;
  17217. };
  17218. MeshBuilder.CreateTube = function (name, options, scene) {
  17219. var path = options.path;
  17220. var radius = options.radius || 1;
  17221. var tessellation = options.tessellation || 64;
  17222. var radiusFunction = options.radiusFunction;
  17223. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17224. var updatable = options.updatable;
  17225. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17226. var instance = options.instance;
  17227. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17228. // tube geometry
  17229. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17230. var tangents = path3D.getTangents();
  17231. var normals = path3D.getNormals();
  17232. var distances = path3D.getDistances();
  17233. var pi2 = Math.PI * 2;
  17234. var step = pi2 / tessellation * arc;
  17235. var returnRadius = function () { return radius; };
  17236. var radiusFunctionFinal = radiusFunction || returnRadius;
  17237. var circlePath;
  17238. var rad;
  17239. var normal;
  17240. var rotated;
  17241. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17242. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17243. for (var i = 0; i < path.length; i++) {
  17244. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17245. circlePath = Array(); // current circle array
  17246. normal = normals[i]; // current normal
  17247. for (var t = 0; t < tessellation; t++) {
  17248. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17249. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17250. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17251. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17252. circlePath[t] = rotated;
  17253. }
  17254. circlePaths[index] = circlePath;
  17255. index++;
  17256. }
  17257. // cap
  17258. var capPath = function (nbPoints, pathIndex) {
  17259. var pointCap = Array();
  17260. for (var i = 0; i < nbPoints; i++) {
  17261. pointCap.push(path[pathIndex]);
  17262. }
  17263. return pointCap;
  17264. };
  17265. switch (cap) {
  17266. case BABYLON.Mesh.NO_CAP:
  17267. break;
  17268. case BABYLON.Mesh.CAP_START:
  17269. circlePaths[0] = capPath(tessellation, 0);
  17270. circlePaths[1] = circlePaths[2].slice(0);
  17271. break;
  17272. case BABYLON.Mesh.CAP_END:
  17273. circlePaths[index] = circlePaths[index - 1].slice(0);
  17274. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17275. break;
  17276. case BABYLON.Mesh.CAP_ALL:
  17277. circlePaths[0] = capPath(tessellation, 0);
  17278. circlePaths[1] = circlePaths[2].slice(0);
  17279. circlePaths[index] = circlePaths[index - 1].slice(0);
  17280. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17281. break;
  17282. default:
  17283. break;
  17284. }
  17285. return circlePaths;
  17286. };
  17287. var path3D;
  17288. var pathArray;
  17289. if (instance) {
  17290. var arc = options.arc || instance.arc;
  17291. path3D = (instance.path3D).update(path);
  17292. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17293. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17294. instance.path3D = path3D;
  17295. instance.pathArray = pathArray;
  17296. instance.arc = arc;
  17297. return instance;
  17298. }
  17299. // tube creation
  17300. path3D = new BABYLON.Path3D(path);
  17301. var newPathArray = new Array();
  17302. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17303. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17304. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17305. tube.pathArray = pathArray;
  17306. tube.path3D = path3D;
  17307. tube.tessellation = tessellation;
  17308. tube.cap = cap;
  17309. tube.arc = options.arc;
  17310. return tube;
  17311. };
  17312. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17313. var polyhedron = new BABYLON.Mesh(name, scene);
  17314. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17315. vertexData.applyToMesh(polyhedron, options.updatable);
  17316. return polyhedron;
  17317. };
  17318. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17319. var indices = sourceMesh.getIndices();
  17320. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17321. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17322. var position = options.position || BABYLON.Vector3.Zero();
  17323. var normal = options.normal || BABYLON.Vector3.Up();
  17324. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17325. var angle = options.angle || 0;
  17326. // Getting correct rotation
  17327. if (!normal) {
  17328. var target = new BABYLON.Vector3(0, 0, 1);
  17329. var camera = sourceMesh.getScene().activeCamera;
  17330. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17331. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17332. }
  17333. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17334. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17335. var pitch = Math.atan2(normal.y, len);
  17336. // Matrix
  17337. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17338. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17339. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17340. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17341. var vertexData = new BABYLON.VertexData();
  17342. vertexData.indices = [];
  17343. vertexData.positions = [];
  17344. vertexData.normals = [];
  17345. vertexData.uvs = [];
  17346. var currentVertexDataIndex = 0;
  17347. var extractDecalVector3 = function (indexId) {
  17348. var vertexId = indices[indexId];
  17349. var result = new BABYLON.PositionNormalVertex();
  17350. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17351. // Send vector to decal local world
  17352. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17353. // Get normal
  17354. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17355. return result;
  17356. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17357. var clip = function (vertices, axis) {
  17358. if (vertices.length === 0) {
  17359. return vertices;
  17360. }
  17361. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17362. var clipVertices = function (v0, v1) {
  17363. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17364. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17365. };
  17366. var result = new Array();
  17367. for (var index = 0; index < vertices.length; index += 3) {
  17368. var v1Out;
  17369. var v2Out;
  17370. var v3Out;
  17371. var total = 0;
  17372. var nV1, nV2, nV3, nV4;
  17373. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17374. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17375. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17376. v1Out = d1 > 0;
  17377. v2Out = d2 > 0;
  17378. v3Out = d3 > 0;
  17379. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17380. switch (total) {
  17381. case 0:
  17382. result.push(vertices[index]);
  17383. result.push(vertices[index + 1]);
  17384. result.push(vertices[index + 2]);
  17385. break;
  17386. case 1:
  17387. if (v1Out) {
  17388. nV1 = vertices[index + 1];
  17389. nV2 = vertices[index + 2];
  17390. nV3 = clipVertices(vertices[index], nV1);
  17391. nV4 = clipVertices(vertices[index], nV2);
  17392. }
  17393. if (v2Out) {
  17394. nV1 = vertices[index];
  17395. nV2 = vertices[index + 2];
  17396. nV3 = clipVertices(vertices[index + 1], nV1);
  17397. nV4 = clipVertices(vertices[index + 1], nV2);
  17398. result.push(nV3);
  17399. result.push(nV2.clone());
  17400. result.push(nV1.clone());
  17401. result.push(nV2.clone());
  17402. result.push(nV3.clone());
  17403. result.push(nV4);
  17404. break;
  17405. }
  17406. if (v3Out) {
  17407. nV1 = vertices[index];
  17408. nV2 = vertices[index + 1];
  17409. nV3 = clipVertices(vertices[index + 2], nV1);
  17410. nV4 = clipVertices(vertices[index + 2], nV2);
  17411. }
  17412. result.push(nV1.clone());
  17413. result.push(nV2.clone());
  17414. result.push(nV3);
  17415. result.push(nV4);
  17416. result.push(nV3.clone());
  17417. result.push(nV2.clone());
  17418. break;
  17419. case 2:
  17420. if (!v1Out) {
  17421. nV1 = vertices[index].clone();
  17422. nV2 = clipVertices(nV1, vertices[index + 1]);
  17423. nV3 = clipVertices(nV1, vertices[index + 2]);
  17424. result.push(nV1);
  17425. result.push(nV2);
  17426. result.push(nV3);
  17427. }
  17428. if (!v2Out) {
  17429. nV1 = vertices[index + 1].clone();
  17430. nV2 = clipVertices(nV1, vertices[index + 2]);
  17431. nV3 = clipVertices(nV1, vertices[index]);
  17432. result.push(nV1);
  17433. result.push(nV2);
  17434. result.push(nV3);
  17435. }
  17436. if (!v3Out) {
  17437. nV1 = vertices[index + 2].clone();
  17438. nV2 = clipVertices(nV1, vertices[index]);
  17439. nV3 = clipVertices(nV1, vertices[index + 1]);
  17440. result.push(nV1);
  17441. result.push(nV2);
  17442. result.push(nV3);
  17443. }
  17444. break;
  17445. case 3:
  17446. break;
  17447. }
  17448. }
  17449. return result;
  17450. };
  17451. for (var index = 0; index < indices.length; index += 3) {
  17452. var faceVertices = new Array();
  17453. faceVertices.push(extractDecalVector3(index));
  17454. faceVertices.push(extractDecalVector3(index + 1));
  17455. faceVertices.push(extractDecalVector3(index + 2));
  17456. // Clip
  17457. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17458. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17459. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17460. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17461. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17462. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17463. if (faceVertices.length === 0) {
  17464. continue;
  17465. }
  17466. // Add UVs and get back to world
  17467. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17468. var vertex = faceVertices[vIndex];
  17469. //TODO check for Int32Array
  17470. vertexData.indices.push(currentVertexDataIndex);
  17471. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17472. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17473. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17474. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17475. currentVertexDataIndex++;
  17476. }
  17477. }
  17478. // Return mesh
  17479. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17480. vertexData.applyToMesh(decal);
  17481. decal.position = position.clone();
  17482. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17483. return decal;
  17484. };
  17485. // Privates
  17486. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17487. // extrusion geometry
  17488. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17489. var tangents = path3D.getTangents();
  17490. var normals = path3D.getNormals();
  17491. var binormals = path3D.getBinormals();
  17492. var distances = path3D.getDistances();
  17493. var angle = 0;
  17494. var returnScale = function () { return scale; };
  17495. var returnRotation = function () { return rotation; };
  17496. var rotate = custom ? rotateFunction : returnRotation;
  17497. var scl = custom ? scaleFunction : returnScale;
  17498. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17499. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17500. for (var i = 0; i < curve.length; i++) {
  17501. var shapePath = new Array();
  17502. var angleStep = rotate(i, distances[i]);
  17503. var scaleRatio = scl(i, distances[i]);
  17504. for (var p = 0; p < shape.length; p++) {
  17505. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17506. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17507. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17508. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17509. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17510. shapePath[p] = rotated;
  17511. }
  17512. shapePaths[index] = shapePath;
  17513. angle += angleStep;
  17514. index++;
  17515. }
  17516. // cap
  17517. var capPath = function (shapePath) {
  17518. var pointCap = Array();
  17519. var barycenter = BABYLON.Vector3.Zero();
  17520. var i;
  17521. for (i = 0; i < shapePath.length; i++) {
  17522. barycenter.addInPlace(shapePath[i]);
  17523. }
  17524. barycenter.scaleInPlace(1 / shapePath.length);
  17525. for (i = 0; i < shapePath.length; i++) {
  17526. pointCap.push(barycenter);
  17527. }
  17528. return pointCap;
  17529. };
  17530. switch (cap) {
  17531. case BABYLON.Mesh.NO_CAP:
  17532. break;
  17533. case BABYLON.Mesh.CAP_START:
  17534. shapePaths[0] = capPath(shapePaths[2]);
  17535. shapePaths[1] = shapePaths[2].slice(0);
  17536. break;
  17537. case BABYLON.Mesh.CAP_END:
  17538. shapePaths[index] = shapePaths[index - 1];
  17539. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17540. break;
  17541. case BABYLON.Mesh.CAP_ALL:
  17542. shapePaths[0] = capPath(shapePaths[2]);
  17543. shapePaths[1] = shapePaths[2].slice(0);
  17544. shapePaths[index] = shapePaths[index - 1];
  17545. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17546. break;
  17547. default:
  17548. break;
  17549. }
  17550. return shapePaths;
  17551. };
  17552. var path3D;
  17553. var pathArray;
  17554. if (instance) {
  17555. path3D = (instance.path3D).update(curve);
  17556. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17557. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17558. return instance;
  17559. }
  17560. // extruded shape creation
  17561. path3D = new BABYLON.Path3D(curve);
  17562. var newShapePaths = new Array();
  17563. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17564. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17565. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17566. extrudedGeneric.pathArray = pathArray;
  17567. extrudedGeneric.path3D = path3D;
  17568. extrudedGeneric.cap = cap;
  17569. return extrudedGeneric;
  17570. };
  17571. return MeshBuilder;
  17572. })();
  17573. BABYLON.MeshBuilder = MeshBuilder;
  17574. })(BABYLON || (BABYLON = {}));
  17575. var BABYLON;
  17576. (function (BABYLON) {
  17577. var BaseTexture = (function () {
  17578. function BaseTexture(scene) {
  17579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17580. this.hasAlpha = false;
  17581. this.getAlphaFromRGB = false;
  17582. this.level = 1;
  17583. this.isCube = false;
  17584. this.isRenderTarget = false;
  17585. this.animations = new Array();
  17586. this.coordinatesIndex = 0;
  17587. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17588. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17589. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17590. this.anisotropicFilteringLevel = 4;
  17591. this._scene = scene;
  17592. this._scene.textures.push(this);
  17593. }
  17594. BaseTexture.prototype.getScene = function () {
  17595. return this._scene;
  17596. };
  17597. BaseTexture.prototype.getTextureMatrix = function () {
  17598. return null;
  17599. };
  17600. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17601. return null;
  17602. };
  17603. BaseTexture.prototype.getInternalTexture = function () {
  17604. return this._texture;
  17605. };
  17606. BaseTexture.prototype.isReady = function () {
  17607. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17608. return true;
  17609. }
  17610. if (this._texture) {
  17611. return this._texture.isReady;
  17612. }
  17613. return false;
  17614. };
  17615. BaseTexture.prototype.getSize = function () {
  17616. if (this._texture._width) {
  17617. return { width: this._texture._width, height: this._texture._height };
  17618. }
  17619. if (this._texture._size) {
  17620. return { width: this._texture._size, height: this._texture._size };
  17621. }
  17622. return { width: 0, height: 0 };
  17623. };
  17624. BaseTexture.prototype.getBaseSize = function () {
  17625. if (!this.isReady())
  17626. return { width: 0, height: 0 };
  17627. if (this._texture._size) {
  17628. return { width: this._texture._size, height: this._texture._size };
  17629. }
  17630. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17631. };
  17632. BaseTexture.prototype.scale = function (ratio) {
  17633. };
  17634. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17635. get: function () {
  17636. return false;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17642. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17643. for (var index = 0; index < texturesCache.length; index++) {
  17644. var texturesCacheEntry = texturesCache[index];
  17645. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17646. texturesCache.splice(index, 1);
  17647. return;
  17648. }
  17649. }
  17650. };
  17651. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17652. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17653. for (var index = 0; index < texturesCache.length; index++) {
  17654. var texturesCacheEntry = texturesCache[index];
  17655. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17656. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17657. texturesCacheEntry.references++;
  17658. return texturesCacheEntry;
  17659. }
  17660. }
  17661. }
  17662. return null;
  17663. };
  17664. BaseTexture.prototype.delayLoad = function () {
  17665. };
  17666. BaseTexture.prototype.clone = function () {
  17667. return null;
  17668. };
  17669. BaseTexture.prototype.releaseInternalTexture = function () {
  17670. if (this._texture) {
  17671. this._scene.getEngine().releaseInternalTexture(this._texture);
  17672. delete this._texture;
  17673. }
  17674. };
  17675. BaseTexture.prototype.dispose = function () {
  17676. // Animations
  17677. this.getScene().stopAnimation(this);
  17678. // Remove from scene
  17679. var index = this._scene.textures.indexOf(this);
  17680. if (index >= 0) {
  17681. this._scene.textures.splice(index, 1);
  17682. }
  17683. if (this._texture === undefined) {
  17684. return;
  17685. }
  17686. // Release
  17687. this.releaseInternalTexture();
  17688. // Callback
  17689. if (this.onDispose) {
  17690. this.onDispose();
  17691. }
  17692. };
  17693. BaseTexture.prototype.serialize = function () {
  17694. var serializationObject = {};
  17695. if (!this.name) {
  17696. return null;
  17697. }
  17698. serializationObject.name = this.name;
  17699. serializationObject.hasAlpha = this.hasAlpha;
  17700. serializationObject.level = this.level;
  17701. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17702. serializationObject.coordinatesMode = this.coordinatesMode;
  17703. serializationObject.wrapU = this.wrapU;
  17704. serializationObject.wrapV = this.wrapV;
  17705. // Animations
  17706. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17707. return serializationObject;
  17708. };
  17709. return BaseTexture;
  17710. })();
  17711. BABYLON.BaseTexture = BaseTexture;
  17712. })(BABYLON || (BABYLON = {}));
  17713. var BABYLON;
  17714. (function (BABYLON) {
  17715. var Texture = (function (_super) {
  17716. __extends(Texture, _super);
  17717. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17718. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17719. if (onLoad === void 0) { onLoad = null; }
  17720. if (onError === void 0) { onError = null; }
  17721. if (buffer === void 0) { buffer = null; }
  17722. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17723. _super.call(this, scene);
  17724. this.uOffset = 0;
  17725. this.vOffset = 0;
  17726. this.uScale = 1.0;
  17727. this.vScale = 1.0;
  17728. this.uAng = 0;
  17729. this.vAng = 0;
  17730. this.wAng = 0;
  17731. this.name = url;
  17732. this.url = url;
  17733. this._noMipmap = noMipmap;
  17734. this._invertY = invertY;
  17735. this._samplingMode = samplingMode;
  17736. this._buffer = buffer;
  17737. this._deleteBuffer = deleteBuffer;
  17738. if (!url) {
  17739. return;
  17740. }
  17741. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17742. if (!this._texture) {
  17743. if (!scene.useDelayedTextureLoading) {
  17744. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17745. if (deleteBuffer) {
  17746. delete this._buffer;
  17747. }
  17748. }
  17749. else {
  17750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17751. this._delayedOnLoad = onLoad;
  17752. this._delayedOnError = onError;
  17753. }
  17754. }
  17755. else {
  17756. BABYLON.Tools.SetImmediate(function () {
  17757. if (onLoad) {
  17758. onLoad();
  17759. }
  17760. });
  17761. }
  17762. }
  17763. Texture.prototype.delayLoad = function () {
  17764. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17765. return;
  17766. }
  17767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17768. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17769. if (!this._texture) {
  17770. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17771. if (this._deleteBuffer) {
  17772. delete this._buffer;
  17773. }
  17774. }
  17775. };
  17776. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17777. if (!this._texture) {
  17778. return;
  17779. }
  17780. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17781. };
  17782. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17783. x *= this.uScale;
  17784. y *= this.vScale;
  17785. x -= 0.5 * this.uScale;
  17786. y -= 0.5 * this.vScale;
  17787. z -= 0.5;
  17788. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17789. t.x += 0.5 * this.uScale + this.uOffset;
  17790. t.y += 0.5 * this.vScale + this.vOffset;
  17791. t.z += 0.5;
  17792. };
  17793. Texture.prototype.getTextureMatrix = function () {
  17794. if (this.uOffset === this._cachedUOffset &&
  17795. this.vOffset === this._cachedVOffset &&
  17796. this.uScale === this._cachedUScale &&
  17797. this.vScale === this._cachedVScale &&
  17798. this.uAng === this._cachedUAng &&
  17799. this.vAng === this._cachedVAng &&
  17800. this.wAng === this._cachedWAng) {
  17801. return this._cachedTextureMatrix;
  17802. }
  17803. this._cachedUOffset = this.uOffset;
  17804. this._cachedVOffset = this.vOffset;
  17805. this._cachedUScale = this.uScale;
  17806. this._cachedVScale = this.vScale;
  17807. this._cachedUAng = this.uAng;
  17808. this._cachedVAng = this.vAng;
  17809. this._cachedWAng = this.wAng;
  17810. if (!this._cachedTextureMatrix) {
  17811. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17812. this._rowGenerationMatrix = new BABYLON.Matrix();
  17813. this._t0 = BABYLON.Vector3.Zero();
  17814. this._t1 = BABYLON.Vector3.Zero();
  17815. this._t2 = BABYLON.Vector3.Zero();
  17816. }
  17817. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17818. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17819. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17820. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17821. this._t1.subtractInPlace(this._t0);
  17822. this._t2.subtractInPlace(this._t0);
  17823. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17824. this._cachedTextureMatrix.m[0] = this._t1.x;
  17825. this._cachedTextureMatrix.m[1] = this._t1.y;
  17826. this._cachedTextureMatrix.m[2] = this._t1.z;
  17827. this._cachedTextureMatrix.m[4] = this._t2.x;
  17828. this._cachedTextureMatrix.m[5] = this._t2.y;
  17829. this._cachedTextureMatrix.m[6] = this._t2.z;
  17830. this._cachedTextureMatrix.m[8] = this._t0.x;
  17831. this._cachedTextureMatrix.m[9] = this._t0.y;
  17832. this._cachedTextureMatrix.m[10] = this._t0.z;
  17833. return this._cachedTextureMatrix;
  17834. };
  17835. Texture.prototype.getReflectionTextureMatrix = function () {
  17836. if (this.uOffset === this._cachedUOffset &&
  17837. this.vOffset === this._cachedVOffset &&
  17838. this.uScale === this._cachedUScale &&
  17839. this.vScale === this._cachedVScale &&
  17840. this.coordinatesMode === this._cachedCoordinatesMode) {
  17841. return this._cachedTextureMatrix;
  17842. }
  17843. if (!this._cachedTextureMatrix) {
  17844. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17845. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17846. }
  17847. this._cachedCoordinatesMode = this.coordinatesMode;
  17848. switch (this.coordinatesMode) {
  17849. case Texture.PLANAR_MODE:
  17850. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17851. this._cachedTextureMatrix[0] = this.uScale;
  17852. this._cachedTextureMatrix[5] = this.vScale;
  17853. this._cachedTextureMatrix[12] = this.uOffset;
  17854. this._cachedTextureMatrix[13] = this.vOffset;
  17855. break;
  17856. case Texture.PROJECTION_MODE:
  17857. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17858. this._projectionModeMatrix.m[0] = 0.5;
  17859. this._projectionModeMatrix.m[5] = -0.5;
  17860. this._projectionModeMatrix.m[10] = 0.0;
  17861. this._projectionModeMatrix.m[12] = 0.5;
  17862. this._projectionModeMatrix.m[13] = 0.5;
  17863. this._projectionModeMatrix.m[14] = 1.0;
  17864. this._projectionModeMatrix.m[15] = 1.0;
  17865. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17866. break;
  17867. default:
  17868. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17869. break;
  17870. }
  17871. return this._cachedTextureMatrix;
  17872. };
  17873. Texture.prototype.clone = function () {
  17874. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17875. // Base texture
  17876. newTexture.hasAlpha = this.hasAlpha;
  17877. newTexture.level = this.level;
  17878. newTexture.wrapU = this.wrapU;
  17879. newTexture.wrapV = this.wrapV;
  17880. newTexture.coordinatesIndex = this.coordinatesIndex;
  17881. newTexture.coordinatesMode = this.coordinatesMode;
  17882. // Texture
  17883. newTexture.uOffset = this.uOffset;
  17884. newTexture.vOffset = this.vOffset;
  17885. newTexture.uScale = this.uScale;
  17886. newTexture.vScale = this.vScale;
  17887. newTexture.uAng = this.uAng;
  17888. newTexture.vAng = this.vAng;
  17889. newTexture.wAng = this.wAng;
  17890. return newTexture;
  17891. };
  17892. Texture.prototype.serialize = function () {
  17893. if (!this.name) {
  17894. return null;
  17895. }
  17896. var serializationObject = _super.prototype.serialize.call(this);
  17897. serializationObject.uOffset = this.uOffset;
  17898. serializationObject.vOffset = this.vOffset;
  17899. serializationObject.uScale = this.uScale;
  17900. serializationObject.vScale = this.vScale;
  17901. serializationObject.uAng = this.uAng;
  17902. serializationObject.vAng = this.vAng;
  17903. serializationObject.wAng = this.wAng;
  17904. return serializationObject;
  17905. };
  17906. // Statics
  17907. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17908. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17909. if (onLoad === void 0) { onLoad = null; }
  17910. if (onError === void 0) { onError = null; }
  17911. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17912. };
  17913. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17914. if (parsedTexture.isCube) {
  17915. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17916. }
  17917. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17918. return null;
  17919. }
  17920. var texture;
  17921. if (parsedTexture.mirrorPlane) {
  17922. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17923. texture._waitingRenderList = parsedTexture.renderList;
  17924. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17925. }
  17926. else if (parsedTexture.isRenderTarget) {
  17927. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17928. texture._waitingRenderList = parsedTexture.renderList;
  17929. }
  17930. else {
  17931. if (parsedTexture.base64String) {
  17932. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17933. }
  17934. else {
  17935. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17936. }
  17937. }
  17938. texture.name = parsedTexture.name;
  17939. texture.hasAlpha = parsedTexture.hasAlpha;
  17940. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17941. texture.level = parsedTexture.level;
  17942. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17943. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17944. texture.uOffset = parsedTexture.uOffset;
  17945. texture.vOffset = parsedTexture.vOffset;
  17946. texture.uScale = parsedTexture.uScale;
  17947. texture.vScale = parsedTexture.vScale;
  17948. texture.uAng = parsedTexture.uAng;
  17949. texture.vAng = parsedTexture.vAng;
  17950. texture.wAng = parsedTexture.wAng;
  17951. texture.wrapU = parsedTexture.wrapU;
  17952. texture.wrapV = parsedTexture.wrapV;
  17953. // Animations
  17954. if (parsedTexture.animations) {
  17955. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17956. var parsedAnimation = parsedTexture.animations[animationIndex];
  17957. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17958. }
  17959. }
  17960. return texture;
  17961. };
  17962. // Constants
  17963. Texture.NEAREST_SAMPLINGMODE = 1;
  17964. Texture.BILINEAR_SAMPLINGMODE = 2;
  17965. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17966. Texture.EXPLICIT_MODE = 0;
  17967. Texture.SPHERICAL_MODE = 1;
  17968. Texture.PLANAR_MODE = 2;
  17969. Texture.CUBIC_MODE = 3;
  17970. Texture.PROJECTION_MODE = 4;
  17971. Texture.SKYBOX_MODE = 5;
  17972. Texture.INVCUBIC_MODE = 6;
  17973. Texture.EQUIRECTANGULAR_MODE = 7;
  17974. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17975. Texture.CLAMP_ADDRESSMODE = 0;
  17976. Texture.WRAP_ADDRESSMODE = 1;
  17977. Texture.MIRROR_ADDRESSMODE = 2;
  17978. return Texture;
  17979. })(BABYLON.BaseTexture);
  17980. BABYLON.Texture = Texture;
  17981. })(BABYLON || (BABYLON = {}));
  17982. var BABYLON;
  17983. (function (BABYLON) {
  17984. var CubeTexture = (function (_super) {
  17985. __extends(CubeTexture, _super);
  17986. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  17987. _super.call(this, scene);
  17988. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17989. this.name = rootUrl;
  17990. this.url = rootUrl;
  17991. this._noMipmap = noMipmap;
  17992. this.hasAlpha = false;
  17993. if (!rootUrl && !files) {
  17994. return;
  17995. }
  17996. this._texture = this._getFromCache(rootUrl, noMipmap);
  17997. if (!files) {
  17998. if (!extensions) {
  17999. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  18000. }
  18001. files = [];
  18002. for (var index = 0; index < extensions.length; index++) {
  18003. files.push(rootUrl + extensions[index]);
  18004. }
  18005. this._extensions = extensions;
  18006. }
  18007. this._files = files;
  18008. if (!this._texture) {
  18009. if (!scene.useDelayedTextureLoading) {
  18010. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  18011. }
  18012. else {
  18013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18014. }
  18015. }
  18016. this.isCube = true;
  18017. this._textureMatrix = BABYLON.Matrix.Identity();
  18018. }
  18019. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  18020. return new CubeTexture("", scene, null, noMipmap, files);
  18021. };
  18022. CubeTexture.prototype.clone = function () {
  18023. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  18024. // Base texture
  18025. newTexture.level = this.level;
  18026. newTexture.wrapU = this.wrapU;
  18027. newTexture.wrapV = this.wrapV;
  18028. newTexture.coordinatesIndex = this.coordinatesIndex;
  18029. newTexture.coordinatesMode = this.coordinatesMode;
  18030. return newTexture;
  18031. };
  18032. // Methods
  18033. CubeTexture.prototype.delayLoad = function () {
  18034. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18035. return;
  18036. }
  18037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18038. this._texture = this._getFromCache(this.url, this._noMipmap);
  18039. if (!this._texture) {
  18040. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18041. }
  18042. };
  18043. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18044. return this._textureMatrix;
  18045. };
  18046. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18047. var texture = null;
  18048. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18049. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18050. texture.name = parsedTexture.name;
  18051. texture.hasAlpha = parsedTexture.hasAlpha;
  18052. texture.level = parsedTexture.level;
  18053. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18054. }
  18055. return texture;
  18056. };
  18057. CubeTexture.prototype.serialize = function () {
  18058. if (!this.name) {
  18059. return null;
  18060. }
  18061. var serializationObject = {};
  18062. serializationObject.name = this.name;
  18063. serializationObject.hasAlpha = this.hasAlpha;
  18064. serializationObject.isCube = true;
  18065. serializationObject.level = this.level;
  18066. serializationObject.coordinatesMode = this.coordinatesMode;
  18067. return serializationObject;
  18068. };
  18069. return CubeTexture;
  18070. })(BABYLON.BaseTexture);
  18071. BABYLON.CubeTexture = CubeTexture;
  18072. })(BABYLON || (BABYLON = {}));
  18073. var BABYLON;
  18074. (function (BABYLON) {
  18075. var RenderTargetTexture = (function (_super) {
  18076. __extends(RenderTargetTexture, _super);
  18077. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18078. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18079. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18080. if (isCube === void 0) { isCube = false; }
  18081. _super.call(this, null, scene, !generateMipMaps);
  18082. this.isCube = isCube;
  18083. this.renderList = new Array();
  18084. this.renderParticles = true;
  18085. this.renderSprites = false;
  18086. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18087. this._currentRefreshId = -1;
  18088. this._refreshRate = 1;
  18089. this.name = name;
  18090. this.isRenderTarget = true;
  18091. this._size = size;
  18092. this._generateMipMaps = generateMipMaps;
  18093. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18094. if (isCube) {
  18095. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18096. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18097. this._textureMatrix = BABYLON.Matrix.Identity();
  18098. }
  18099. else {
  18100. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18101. }
  18102. // Rendering groups
  18103. this._renderingManager = new BABYLON.RenderingManager(scene);
  18104. }
  18105. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18106. get: function () {
  18107. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18113. get: function () {
  18114. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18115. },
  18116. enumerable: true,
  18117. configurable: true
  18118. });
  18119. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18120. get: function () {
  18121. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18122. },
  18123. enumerable: true,
  18124. configurable: true
  18125. });
  18126. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18127. this._currentRefreshId = -1;
  18128. };
  18129. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18130. get: function () {
  18131. return this._refreshRate;
  18132. },
  18133. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18134. set: function (value) {
  18135. this._refreshRate = value;
  18136. this.resetRefreshCounter();
  18137. },
  18138. enumerable: true,
  18139. configurable: true
  18140. });
  18141. RenderTargetTexture.prototype._shouldRender = function () {
  18142. if (this._currentRefreshId === -1) {
  18143. this._currentRefreshId = 1;
  18144. return true;
  18145. }
  18146. if (this.refreshRate === this._currentRefreshId) {
  18147. this._currentRefreshId = 1;
  18148. return true;
  18149. }
  18150. this._currentRefreshId++;
  18151. return false;
  18152. };
  18153. RenderTargetTexture.prototype.isReady = function () {
  18154. if (!this.getScene().renderTargetsEnabled) {
  18155. return false;
  18156. }
  18157. return _super.prototype.isReady.call(this);
  18158. };
  18159. RenderTargetTexture.prototype.getRenderSize = function () {
  18160. return this._size;
  18161. };
  18162. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18163. get: function () {
  18164. return true;
  18165. },
  18166. enumerable: true,
  18167. configurable: true
  18168. });
  18169. RenderTargetTexture.prototype.scale = function (ratio) {
  18170. var newSize = this._size * ratio;
  18171. this.resize(newSize, this._generateMipMaps);
  18172. };
  18173. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18174. if (this.isCube) {
  18175. return this._textureMatrix;
  18176. }
  18177. return _super.prototype.getReflectionTextureMatrix.call(this);
  18178. };
  18179. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18180. this.releaseInternalTexture();
  18181. if (this.isCube) {
  18182. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18183. }
  18184. else {
  18185. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18186. }
  18187. };
  18188. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18189. var scene = this.getScene();
  18190. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18191. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18192. }
  18193. if (this._waitingRenderList) {
  18194. this.renderList = [];
  18195. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18196. var id = this._waitingRenderList[index];
  18197. this.renderList.push(scene.getMeshByID(id));
  18198. }
  18199. delete this._waitingRenderList;
  18200. }
  18201. if (this.renderList && this.renderList.length === 0) {
  18202. return;
  18203. }
  18204. // Prepare renderingManager
  18205. this._renderingManager.reset();
  18206. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18207. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18208. var mesh = currentRenderList[meshIndex];
  18209. if (mesh) {
  18210. if (!mesh.isReady()) {
  18211. // Reset _currentRefreshId
  18212. this.resetRefreshCounter();
  18213. continue;
  18214. }
  18215. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18216. mesh._activate(scene.getRenderId());
  18217. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18218. var subMesh = mesh.subMeshes[subIndex];
  18219. scene._activeIndices += subMesh.indexCount;
  18220. this._renderingManager.dispatch(subMesh);
  18221. }
  18222. }
  18223. }
  18224. }
  18225. if (this.isCube) {
  18226. for (var face = 0; face < 6; face++) {
  18227. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18228. scene.incrementRenderId();
  18229. }
  18230. }
  18231. else {
  18232. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18233. }
  18234. if (this.onAfterUnbind) {
  18235. this.onAfterUnbind();
  18236. }
  18237. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18238. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18239. }
  18240. scene.resetCachedMaterial();
  18241. };
  18242. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18243. var scene = this.getScene();
  18244. var engine = scene.getEngine();
  18245. // Bind
  18246. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18247. if (this.isCube) {
  18248. engine.bindFramebuffer(this._texture, faceIndex);
  18249. }
  18250. else {
  18251. engine.bindFramebuffer(this._texture);
  18252. }
  18253. }
  18254. if (this.onBeforeRender) {
  18255. this.onBeforeRender(faceIndex);
  18256. }
  18257. // Clear
  18258. if (this.onClear) {
  18259. this.onClear(engine);
  18260. }
  18261. else {
  18262. engine.clear(scene.clearColor, true, true);
  18263. }
  18264. if (!this._doNotChangeAspectRatio) {
  18265. scene.updateTransformMatrix(true);
  18266. }
  18267. // Render
  18268. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18269. if (useCameraPostProcess) {
  18270. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18271. }
  18272. if (!this._doNotChangeAspectRatio) {
  18273. scene.updateTransformMatrix(true);
  18274. }
  18275. if (this.onAfterRender) {
  18276. this.onAfterRender(faceIndex);
  18277. }
  18278. // Dump ?
  18279. if (dumpForDebug) {
  18280. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18281. }
  18282. // Unbind
  18283. if (!this.isCube || faceIndex === 5) {
  18284. if (this.isCube) {
  18285. if (faceIndex === 5) {
  18286. engine.generateMipMapsForCubemap(this._texture);
  18287. }
  18288. }
  18289. engine.unBindFramebuffer(this._texture, this.isCube);
  18290. }
  18291. };
  18292. RenderTargetTexture.prototype.clone = function () {
  18293. var textureSize = this.getSize();
  18294. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18295. // Base texture
  18296. newTexture.hasAlpha = this.hasAlpha;
  18297. newTexture.level = this.level;
  18298. // RenderTarget Texture
  18299. newTexture.coordinatesMode = this.coordinatesMode;
  18300. newTexture.renderList = this.renderList.slice(0);
  18301. return newTexture;
  18302. };
  18303. RenderTargetTexture.prototype.serialize = function () {
  18304. if (!this.name) {
  18305. return null;
  18306. }
  18307. var serializationObject = _super.prototype.serialize.call(this);
  18308. serializationObject.renderTargetSize = this.getRenderSize();
  18309. serializationObject.renderList = [];
  18310. for (var index = 0; index < this.renderList.length; index++) {
  18311. serializationObject.renderList.push(this.renderList[index].id);
  18312. }
  18313. return serializationObject;
  18314. };
  18315. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18316. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18317. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18318. return RenderTargetTexture;
  18319. })(BABYLON.Texture);
  18320. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18321. })(BABYLON || (BABYLON = {}));
  18322. var BABYLON;
  18323. (function (BABYLON) {
  18324. var ProceduralTexture = (function (_super) {
  18325. __extends(ProceduralTexture, _super);
  18326. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18327. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18328. if (isCube === void 0) { isCube = false; }
  18329. _super.call(this, null, scene, !generateMipMaps);
  18330. this.isCube = isCube;
  18331. this.isEnabled = true;
  18332. this._currentRefreshId = -1;
  18333. this._refreshRate = 1;
  18334. this._vertexDeclaration = [2];
  18335. this._vertexStrideSize = 2 * 4;
  18336. this._uniforms = new Array();
  18337. this._samplers = new Array();
  18338. this._textures = new Array();
  18339. this._floats = new Array();
  18340. this._floatsArrays = {};
  18341. this._colors3 = new Array();
  18342. this._colors4 = new Array();
  18343. this._vectors2 = new Array();
  18344. this._vectors3 = new Array();
  18345. this._matrices = new Array();
  18346. this._fallbackTextureUsed = false;
  18347. scene._proceduralTextures.push(this);
  18348. this.name = name;
  18349. this.isRenderTarget = true;
  18350. this._size = size;
  18351. this._generateMipMaps = generateMipMaps;
  18352. this.setFragment(fragment);
  18353. this._fallbackTexture = fallbackTexture;
  18354. if (isCube) {
  18355. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18356. this.setFloat("face", 0);
  18357. }
  18358. else {
  18359. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18360. }
  18361. // VBO
  18362. var vertices = [];
  18363. vertices.push(1, 1);
  18364. vertices.push(-1, 1);
  18365. vertices.push(-1, -1);
  18366. vertices.push(1, -1);
  18367. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18368. // Indices
  18369. var indices = [];
  18370. indices.push(0);
  18371. indices.push(1);
  18372. indices.push(2);
  18373. indices.push(0);
  18374. indices.push(2);
  18375. indices.push(3);
  18376. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18377. }
  18378. ProceduralTexture.prototype.reset = function () {
  18379. if (this._effect === undefined) {
  18380. return;
  18381. }
  18382. var engine = this.getScene().getEngine();
  18383. engine._releaseEffect(this._effect);
  18384. };
  18385. ProceduralTexture.prototype.isReady = function () {
  18386. var _this = this;
  18387. var engine = this.getScene().getEngine();
  18388. var shaders;
  18389. if (!this._fragment) {
  18390. return false;
  18391. }
  18392. if (this._fallbackTextureUsed) {
  18393. return true;
  18394. }
  18395. if (this._fragment.fragmentElement !== undefined) {
  18396. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18397. }
  18398. else {
  18399. shaders = { vertex: "procedural", fragment: this._fragment };
  18400. }
  18401. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18402. _this.releaseInternalTexture();
  18403. if (_this._fallbackTexture) {
  18404. _this._texture = _this._fallbackTexture._texture;
  18405. _this._texture.references++;
  18406. }
  18407. _this._fallbackTextureUsed = true;
  18408. });
  18409. return this._effect.isReady();
  18410. };
  18411. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18412. this._currentRefreshId = -1;
  18413. };
  18414. ProceduralTexture.prototype.setFragment = function (fragment) {
  18415. this._fragment = fragment;
  18416. };
  18417. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18418. get: function () {
  18419. return this._refreshRate;
  18420. },
  18421. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18422. set: function (value) {
  18423. this._refreshRate = value;
  18424. this.resetRefreshCounter();
  18425. },
  18426. enumerable: true,
  18427. configurable: true
  18428. });
  18429. ProceduralTexture.prototype._shouldRender = function () {
  18430. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18431. return false;
  18432. }
  18433. if (this._fallbackTextureUsed) {
  18434. return false;
  18435. }
  18436. if (this._currentRefreshId === -1) {
  18437. this._currentRefreshId = 1;
  18438. return true;
  18439. }
  18440. if (this.refreshRate === this._currentRefreshId) {
  18441. this._currentRefreshId = 1;
  18442. return true;
  18443. }
  18444. this._currentRefreshId++;
  18445. return false;
  18446. };
  18447. ProceduralTexture.prototype.getRenderSize = function () {
  18448. return this._size;
  18449. };
  18450. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18451. if (this._fallbackTextureUsed) {
  18452. return;
  18453. }
  18454. this.releaseInternalTexture();
  18455. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18456. };
  18457. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18458. if (this._uniforms.indexOf(uniformName) === -1) {
  18459. this._uniforms.push(uniformName);
  18460. }
  18461. };
  18462. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18463. if (this._samplers.indexOf(name) === -1) {
  18464. this._samplers.push(name);
  18465. }
  18466. this._textures[name] = texture;
  18467. return this;
  18468. };
  18469. ProceduralTexture.prototype.setFloat = function (name, value) {
  18470. this._checkUniform(name);
  18471. this._floats[name] = value;
  18472. return this;
  18473. };
  18474. ProceduralTexture.prototype.setFloats = function (name, value) {
  18475. this._checkUniform(name);
  18476. this._floatsArrays[name] = value;
  18477. return this;
  18478. };
  18479. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18480. this._checkUniform(name);
  18481. this._colors3[name] = value;
  18482. return this;
  18483. };
  18484. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18485. this._checkUniform(name);
  18486. this._colors4[name] = value;
  18487. return this;
  18488. };
  18489. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18490. this._checkUniform(name);
  18491. this._vectors2[name] = value;
  18492. return this;
  18493. };
  18494. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18495. this._checkUniform(name);
  18496. this._vectors3[name] = value;
  18497. return this;
  18498. };
  18499. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18500. this._checkUniform(name);
  18501. this._matrices[name] = value;
  18502. return this;
  18503. };
  18504. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18505. var scene = this.getScene();
  18506. var engine = scene.getEngine();
  18507. // Render
  18508. engine.enableEffect(this._effect);
  18509. engine.setState(false);
  18510. // Texture
  18511. for (var name in this._textures) {
  18512. this._effect.setTexture(name, this._textures[name]);
  18513. }
  18514. // Float
  18515. for (name in this._floats) {
  18516. this._effect.setFloat(name, this._floats[name]);
  18517. }
  18518. // Floats
  18519. for (name in this._floatsArrays) {
  18520. this._effect.setArray(name, this._floatsArrays[name]);
  18521. }
  18522. // Color3
  18523. for (name in this._colors3) {
  18524. this._effect.setColor3(name, this._colors3[name]);
  18525. }
  18526. // Color4
  18527. for (name in this._colors4) {
  18528. var color = this._colors4[name];
  18529. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18530. }
  18531. // Vector2
  18532. for (name in this._vectors2) {
  18533. this._effect.setVector2(name, this._vectors2[name]);
  18534. }
  18535. // Vector3
  18536. for (name in this._vectors3) {
  18537. this._effect.setVector3(name, this._vectors3[name]);
  18538. }
  18539. // Matrix
  18540. for (name in this._matrices) {
  18541. this._effect.setMatrix(name, this._matrices[name]);
  18542. }
  18543. // VBOs
  18544. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18545. if (this.isCube) {
  18546. for (var face = 0; face < 6; face++) {
  18547. engine.bindFramebuffer(this._texture, face);
  18548. this._effect.setFloat("face", face);
  18549. // Clear
  18550. engine.clear(scene.clearColor, true, true);
  18551. // Draw order
  18552. engine.draw(true, 0, 6);
  18553. // Mipmaps
  18554. if (face === 5) {
  18555. engine.generateMipMapsForCubemap(this._texture);
  18556. }
  18557. }
  18558. }
  18559. else {
  18560. engine.bindFramebuffer(this._texture);
  18561. // Clear
  18562. engine.clear(scene.clearColor, true, true);
  18563. // Draw order
  18564. engine.draw(true, 0, 6);
  18565. }
  18566. // Unbind
  18567. engine.unBindFramebuffer(this._texture, this.isCube);
  18568. if (this.onGenerated) {
  18569. this.onGenerated();
  18570. }
  18571. };
  18572. ProceduralTexture.prototype.clone = function () {
  18573. var textureSize = this.getSize();
  18574. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18575. // Base texture
  18576. newTexture.hasAlpha = this.hasAlpha;
  18577. newTexture.level = this.level;
  18578. // RenderTarget Texture
  18579. newTexture.coordinatesMode = this.coordinatesMode;
  18580. return newTexture;
  18581. };
  18582. ProceduralTexture.prototype.dispose = function () {
  18583. var index = this.getScene()._proceduralTextures.indexOf(this);
  18584. if (index >= 0) {
  18585. this.getScene()._proceduralTextures.splice(index, 1);
  18586. }
  18587. _super.prototype.dispose.call(this);
  18588. };
  18589. return ProceduralTexture;
  18590. })(BABYLON.Texture);
  18591. BABYLON.ProceduralTexture = ProceduralTexture;
  18592. })(BABYLON || (BABYLON = {}));
  18593. var BABYLON;
  18594. (function (BABYLON) {
  18595. var MirrorTexture = (function (_super) {
  18596. __extends(MirrorTexture, _super);
  18597. function MirrorTexture(name, size, scene, generateMipMaps) {
  18598. var _this = this;
  18599. _super.call(this, name, size, scene, generateMipMaps, true);
  18600. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18601. this._transformMatrix = BABYLON.Matrix.Zero();
  18602. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18603. this.onBeforeRender = function () {
  18604. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18605. _this._savedViewMatrix = scene.getViewMatrix();
  18606. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18607. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18608. scene.clipPlane = _this.mirrorPlane;
  18609. scene.getEngine().cullBackFaces = false;
  18610. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18611. };
  18612. this.onAfterRender = function () {
  18613. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18614. scene.getEngine().cullBackFaces = true;
  18615. scene._mirroredCameraPosition = null;
  18616. delete scene.clipPlane;
  18617. };
  18618. }
  18619. MirrorTexture.prototype.clone = function () {
  18620. var textureSize = this.getSize();
  18621. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18622. // Base texture
  18623. newTexture.hasAlpha = this.hasAlpha;
  18624. newTexture.level = this.level;
  18625. // Mirror Texture
  18626. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18627. newTexture.renderList = this.renderList.slice(0);
  18628. return newTexture;
  18629. };
  18630. MirrorTexture.prototype.serialize = function () {
  18631. if (!this.name) {
  18632. return null;
  18633. }
  18634. var serializationObject = _super.prototype.serialize.call(this);
  18635. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18636. return serializationObject;
  18637. };
  18638. return MirrorTexture;
  18639. })(BABYLON.RenderTargetTexture);
  18640. BABYLON.MirrorTexture = MirrorTexture;
  18641. })(BABYLON || (BABYLON = {}));
  18642. var BABYLON;
  18643. (function (BABYLON) {
  18644. /**
  18645. * Creates a refraction texture used by refraction channel of the standard material.
  18646. * @param name the texture name
  18647. * @param size size of the underlying texture
  18648. * @param scene root scene
  18649. */
  18650. var RefractionTexture = (function (_super) {
  18651. __extends(RefractionTexture, _super);
  18652. function RefractionTexture(name, size, scene, generateMipMaps) {
  18653. var _this = this;
  18654. _super.call(this, name, size, scene, generateMipMaps, true);
  18655. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18656. this.depth = 2.0;
  18657. this.onBeforeRender = function () {
  18658. scene.clipPlane = _this.refractionPlane;
  18659. };
  18660. this.onAfterRender = function () {
  18661. delete scene.clipPlane;
  18662. };
  18663. }
  18664. RefractionTexture.prototype.clone = function () {
  18665. var textureSize = this.getSize();
  18666. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18667. // Base texture
  18668. newTexture.hasAlpha = this.hasAlpha;
  18669. newTexture.level = this.level;
  18670. // Refraction Texture
  18671. newTexture.refractionPlane = this.refractionPlane.clone();
  18672. newTexture.renderList = this.renderList.slice(0);
  18673. newTexture.depth = this.depth;
  18674. return newTexture;
  18675. };
  18676. RefractionTexture.prototype.serialize = function () {
  18677. if (!this.name) {
  18678. return null;
  18679. }
  18680. var serializationObject = _super.prototype.serialize.call(this);
  18681. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18682. serializationObject.depth = this.depth;
  18683. return serializationObject;
  18684. };
  18685. return RefractionTexture;
  18686. })(BABYLON.RenderTargetTexture);
  18687. BABYLON.RefractionTexture = RefractionTexture;
  18688. })(BABYLON || (BABYLON = {}));
  18689. var BABYLON;
  18690. (function (BABYLON) {
  18691. var DynamicTexture = (function (_super) {
  18692. __extends(DynamicTexture, _super);
  18693. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18695. _super.call(this, null, scene, !generateMipMaps);
  18696. this.name = name;
  18697. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18698. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18699. this._generateMipMaps = generateMipMaps;
  18700. if (options.getContext) {
  18701. this._canvas = options;
  18702. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18703. }
  18704. else {
  18705. this._canvas = document.createElement("canvas");
  18706. if (options.width) {
  18707. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18708. }
  18709. else {
  18710. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18711. }
  18712. }
  18713. var textureSize = this.getSize();
  18714. this._canvas.width = textureSize.width;
  18715. this._canvas.height = textureSize.height;
  18716. this._context = this._canvas.getContext("2d");
  18717. }
  18718. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18719. get: function () {
  18720. return true;
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. DynamicTexture.prototype.scale = function (ratio) {
  18726. var textureSize = this.getSize();
  18727. textureSize.width *= ratio;
  18728. textureSize.height *= ratio;
  18729. this._canvas.width = textureSize.width;
  18730. this._canvas.height = textureSize.height;
  18731. this.releaseInternalTexture();
  18732. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18733. };
  18734. DynamicTexture.prototype.getContext = function () {
  18735. return this._context;
  18736. };
  18737. DynamicTexture.prototype.clear = function () {
  18738. var size = this.getSize();
  18739. this._context.fillRect(0, 0, size.width, size.height);
  18740. };
  18741. DynamicTexture.prototype.update = function (invertY) {
  18742. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18743. };
  18744. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18745. if (update === void 0) { update = true; }
  18746. var size = this.getSize();
  18747. if (clearColor) {
  18748. this._context.fillStyle = clearColor;
  18749. this._context.fillRect(0, 0, size.width, size.height);
  18750. }
  18751. this._context.font = font;
  18752. if (x === null) {
  18753. var textSize = this._context.measureText(text);
  18754. x = (size.width - textSize.width) / 2;
  18755. }
  18756. this._context.fillStyle = color;
  18757. this._context.fillText(text, x, y);
  18758. if (update) {
  18759. this.update(invertY);
  18760. }
  18761. };
  18762. DynamicTexture.prototype.clone = function () {
  18763. var textureSize = this.getSize();
  18764. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18765. // Base texture
  18766. newTexture.hasAlpha = this.hasAlpha;
  18767. newTexture.level = this.level;
  18768. // Dynamic Texture
  18769. newTexture.wrapU = this.wrapU;
  18770. newTexture.wrapV = this.wrapV;
  18771. return newTexture;
  18772. };
  18773. return DynamicTexture;
  18774. })(BABYLON.Texture);
  18775. BABYLON.DynamicTexture = DynamicTexture;
  18776. })(BABYLON || (BABYLON = {}));
  18777. var BABYLON;
  18778. (function (BABYLON) {
  18779. var VideoTexture = (function (_super) {
  18780. __extends(VideoTexture, _super);
  18781. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18782. var _this = this;
  18783. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18784. if (invertY === void 0) { invertY = false; }
  18785. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18786. _super.call(this, null, scene, !generateMipMaps, invertY);
  18787. this._autoLaunch = true;
  18788. this.name = name;
  18789. this.video = document.createElement("video");
  18790. this.video.autoplay = false;
  18791. this.video.loop = true;
  18792. this.video.addEventListener("canplaythrough", function () {
  18793. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18794. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18795. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18796. }
  18797. else {
  18798. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18799. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18800. generateMipMaps = false;
  18801. }
  18802. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18803. _this._texture.isReady = true;
  18804. });
  18805. urls.forEach(function (url) {
  18806. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18807. var source = document.createElement("source");
  18808. source.src = url;
  18809. _this.video.appendChild(source);
  18810. });
  18811. this._lastUpdate = BABYLON.Tools.Now;
  18812. }
  18813. VideoTexture.prototype.update = function () {
  18814. if (this._autoLaunch) {
  18815. this._autoLaunch = false;
  18816. this.video.play();
  18817. }
  18818. var now = BABYLON.Tools.Now;
  18819. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18820. return false;
  18821. }
  18822. this._lastUpdate = now;
  18823. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18824. return true;
  18825. };
  18826. return VideoTexture;
  18827. })(BABYLON.Texture);
  18828. BABYLON.VideoTexture = VideoTexture;
  18829. })(BABYLON || (BABYLON = {}));
  18830. var BABYLON;
  18831. (function (BABYLON) {
  18832. var CustomProceduralTexture = (function (_super) {
  18833. __extends(CustomProceduralTexture, _super);
  18834. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18835. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18836. this._animate = true;
  18837. this._time = 0;
  18838. this._texturePath = texturePath;
  18839. //Try to load json
  18840. this.loadJson(texturePath);
  18841. this.refreshRate = 1;
  18842. }
  18843. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18844. var _this = this;
  18845. var that = this;
  18846. function noConfigFile() {
  18847. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18848. try {
  18849. that.setFragment(that._texturePath);
  18850. }
  18851. catch (ex) {
  18852. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18853. }
  18854. }
  18855. var configFileUrl = jsonUrl + "/config.json";
  18856. var xhr = new XMLHttpRequest();
  18857. xhr.open("GET", configFileUrl, true);
  18858. xhr.addEventListener("load", function () {
  18859. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18860. try {
  18861. _this._config = JSON.parse(xhr.response);
  18862. _this.updateShaderUniforms();
  18863. _this.updateTextures();
  18864. _this.setFragment(_this._texturePath + "/custom");
  18865. _this._animate = _this._config.animate;
  18866. _this.refreshRate = _this._config.refreshrate;
  18867. }
  18868. catch (ex) {
  18869. noConfigFile();
  18870. }
  18871. }
  18872. else {
  18873. noConfigFile();
  18874. }
  18875. }, false);
  18876. xhr.addEventListener("error", function () {
  18877. noConfigFile();
  18878. }, false);
  18879. try {
  18880. xhr.send();
  18881. }
  18882. catch (ex) {
  18883. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18884. }
  18885. };
  18886. CustomProceduralTexture.prototype.isReady = function () {
  18887. if (!_super.prototype.isReady.call(this)) {
  18888. return false;
  18889. }
  18890. for (var name in this._textures) {
  18891. var texture = this._textures[name];
  18892. if (!texture.isReady()) {
  18893. return false;
  18894. }
  18895. }
  18896. return true;
  18897. };
  18898. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18899. if (this._animate) {
  18900. this._time += this.getScene().getAnimationRatio() * 0.03;
  18901. this.updateShaderUniforms();
  18902. }
  18903. _super.prototype.render.call(this, useCameraPostProcess);
  18904. };
  18905. CustomProceduralTexture.prototype.updateTextures = function () {
  18906. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18907. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18908. }
  18909. };
  18910. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18911. if (this._config) {
  18912. for (var j = 0; j < this._config.uniforms.length; j++) {
  18913. var uniform = this._config.uniforms[j];
  18914. switch (uniform.type) {
  18915. case "float":
  18916. this.setFloat(uniform.name, uniform.value);
  18917. break;
  18918. case "color3":
  18919. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18920. break;
  18921. case "color4":
  18922. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18923. break;
  18924. case "vector2":
  18925. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18926. break;
  18927. case "vector3":
  18928. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18929. break;
  18930. }
  18931. }
  18932. }
  18933. this.setFloat("time", this._time);
  18934. };
  18935. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18936. get: function () {
  18937. return this._animate;
  18938. },
  18939. set: function (value) {
  18940. this._animate = value;
  18941. },
  18942. enumerable: true,
  18943. configurable: true
  18944. });
  18945. return CustomProceduralTexture;
  18946. })(BABYLON.ProceduralTexture);
  18947. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18948. })(BABYLON || (BABYLON = {}));
  18949. var BABYLON;
  18950. (function (BABYLON) {
  18951. var EffectFallbacks = (function () {
  18952. function EffectFallbacks() {
  18953. this._defines = {};
  18954. this._currentRank = 32;
  18955. this._maxRank = -1;
  18956. }
  18957. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18958. if (!this._defines[rank]) {
  18959. if (rank < this._currentRank) {
  18960. this._currentRank = rank;
  18961. }
  18962. if (rank > this._maxRank) {
  18963. this._maxRank = rank;
  18964. }
  18965. this._defines[rank] = new Array();
  18966. }
  18967. this._defines[rank].push(define);
  18968. };
  18969. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18970. this._meshRank = rank;
  18971. this._mesh = mesh;
  18972. if (rank > this._maxRank) {
  18973. this._maxRank = rank;
  18974. }
  18975. };
  18976. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18977. get: function () {
  18978. return this._currentRank <= this._maxRank;
  18979. },
  18980. enumerable: true,
  18981. configurable: true
  18982. });
  18983. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18984. var currentFallbacks = this._defines[this._currentRank];
  18985. for (var index = 0; index < currentFallbacks.length; index++) {
  18986. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18987. }
  18988. if (this._mesh && this._currentRank === this._meshRank) {
  18989. this._mesh.computeBonesUsingShaders = false;
  18990. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18991. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18992. }
  18993. this._currentRank++;
  18994. return currentDefines;
  18995. };
  18996. return EffectFallbacks;
  18997. })();
  18998. BABYLON.EffectFallbacks = EffectFallbacks;
  18999. var Effect = (function () {
  19000. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  19001. var _this = this;
  19002. this._isReady = false;
  19003. this._compilationError = "";
  19004. this._valueCache = [];
  19005. this._engine = engine;
  19006. this.name = baseName;
  19007. this.defines = defines;
  19008. this._uniformsNames = uniformsNames.concat(samplers);
  19009. this._samplers = samplers;
  19010. this._attributesNames = attributesNames;
  19011. this.onError = onError;
  19012. this.onCompiled = onCompiled;
  19013. var vertexSource;
  19014. var fragmentSource;
  19015. if (baseName.vertexElement) {
  19016. vertexSource = document.getElementById(baseName.vertexElement);
  19017. if (!vertexSource) {
  19018. vertexSource = baseName.vertexElement;
  19019. }
  19020. }
  19021. else {
  19022. vertexSource = baseName.vertex || baseName;
  19023. }
  19024. if (baseName.fragmentElement) {
  19025. fragmentSource = document.getElementById(baseName.fragmentElement);
  19026. if (!fragmentSource) {
  19027. fragmentSource = baseName.fragmentElement;
  19028. }
  19029. }
  19030. else {
  19031. fragmentSource = baseName.fragment || baseName;
  19032. }
  19033. this._loadVertexShader(vertexSource, function (vertexCode) {
  19034. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19035. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19036. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19037. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19038. });
  19039. });
  19040. });
  19041. });
  19042. }
  19043. // Properties
  19044. Effect.prototype.isReady = function () {
  19045. return this._isReady;
  19046. };
  19047. Effect.prototype.getProgram = function () {
  19048. return this._program;
  19049. };
  19050. Effect.prototype.getAttributesNames = function () {
  19051. return this._attributesNames;
  19052. };
  19053. Effect.prototype.getAttributeLocation = function (index) {
  19054. return this._attributes[index];
  19055. };
  19056. Effect.prototype.getAttributeLocationByName = function (name) {
  19057. var index = this._attributesNames.indexOf(name);
  19058. return this._attributes[index];
  19059. };
  19060. Effect.prototype.getAttributesCount = function () {
  19061. return this._attributes.length;
  19062. };
  19063. Effect.prototype.getUniformIndex = function (uniformName) {
  19064. return this._uniformsNames.indexOf(uniformName);
  19065. };
  19066. Effect.prototype.getUniform = function (uniformName) {
  19067. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19068. };
  19069. Effect.prototype.getSamplers = function () {
  19070. return this._samplers;
  19071. };
  19072. Effect.prototype.getCompilationError = function () {
  19073. return this._compilationError;
  19074. };
  19075. // Methods
  19076. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19077. // DOM element ?
  19078. if (vertex instanceof HTMLElement) {
  19079. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19080. callback(vertexCode);
  19081. return;
  19082. }
  19083. // Is in local store ?
  19084. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19085. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19086. return;
  19087. }
  19088. var vertexShaderUrl;
  19089. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19090. vertexShaderUrl = vertex;
  19091. }
  19092. else {
  19093. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19094. }
  19095. // Vertex shader
  19096. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19097. };
  19098. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19099. // DOM element ?
  19100. if (fragment instanceof HTMLElement) {
  19101. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19102. callback(fragmentCode);
  19103. return;
  19104. }
  19105. // Is in local store ?
  19106. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19107. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19108. return;
  19109. }
  19110. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19111. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19112. return;
  19113. }
  19114. var fragmentShaderUrl;
  19115. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19116. fragmentShaderUrl = fragment;
  19117. }
  19118. else {
  19119. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19120. }
  19121. // Fragment shader
  19122. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19123. };
  19124. Effect.prototype._dumpShadersName = function () {
  19125. if (this.name.vertexElement) {
  19126. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19127. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19128. }
  19129. else if (this.name.vertex) {
  19130. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19131. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19132. }
  19133. else {
  19134. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19135. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19136. }
  19137. };
  19138. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19139. var _this = this;
  19140. var regex = /#include<(.+)>(\((.*)\))*/g;
  19141. var match = regex.exec(sourceCode);
  19142. var returnValue = new String(sourceCode);
  19143. while (match != null) {
  19144. var includeFile = match[1];
  19145. if (Effect.IncludesShadersStore[includeFile]) {
  19146. // Substitution
  19147. var includeContent = Effect.IncludesShadersStore[includeFile];
  19148. if (match[2]) {
  19149. var splits = match[2].substr(1, match[2].length - 2).split(",");
  19150. for (var index = 0; index < splits.length; index += 2) {
  19151. var source = new RegExp(splits[index], "g");
  19152. var dest = splits[index + 1];
  19153. includeContent = includeContent.replace(source, dest);
  19154. }
  19155. }
  19156. // Replace
  19157. returnValue = returnValue.replace(match[0], includeContent);
  19158. }
  19159. else {
  19160. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19161. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19162. Effect.IncludesShadersStore[includeFile] = fileContent;
  19163. _this._processIncludes(returnValue, callback);
  19164. });
  19165. return;
  19166. }
  19167. match = regex.exec(sourceCode);
  19168. }
  19169. callback(returnValue);
  19170. };
  19171. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19172. try {
  19173. var engine = this._engine;
  19174. // Precision
  19175. if (!engine.getCaps().highPrecisionShaderSupported) {
  19176. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19177. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19178. }
  19179. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19180. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19181. this._attributes = engine.getAttributes(this._program, attributesNames);
  19182. for (var index = 0; index < this._samplers.length; index++) {
  19183. var sampler = this.getUniform(this._samplers[index]);
  19184. if (sampler == null) {
  19185. this._samplers.splice(index, 1);
  19186. index--;
  19187. }
  19188. }
  19189. engine.bindSamplers(this);
  19190. this._isReady = true;
  19191. if (this.onCompiled) {
  19192. this.onCompiled(this);
  19193. }
  19194. }
  19195. catch (e) {
  19196. // Is it a problem with precision?
  19197. if (e.message.indexOf("highp") !== -1) {
  19198. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19199. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19200. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19201. return;
  19202. }
  19203. // Let's go through fallbacks then
  19204. if (fallbacks && fallbacks.isMoreFallbacks) {
  19205. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19206. this._dumpShadersName();
  19207. defines = fallbacks.reduce(defines);
  19208. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19209. }
  19210. else {
  19211. BABYLON.Tools.Error("Unable to compile effect: ");
  19212. this._dumpShadersName();
  19213. BABYLON.Tools.Error("Defines: " + defines);
  19214. BABYLON.Tools.Error("Error: " + e.message);
  19215. this._compilationError = e.message;
  19216. if (this.onError) {
  19217. this.onError(this, this._compilationError);
  19218. }
  19219. }
  19220. }
  19221. };
  19222. Object.defineProperty(Effect.prototype, "isSupported", {
  19223. get: function () {
  19224. return this._compilationError === "";
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Effect.prototype._bindTexture = function (channel, texture) {
  19230. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19231. };
  19232. Effect.prototype.setTexture = function (channel, texture) {
  19233. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19234. };
  19235. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19236. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19237. };
  19238. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19239. if (!this._valueCache[uniformName]) {
  19240. this._valueCache[uniformName] = new BABYLON.Matrix();
  19241. }
  19242. for (var index = 0; index < 16; index++) {
  19243. this._valueCache[uniformName].m[index] = matrix.m[index];
  19244. }
  19245. };
  19246. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19247. if (!this._valueCache[uniformName]) {
  19248. this._valueCache[uniformName] = [x, y];
  19249. return;
  19250. }
  19251. this._valueCache[uniformName][0] = x;
  19252. this._valueCache[uniformName][1] = y;
  19253. };
  19254. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19255. if (!this._valueCache[uniformName]) {
  19256. this._valueCache[uniformName] = [x, y, z];
  19257. return;
  19258. }
  19259. this._valueCache[uniformName][0] = x;
  19260. this._valueCache[uniformName][1] = y;
  19261. this._valueCache[uniformName][2] = z;
  19262. };
  19263. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19264. if (!this._valueCache[uniformName]) {
  19265. this._valueCache[uniformName] = [x, y, z, w];
  19266. return;
  19267. }
  19268. this._valueCache[uniformName][0] = x;
  19269. this._valueCache[uniformName][1] = y;
  19270. this._valueCache[uniformName][2] = z;
  19271. this._valueCache[uniformName][3] = w;
  19272. };
  19273. Effect.prototype.setArray = function (uniformName, array) {
  19274. this._engine.setArray(this.getUniform(uniformName), array);
  19275. return this;
  19276. };
  19277. Effect.prototype.setArray2 = function (uniformName, array) {
  19278. this._engine.setArray2(this.getUniform(uniformName), array);
  19279. return this;
  19280. };
  19281. Effect.prototype.setArray3 = function (uniformName, array) {
  19282. this._engine.setArray3(this.getUniform(uniformName), array);
  19283. return this;
  19284. };
  19285. Effect.prototype.setArray4 = function (uniformName, array) {
  19286. this._engine.setArray4(this.getUniform(uniformName), array);
  19287. return this;
  19288. };
  19289. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19290. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19291. return this;
  19292. };
  19293. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19294. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19295. // return this;
  19296. // this._cacheMatrix(uniformName, matrix);
  19297. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19298. return this;
  19299. };
  19300. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19301. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19302. return this;
  19303. };
  19304. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19305. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19306. return this;
  19307. };
  19308. Effect.prototype.setFloat = function (uniformName, value) {
  19309. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19310. return this;
  19311. this._valueCache[uniformName] = value;
  19312. this._engine.setFloat(this.getUniform(uniformName), value);
  19313. return this;
  19314. };
  19315. Effect.prototype.setBool = function (uniformName, bool) {
  19316. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19317. return this;
  19318. this._valueCache[uniformName] = bool;
  19319. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19320. return this;
  19321. };
  19322. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19323. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19324. return this;
  19325. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19326. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19327. return this;
  19328. };
  19329. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19330. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19331. return this;
  19332. this._cacheFloat2(uniformName, x, y);
  19333. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19334. return this;
  19335. };
  19336. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19337. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19338. return this;
  19339. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19340. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19341. return this;
  19342. };
  19343. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19344. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19345. return this;
  19346. this._cacheFloat3(uniformName, x, y, z);
  19347. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19348. return this;
  19349. };
  19350. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19351. 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)
  19352. return this;
  19353. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19354. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19355. return this;
  19356. };
  19357. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19358. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19359. return this;
  19360. this._cacheFloat4(uniformName, x, y, z, w);
  19361. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19362. return this;
  19363. };
  19364. Effect.prototype.setColor3 = function (uniformName, color3) {
  19365. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19366. return this;
  19367. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19368. this._engine.setColor3(this.getUniform(uniformName), color3);
  19369. return this;
  19370. };
  19371. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19372. 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)
  19373. return this;
  19374. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19375. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19376. return this;
  19377. };
  19378. // Statics
  19379. Effect.ShadersStore = {};
  19380. Effect.IncludesShadersStore = {};
  19381. return Effect;
  19382. })();
  19383. BABYLON.Effect = Effect;
  19384. })(BABYLON || (BABYLON = {}));
  19385. var BABYLON;
  19386. (function (BABYLON) {
  19387. var maxSimultaneousLights = 4;
  19388. var MaterialHelper = (function () {
  19389. function MaterialHelper() {
  19390. }
  19391. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19392. var lightIndex = 0;
  19393. var needNormals = false;
  19394. for (var index = 0; index < scene.lights.length; index++) {
  19395. var light = scene.lights[index];
  19396. if (!light.isEnabled()) {
  19397. continue;
  19398. }
  19399. // Excluded check
  19400. if (light._excludedMeshesIds.length > 0) {
  19401. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19402. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19403. if (excludedMesh) {
  19404. light.excludedMeshes.push(excludedMesh);
  19405. }
  19406. }
  19407. light._excludedMeshesIds = [];
  19408. }
  19409. // Included check
  19410. if (light._includedOnlyMeshesIds.length > 0) {
  19411. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19412. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19413. if (includedOnlyMesh) {
  19414. light.includedOnlyMeshes.push(includedOnlyMesh);
  19415. }
  19416. }
  19417. light._includedOnlyMeshesIds = [];
  19418. }
  19419. if (!light.canAffectMesh(mesh)) {
  19420. continue;
  19421. }
  19422. needNormals = true;
  19423. defines["LIGHT" + lightIndex] = true;
  19424. var type;
  19425. if (light instanceof BABYLON.SpotLight) {
  19426. type = "SPOTLIGHT" + lightIndex;
  19427. }
  19428. else if (light instanceof BABYLON.HemisphericLight) {
  19429. type = "HEMILIGHT" + lightIndex;
  19430. }
  19431. else if (light instanceof BABYLON.PointLight) {
  19432. type = "POINTLIGHT" + lightIndex;
  19433. }
  19434. else {
  19435. type = "DIRLIGHT" + lightIndex;
  19436. }
  19437. defines[type] = true;
  19438. // Specular
  19439. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19440. defines["SPECULARTERM"] = true;
  19441. }
  19442. // Shadows
  19443. if (scene.shadowsEnabled) {
  19444. var shadowGenerator = light.getShadowGenerator();
  19445. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19446. defines["SHADOW" + lightIndex] = true;
  19447. defines["SHADOWS"] = true;
  19448. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19449. defines["SHADOWVSM" + lightIndex] = true;
  19450. }
  19451. if (shadowGenerator.usePoissonSampling) {
  19452. defines["SHADOWPCF" + lightIndex] = true;
  19453. }
  19454. }
  19455. }
  19456. lightIndex++;
  19457. if (lightIndex === maxSimultaneousLights)
  19458. break;
  19459. }
  19460. return needNormals;
  19461. };
  19462. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19463. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19464. if (!defines["LIGHT" + lightIndex]) {
  19465. continue;
  19466. }
  19467. if (lightIndex > 0) {
  19468. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19469. }
  19470. if (defines["SHADOW" + lightIndex]) {
  19471. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19472. }
  19473. if (defines["SHADOWPCF" + lightIndex]) {
  19474. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19475. }
  19476. if (defines["SHADOWVSM" + lightIndex]) {
  19477. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19478. }
  19479. }
  19480. };
  19481. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19482. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19483. fallbacks.addCPUSkinningFallback(0, mesh);
  19484. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19485. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19486. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19487. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19488. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19489. }
  19490. }
  19491. };
  19492. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19493. if (defines["INSTANCES"]) {
  19494. attribs.push("world0");
  19495. attribs.push("world1");
  19496. attribs.push("world2");
  19497. attribs.push("world3");
  19498. }
  19499. };
  19500. // Bindings
  19501. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19502. var shadowGenerator = light.getShadowGenerator();
  19503. if (mesh.receiveShadows && shadowGenerator) {
  19504. if (!light.needCube()) {
  19505. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19506. }
  19507. else {
  19508. if (!depthValuesAlreadySet) {
  19509. depthValuesAlreadySet = true;
  19510. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19511. }
  19512. }
  19513. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19514. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19515. }
  19516. return depthValuesAlreadySet;
  19517. };
  19518. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19519. if (light instanceof BABYLON.PointLight) {
  19520. // Point Light
  19521. light.transferToEffect(effect, "vLightData" + lightIndex);
  19522. }
  19523. else if (light instanceof BABYLON.DirectionalLight) {
  19524. // Directional Light
  19525. light.transferToEffect(effect, "vLightData" + lightIndex);
  19526. }
  19527. else if (light instanceof BABYLON.SpotLight) {
  19528. // Spot Light
  19529. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19530. }
  19531. else if (light instanceof BABYLON.HemisphericLight) {
  19532. // Hemispheric Light
  19533. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19534. }
  19535. };
  19536. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19537. var lightIndex = 0;
  19538. var depthValuesAlreadySet = false;
  19539. for (var index = 0; index < scene.lights.length; index++) {
  19540. var light = scene.lights[index];
  19541. if (!light.isEnabled()) {
  19542. continue;
  19543. }
  19544. if (!light.canAffectMesh(mesh)) {
  19545. continue;
  19546. }
  19547. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19548. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19549. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19550. if (defines["SPECULARTERM"]) {
  19551. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19552. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19553. }
  19554. // Shadows
  19555. if (scene.shadowsEnabled) {
  19556. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19557. }
  19558. lightIndex++;
  19559. if (lightIndex === maxSimultaneousLights)
  19560. break;
  19561. }
  19562. };
  19563. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19564. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19565. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19566. effect.setColor3("vFogColor", scene.fogColor);
  19567. }
  19568. };
  19569. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19570. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19571. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19572. }
  19573. };
  19574. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19575. if (defines["LOGARITHMICDEPTH"]) {
  19576. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19577. }
  19578. };
  19579. MaterialHelper.BindClipPlane = function (effect, scene) {
  19580. if (scene.clipPlane) {
  19581. var clipPlane = scene.clipPlane;
  19582. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19583. }
  19584. };
  19585. return MaterialHelper;
  19586. })();
  19587. BABYLON.MaterialHelper = MaterialHelper;
  19588. })(BABYLON || (BABYLON = {}));
  19589. var BABYLON;
  19590. (function (BABYLON) {
  19591. var FresnelParameters = (function () {
  19592. function FresnelParameters() {
  19593. this.isEnabled = true;
  19594. this.leftColor = BABYLON.Color3.White();
  19595. this.rightColor = BABYLON.Color3.Black();
  19596. this.bias = 0;
  19597. this.power = 1;
  19598. }
  19599. FresnelParameters.prototype.clone = function () {
  19600. var newFresnelParameters = new FresnelParameters();
  19601. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19602. return new FresnelParameters;
  19603. };
  19604. FresnelParameters.prototype.serialize = function () {
  19605. var serializationObject = {};
  19606. serializationObject.isEnabled = this.isEnabled;
  19607. serializationObject.leftColor = this.leftColor;
  19608. serializationObject.rightColor = this.rightColor;
  19609. serializationObject.bias = this.bias;
  19610. serializationObject.power = this.power;
  19611. return serializationObject;
  19612. };
  19613. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19614. var fresnelParameters = new FresnelParameters();
  19615. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19616. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19617. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19618. fresnelParameters.bias = parsedFresnelParameters.bias;
  19619. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19620. return fresnelParameters;
  19621. };
  19622. return FresnelParameters;
  19623. })();
  19624. BABYLON.FresnelParameters = FresnelParameters;
  19625. })(BABYLON || (BABYLON = {}));
  19626. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19627. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19628. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19629. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19630. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19631. };
  19632. var BABYLON;
  19633. (function (BABYLON) {
  19634. var MaterialDefines = (function () {
  19635. function MaterialDefines() {
  19636. }
  19637. MaterialDefines.prototype.isEqual = function (other) {
  19638. for (var index = 0; index < this._keys.length; index++) {
  19639. var prop = this._keys[index];
  19640. if (this[prop] !== other[prop]) {
  19641. return false;
  19642. }
  19643. }
  19644. return true;
  19645. };
  19646. MaterialDefines.prototype.cloneTo = function (other) {
  19647. for (var index = 0; index < this._keys.length; index++) {
  19648. var prop = this._keys[index];
  19649. other[prop] = this[prop];
  19650. }
  19651. };
  19652. MaterialDefines.prototype.reset = function () {
  19653. for (var index = 0; index < this._keys.length; index++) {
  19654. var prop = this._keys[index];
  19655. if (typeof (this[prop]) === "number") {
  19656. this[prop] = 0;
  19657. }
  19658. else {
  19659. this[prop] = false;
  19660. }
  19661. }
  19662. };
  19663. MaterialDefines.prototype.toString = function () {
  19664. var result = "";
  19665. for (var index = 0; index < this._keys.length; index++) {
  19666. var prop = this._keys[index];
  19667. if (typeof (this[prop]) === "number") {
  19668. result += "#define " + prop + " " + this[prop] + "\n";
  19669. }
  19670. else if (this[prop]) {
  19671. result += "#define " + prop + "\n";
  19672. }
  19673. }
  19674. return result;
  19675. };
  19676. return MaterialDefines;
  19677. })();
  19678. BABYLON.MaterialDefines = MaterialDefines;
  19679. var Material = (function () {
  19680. function Material(name, scene, doNotAdd) {
  19681. this.name = name;
  19682. this.checkReadyOnEveryCall = false;
  19683. this.checkReadyOnlyOnce = false;
  19684. this.state = "";
  19685. this.alpha = 1.0;
  19686. this.backFaceCulling = true;
  19687. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19688. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19689. this.disableDepthWrite = false;
  19690. this.fogEnabled = true;
  19691. this.pointSize = 1.0;
  19692. this.zOffset = 0;
  19693. this._wasPreviouslyReady = false;
  19694. this._fillMode = Material.TriangleFillMode;
  19695. this.id = name;
  19696. this._scene = scene;
  19697. if (!doNotAdd) {
  19698. scene.materials.push(this);
  19699. }
  19700. }
  19701. Object.defineProperty(Material, "TriangleFillMode", {
  19702. get: function () {
  19703. return Material._TriangleFillMode;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(Material, "WireFrameFillMode", {
  19709. get: function () {
  19710. return Material._WireFrameFillMode;
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(Material, "PointFillMode", {
  19716. get: function () {
  19717. return Material._PointFillMode;
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19723. get: function () {
  19724. return Material._ClockWiseSideOrientation;
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19730. get: function () {
  19731. return Material._CounterClockWiseSideOrientation;
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Object.defineProperty(Material.prototype, "wireframe", {
  19737. get: function () {
  19738. return this._fillMode === Material.WireFrameFillMode;
  19739. },
  19740. set: function (value) {
  19741. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19742. },
  19743. enumerable: true,
  19744. configurable: true
  19745. });
  19746. Object.defineProperty(Material.prototype, "pointsCloud", {
  19747. get: function () {
  19748. return this._fillMode === Material.PointFillMode;
  19749. },
  19750. set: function (value) {
  19751. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(Material.prototype, "fillMode", {
  19757. get: function () {
  19758. return this._fillMode;
  19759. },
  19760. set: function (value) {
  19761. this._fillMode = value;
  19762. },
  19763. enumerable: true,
  19764. configurable: true
  19765. });
  19766. Object.defineProperty(Material.prototype, "isFrozen", {
  19767. get: function () {
  19768. return this.checkReadyOnlyOnce;
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Material.prototype.freeze = function () {
  19774. this.checkReadyOnlyOnce = true;
  19775. };
  19776. Material.prototype.unfreeze = function () {
  19777. this.checkReadyOnlyOnce = false;
  19778. };
  19779. Material.prototype.isReady = function (mesh, useInstances) {
  19780. return true;
  19781. };
  19782. Material.prototype.getEffect = function () {
  19783. return this._effect;
  19784. };
  19785. Material.prototype.getScene = function () {
  19786. return this._scene;
  19787. };
  19788. Material.prototype.needAlphaBlending = function () {
  19789. return (this.alpha < 1.0);
  19790. };
  19791. Material.prototype.needAlphaTesting = function () {
  19792. return false;
  19793. };
  19794. Material.prototype.getAlphaTestTexture = function () {
  19795. return null;
  19796. };
  19797. Material.prototype.trackCreation = function (onCompiled, onError) {
  19798. };
  19799. Material.prototype.markDirty = function () {
  19800. this._wasPreviouslyReady = false;
  19801. };
  19802. Material.prototype._preBind = function () {
  19803. var engine = this._scene.getEngine();
  19804. engine.enableEffect(this._effect);
  19805. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19806. };
  19807. Material.prototype.bind = function (world, mesh) {
  19808. this._scene._cachedMaterial = this;
  19809. if (this.onBind) {
  19810. this.onBind(this, mesh);
  19811. }
  19812. if (this.disableDepthWrite) {
  19813. var engine = this._scene.getEngine();
  19814. this._cachedDepthWriteState = engine.getDepthWrite();
  19815. engine.setDepthWrite(false);
  19816. }
  19817. };
  19818. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19819. };
  19820. Material.prototype.unbind = function () {
  19821. if (this.disableDepthWrite) {
  19822. var engine = this._scene.getEngine();
  19823. engine.setDepthWrite(this._cachedDepthWriteState);
  19824. }
  19825. };
  19826. Material.prototype.clone = function (name) {
  19827. return null;
  19828. };
  19829. Material.prototype.getBindedMeshes = function () {
  19830. var result = new Array();
  19831. for (var index = 0; index < this._scene.meshes.length; index++) {
  19832. var mesh = this._scene.meshes[index];
  19833. if (mesh.material === this) {
  19834. result.push(mesh);
  19835. }
  19836. }
  19837. return result;
  19838. };
  19839. Material.prototype.dispose = function (forceDisposeEffect) {
  19840. // Animations
  19841. this.getScene().stopAnimation(this);
  19842. // Remove from scene
  19843. var index = this._scene.materials.indexOf(this);
  19844. if (index >= 0) {
  19845. this._scene.materials.splice(index, 1);
  19846. }
  19847. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19848. if (forceDisposeEffect && this._effect) {
  19849. this._scene.getEngine()._releaseEffect(this._effect);
  19850. this._effect = null;
  19851. }
  19852. // Remove from meshes
  19853. for (index = 0; index < this._scene.meshes.length; index++) {
  19854. var mesh = this._scene.meshes[index];
  19855. if (mesh.material === this) {
  19856. mesh.material = null;
  19857. }
  19858. }
  19859. // Callback
  19860. if (this.onDispose) {
  19861. this.onDispose();
  19862. }
  19863. };
  19864. Material.prototype.serialize = function () {
  19865. return BABYLON.SerializationHelper.Serialize(this);
  19866. };
  19867. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19868. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19869. multiMaterial.id = parsedMultiMaterial.id;
  19870. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19871. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19872. var subMatId = parsedMultiMaterial.materials[matIndex];
  19873. if (subMatId) {
  19874. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19875. }
  19876. else {
  19877. multiMaterial.subMaterials.push(null);
  19878. }
  19879. }
  19880. return multiMaterial;
  19881. };
  19882. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19883. if (!parsedMaterial.customType) {
  19884. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19885. }
  19886. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19887. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19888. ;
  19889. };
  19890. Material._TriangleFillMode = 0;
  19891. Material._WireFrameFillMode = 1;
  19892. Material._PointFillMode = 2;
  19893. Material._ClockWiseSideOrientation = 0;
  19894. Material._CounterClockWiseSideOrientation = 1;
  19895. __decorate([
  19896. BABYLON.serialize()
  19897. ], Material.prototype, "id", void 0);
  19898. __decorate([
  19899. BABYLON.serialize()
  19900. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19901. __decorate([
  19902. BABYLON.serialize()
  19903. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19904. __decorate([
  19905. BABYLON.serialize()
  19906. ], Material.prototype, "state", void 0);
  19907. __decorate([
  19908. BABYLON.serialize()
  19909. ], Material.prototype, "alpha", void 0);
  19910. __decorate([
  19911. BABYLON.serialize()
  19912. ], Material.prototype, "backFaceCulling", void 0);
  19913. __decorate([
  19914. BABYLON.serialize()
  19915. ], Material.prototype, "sideOrientation", void 0);
  19916. __decorate([
  19917. BABYLON.serialize()
  19918. ], Material.prototype, "alphaMode", void 0);
  19919. __decorate([
  19920. BABYLON.serialize()
  19921. ], Material.prototype, "disableDepthWrite", void 0);
  19922. __decorate([
  19923. BABYLON.serialize()
  19924. ], Material.prototype, "fogEnabled", void 0);
  19925. __decorate([
  19926. BABYLON.serialize()
  19927. ], Material.prototype, "pointSize", void 0);
  19928. __decorate([
  19929. BABYLON.serialize()
  19930. ], Material.prototype, "zOffset", void 0);
  19931. __decorate([
  19932. BABYLON.serialize()
  19933. ], Material.prototype, "wireframe", null);
  19934. __decorate([
  19935. BABYLON.serialize()
  19936. ], Material.prototype, "pointsCloud", null);
  19937. __decorate([
  19938. BABYLON.serialize()
  19939. ], Material.prototype, "fillMode", null);
  19940. return Material;
  19941. })();
  19942. BABYLON.Material = Material;
  19943. })(BABYLON || (BABYLON = {}));
  19944. var BABYLON;
  19945. (function (BABYLON) {
  19946. var StandardMaterialDefines = (function (_super) {
  19947. __extends(StandardMaterialDefines, _super);
  19948. function StandardMaterialDefines() {
  19949. _super.call(this);
  19950. this.DIFFUSE = false;
  19951. this.AMBIENT = false;
  19952. this.OPACITY = false;
  19953. this.OPACITYRGB = false;
  19954. this.REFLECTION = false;
  19955. this.EMISSIVE = false;
  19956. this.SPECULAR = false;
  19957. this.BUMP = false;
  19958. this.SPECULAROVERALPHA = false;
  19959. this.CLIPPLANE = false;
  19960. this.ALPHATEST = false;
  19961. this.ALPHAFROMDIFFUSE = false;
  19962. this.POINTSIZE = false;
  19963. this.FOG = false;
  19964. this.LIGHT0 = false;
  19965. this.LIGHT1 = false;
  19966. this.LIGHT2 = false;
  19967. this.LIGHT3 = false;
  19968. this.SPOTLIGHT0 = false;
  19969. this.SPOTLIGHT1 = false;
  19970. this.SPOTLIGHT2 = false;
  19971. this.SPOTLIGHT3 = false;
  19972. this.HEMILIGHT0 = false;
  19973. this.HEMILIGHT1 = false;
  19974. this.HEMILIGHT2 = false;
  19975. this.HEMILIGHT3 = false;
  19976. this.POINTLIGHT0 = false;
  19977. this.POINTLIGHT1 = false;
  19978. this.POINTLIGHT2 = false;
  19979. this.POINTLIGHT3 = false;
  19980. this.DIRLIGHT0 = false;
  19981. this.DIRLIGHT1 = false;
  19982. this.DIRLIGHT2 = false;
  19983. this.DIRLIGHT3 = false;
  19984. this.SPECULARTERM = false;
  19985. this.SHADOW0 = false;
  19986. this.SHADOW1 = false;
  19987. this.SHADOW2 = false;
  19988. this.SHADOW3 = false;
  19989. this.SHADOWS = false;
  19990. this.SHADOWVSM0 = false;
  19991. this.SHADOWVSM1 = false;
  19992. this.SHADOWVSM2 = false;
  19993. this.SHADOWVSM3 = false;
  19994. this.SHADOWPCF0 = false;
  19995. this.SHADOWPCF1 = false;
  19996. this.SHADOWPCF2 = false;
  19997. this.SHADOWPCF3 = false;
  19998. this.DIFFUSEFRESNEL = false;
  19999. this.OPACITYFRESNEL = false;
  20000. this.REFLECTIONFRESNEL = false;
  20001. this.REFRACTIONFRESNEL = false;
  20002. this.EMISSIVEFRESNEL = false;
  20003. this.FRESNEL = false;
  20004. this.NORMAL = false;
  20005. this.UV1 = false;
  20006. this.UV2 = false;
  20007. this.VERTEXCOLOR = false;
  20008. this.VERTEXALPHA = false;
  20009. this.NUM_BONE_INFLUENCERS = 0;
  20010. this.BonesPerMesh = 0;
  20011. this.INSTANCES = false;
  20012. this.GLOSSINESS = false;
  20013. this.ROUGHNESS = false;
  20014. this.EMISSIVEASILLUMINATION = false;
  20015. this.LINKEMISSIVEWITHDIFFUSE = false;
  20016. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20017. this.LIGHTMAP = false;
  20018. this.USELIGHTMAPASSHADOWMAP = false;
  20019. this.REFLECTIONMAP_3D = false;
  20020. this.REFLECTIONMAP_SPHERICAL = false;
  20021. this.REFLECTIONMAP_PLANAR = false;
  20022. this.REFLECTIONMAP_CUBIC = false;
  20023. this.REFLECTIONMAP_PROJECTION = false;
  20024. this.REFLECTIONMAP_SKYBOX = false;
  20025. this.REFLECTIONMAP_EXPLICIT = false;
  20026. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20027. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20028. this.INVERTCUBICMAP = false;
  20029. this.LOGARITHMICDEPTH = false;
  20030. this.REFRACTION = false;
  20031. this.REFRACTIONMAP_3D = false;
  20032. this.REFLECTIONOVERALPHA = false;
  20033. this._keys = Object.keys(this);
  20034. }
  20035. return StandardMaterialDefines;
  20036. })(BABYLON.MaterialDefines);
  20037. var StandardMaterial = (function (_super) {
  20038. __extends(StandardMaterial, _super);
  20039. function StandardMaterial(name, scene) {
  20040. var _this = this;
  20041. _super.call(this, name, scene);
  20042. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20043. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20044. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20045. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20046. this.specularPower = 64;
  20047. this.useAlphaFromDiffuseTexture = false;
  20048. this.useEmissiveAsIllumination = false;
  20049. this.linkEmissiveWithDiffuse = false;
  20050. this.useReflectionFresnelFromSpecular = false;
  20051. this.useSpecularOverAlpha = false;
  20052. this.useReflectionOverAlpha = false;
  20053. this.disableLighting = false;
  20054. this.roughness = 0;
  20055. this.indexOfRefraction = 0.98;
  20056. this.invertRefractionY = true;
  20057. this.useLightmapAsShadowmap = false;
  20058. this.useGlossinessFromSpecularMapAlpha = false;
  20059. this._renderTargets = new BABYLON.SmartArray(16);
  20060. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20061. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20062. this._defines = new StandardMaterialDefines();
  20063. this._cachedDefines = new StandardMaterialDefines();
  20064. this._cachedDefines.BonesPerMesh = -1;
  20065. this.getRenderTargetTextures = function () {
  20066. _this._renderTargets.reset();
  20067. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20068. _this._renderTargets.push(_this.reflectionTexture);
  20069. }
  20070. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20071. _this._renderTargets.push(_this.refractionTexture);
  20072. }
  20073. return _this._renderTargets;
  20074. };
  20075. }
  20076. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20077. get: function () {
  20078. return this._useLogarithmicDepth;
  20079. },
  20080. set: function (value) {
  20081. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20082. },
  20083. enumerable: true,
  20084. configurable: true
  20085. });
  20086. StandardMaterial.prototype.needAlphaBlending = function () {
  20087. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20088. };
  20089. StandardMaterial.prototype.needAlphaTesting = function () {
  20090. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20091. };
  20092. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20093. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20094. };
  20095. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20096. return this.diffuseTexture;
  20097. };
  20098. // Methods
  20099. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20100. if (!mesh) {
  20101. return true;
  20102. }
  20103. if (this._defines.INSTANCES !== useInstances) {
  20104. return false;
  20105. }
  20106. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20107. return true;
  20108. }
  20109. return false;
  20110. };
  20111. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20112. if (this.isFrozen) {
  20113. if (this._wasPreviouslyReady) {
  20114. return true;
  20115. }
  20116. }
  20117. var scene = this.getScene();
  20118. if (!this.checkReadyOnEveryCall) {
  20119. if (this._renderId === scene.getRenderId()) {
  20120. if (this._checkCache(scene, mesh, useInstances)) {
  20121. return true;
  20122. }
  20123. }
  20124. }
  20125. var engine = scene.getEngine();
  20126. var needNormals = false;
  20127. var needUVs = false;
  20128. this._defines.reset();
  20129. // Textures
  20130. if (scene.texturesEnabled) {
  20131. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20132. if (!this.diffuseTexture.isReady()) {
  20133. return false;
  20134. }
  20135. else {
  20136. needUVs = true;
  20137. this._defines.DIFFUSE = true;
  20138. }
  20139. }
  20140. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20141. if (!this.ambientTexture.isReady()) {
  20142. return false;
  20143. }
  20144. else {
  20145. needUVs = true;
  20146. this._defines.AMBIENT = true;
  20147. }
  20148. }
  20149. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20150. if (!this.opacityTexture.isReady()) {
  20151. return false;
  20152. }
  20153. else {
  20154. needUVs = true;
  20155. this._defines.OPACITY = true;
  20156. if (this.opacityTexture.getAlphaFromRGB) {
  20157. this._defines.OPACITYRGB = true;
  20158. }
  20159. }
  20160. }
  20161. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20162. if (!this.reflectionTexture.isReady()) {
  20163. return false;
  20164. }
  20165. else {
  20166. needNormals = true;
  20167. this._defines.REFLECTION = true;
  20168. if (this.roughness > 0) {
  20169. this._defines.ROUGHNESS = true;
  20170. }
  20171. if (this.useReflectionOverAlpha) {
  20172. this._defines.REFLECTIONOVERALPHA = true;
  20173. }
  20174. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20175. this._defines.INVERTCUBICMAP = true;
  20176. }
  20177. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20178. switch (this.reflectionTexture.coordinatesMode) {
  20179. case BABYLON.Texture.CUBIC_MODE:
  20180. case BABYLON.Texture.INVCUBIC_MODE:
  20181. this._defines.REFLECTIONMAP_CUBIC = true;
  20182. break;
  20183. case BABYLON.Texture.EXPLICIT_MODE:
  20184. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20185. break;
  20186. case BABYLON.Texture.PLANAR_MODE:
  20187. this._defines.REFLECTIONMAP_PLANAR = true;
  20188. break;
  20189. case BABYLON.Texture.PROJECTION_MODE:
  20190. this._defines.REFLECTIONMAP_PROJECTION = true;
  20191. break;
  20192. case BABYLON.Texture.SKYBOX_MODE:
  20193. this._defines.REFLECTIONMAP_SKYBOX = true;
  20194. break;
  20195. case BABYLON.Texture.SPHERICAL_MODE:
  20196. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20197. break;
  20198. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20199. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20200. break;
  20201. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20202. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20203. break;
  20204. }
  20205. }
  20206. }
  20207. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20208. if (!this.emissiveTexture.isReady()) {
  20209. return false;
  20210. }
  20211. else {
  20212. needUVs = true;
  20213. this._defines.EMISSIVE = true;
  20214. }
  20215. }
  20216. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20217. if (!this.lightmapTexture.isReady()) {
  20218. return false;
  20219. }
  20220. else {
  20221. needUVs = true;
  20222. this._defines.LIGHTMAP = true;
  20223. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20224. }
  20225. }
  20226. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20227. if (!this.specularTexture.isReady()) {
  20228. return false;
  20229. }
  20230. else {
  20231. needUVs = true;
  20232. this._defines.SPECULAR = true;
  20233. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20234. }
  20235. }
  20236. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20237. if (!this.bumpTexture.isReady()) {
  20238. return false;
  20239. }
  20240. else {
  20241. needUVs = true;
  20242. this._defines.BUMP = true;
  20243. }
  20244. }
  20245. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20246. if (!this.refractionTexture.isReady()) {
  20247. return false;
  20248. }
  20249. else {
  20250. needUVs = true;
  20251. this._defines.REFRACTION = true;
  20252. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20253. }
  20254. }
  20255. }
  20256. // Effect
  20257. if (scene.clipPlane) {
  20258. this._defines.CLIPPLANE = true;
  20259. }
  20260. if (engine.getAlphaTesting()) {
  20261. this._defines.ALPHATEST = true;
  20262. }
  20263. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20264. this._defines.ALPHAFROMDIFFUSE = true;
  20265. }
  20266. if (this.useEmissiveAsIllumination) {
  20267. this._defines.EMISSIVEASILLUMINATION = true;
  20268. }
  20269. if (this.linkEmissiveWithDiffuse) {
  20270. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20271. }
  20272. if (this.useLogarithmicDepth) {
  20273. this._defines.LOGARITHMICDEPTH = true;
  20274. }
  20275. // Point size
  20276. if (this.pointsCloud || scene.forcePointsCloud) {
  20277. this._defines.POINTSIZE = true;
  20278. }
  20279. // Fog
  20280. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20281. this._defines.FOG = true;
  20282. }
  20283. if (scene.lightsEnabled && !this.disableLighting) {
  20284. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20285. }
  20286. if (StandardMaterial.FresnelEnabled) {
  20287. // Fresnel
  20288. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20289. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20290. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20291. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20292. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20293. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20294. this._defines.DIFFUSEFRESNEL = true;
  20295. }
  20296. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20297. this._defines.OPACITYFRESNEL = true;
  20298. }
  20299. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20300. this._defines.REFLECTIONFRESNEL = true;
  20301. if (this.useReflectionFresnelFromSpecular) {
  20302. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20303. }
  20304. }
  20305. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20306. this._defines.REFRACTIONFRESNEL = true;
  20307. }
  20308. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20309. this._defines.EMISSIVEFRESNEL = true;
  20310. }
  20311. needNormals = true;
  20312. this._defines.FRESNEL = true;
  20313. }
  20314. }
  20315. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20316. this._defines.SPECULAROVERALPHA = true;
  20317. }
  20318. // Attribs
  20319. if (mesh) {
  20320. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20321. this._defines.NORMAL = true;
  20322. }
  20323. if (needUVs) {
  20324. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20325. this._defines.UV1 = true;
  20326. }
  20327. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20328. this._defines.UV2 = true;
  20329. }
  20330. }
  20331. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20332. this._defines.VERTEXCOLOR = true;
  20333. if (mesh.hasVertexAlpha) {
  20334. this._defines.VERTEXALPHA = true;
  20335. }
  20336. }
  20337. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20338. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20339. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20340. }
  20341. // Instances
  20342. if (useInstances) {
  20343. this._defines.INSTANCES = true;
  20344. }
  20345. }
  20346. // Get correct effect
  20347. if (!this._defines.isEqual(this._cachedDefines)) {
  20348. this._defines.cloneTo(this._cachedDefines);
  20349. scene.resetCachedMaterial();
  20350. // Fallbacks
  20351. var fallbacks = new BABYLON.EffectFallbacks();
  20352. if (this._defines.REFLECTION) {
  20353. fallbacks.addFallback(0, "REFLECTION");
  20354. }
  20355. if (this._defines.SPECULAR) {
  20356. fallbacks.addFallback(0, "SPECULAR");
  20357. }
  20358. if (this._defines.BUMP) {
  20359. fallbacks.addFallback(0, "BUMP");
  20360. }
  20361. if (this._defines.SPECULAROVERALPHA) {
  20362. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20363. }
  20364. if (this._defines.FOG) {
  20365. fallbacks.addFallback(1, "FOG");
  20366. }
  20367. if (this._defines.POINTSIZE) {
  20368. fallbacks.addFallback(0, "POINTSIZE");
  20369. }
  20370. if (this._defines.LOGARITHMICDEPTH) {
  20371. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20372. }
  20373. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20374. if (this._defines.SPECULARTERM) {
  20375. fallbacks.addFallback(0, "SPECULARTERM");
  20376. }
  20377. if (this._defines.DIFFUSEFRESNEL) {
  20378. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20379. }
  20380. if (this._defines.OPACITYFRESNEL) {
  20381. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20382. }
  20383. if (this._defines.REFLECTIONFRESNEL) {
  20384. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20385. }
  20386. if (this._defines.EMISSIVEFRESNEL) {
  20387. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20388. }
  20389. if (this._defines.FRESNEL) {
  20390. fallbacks.addFallback(4, "FRESNEL");
  20391. }
  20392. //Attributes
  20393. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20394. if (this._defines.NORMAL) {
  20395. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20396. }
  20397. if (this._defines.UV1) {
  20398. attribs.push(BABYLON.VertexBuffer.UVKind);
  20399. }
  20400. if (this._defines.UV2) {
  20401. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20402. }
  20403. if (this._defines.VERTEXCOLOR) {
  20404. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20405. }
  20406. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20407. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20408. // Legacy browser patch
  20409. var shaderName = "default";
  20410. if (!scene.getEngine().getCaps().standardDerivatives) {
  20411. shaderName = "legacydefault";
  20412. }
  20413. var join = this._defines.toString();
  20414. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20415. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20416. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20417. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20418. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20419. "vFogInfos", "vFogColor", "pointSize",
  20420. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20421. "mBones",
  20422. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20423. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20424. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20425. "logarithmicDepthConstant"
  20426. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20427. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20428. ], join, fallbacks, this.onCompiled, this.onError);
  20429. }
  20430. if (!this._effect.isReady()) {
  20431. return false;
  20432. }
  20433. this._renderId = scene.getRenderId();
  20434. this._wasPreviouslyReady = true;
  20435. if (mesh) {
  20436. if (!mesh._materialDefines) {
  20437. mesh._materialDefines = new StandardMaterialDefines();
  20438. }
  20439. this._defines.cloneTo(mesh._materialDefines);
  20440. }
  20441. return true;
  20442. };
  20443. StandardMaterial.prototype.unbind = function () {
  20444. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20445. this._effect.setTexture("reflection2DSampler", null);
  20446. }
  20447. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20448. this._effect.setTexture("refraction2DSampler", null);
  20449. }
  20450. _super.prototype.unbind.call(this);
  20451. };
  20452. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20453. this._effect.setMatrix("world", world);
  20454. };
  20455. StandardMaterial.prototype.bind = function (world, mesh) {
  20456. var scene = this.getScene();
  20457. // Matrices
  20458. this.bindOnlyWorldMatrix(world);
  20459. // Bones
  20460. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20461. if (scene.getCachedMaterial() !== this) {
  20462. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20463. if (StandardMaterial.FresnelEnabled) {
  20464. // Fresnel
  20465. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20466. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20467. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20468. }
  20469. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20470. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20471. }
  20472. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20473. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20474. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20475. }
  20476. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20477. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20478. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20479. }
  20480. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20481. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20482. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20483. }
  20484. }
  20485. // Textures
  20486. if (scene.texturesEnabled) {
  20487. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20488. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20489. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20490. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20491. }
  20492. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20493. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20494. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20495. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20496. }
  20497. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20498. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20499. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20500. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20501. }
  20502. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20503. if (this.reflectionTexture.isCube) {
  20504. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20505. }
  20506. else {
  20507. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20508. }
  20509. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20510. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20511. }
  20512. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20513. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20514. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20515. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20516. }
  20517. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20518. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20519. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20520. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20521. }
  20522. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20523. this._effect.setTexture("specularSampler", this.specularTexture);
  20524. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20525. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20526. }
  20527. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20528. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20529. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20530. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20531. }
  20532. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20533. var depth = 1.0;
  20534. if (this.refractionTexture.isCube) {
  20535. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20536. }
  20537. else {
  20538. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20539. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20540. if (this.refractionTexture.depth) {
  20541. depth = this.refractionTexture.depth;
  20542. }
  20543. }
  20544. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20545. }
  20546. }
  20547. // Clip plane
  20548. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20549. // Point size
  20550. if (this.pointsCloud) {
  20551. this._effect.setFloat("pointSize", this.pointSize);
  20552. }
  20553. // Colors
  20554. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20555. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20556. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20557. if (this._defines.SPECULARTERM) {
  20558. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20559. }
  20560. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20561. }
  20562. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20563. // Diffuse
  20564. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20565. // Lights
  20566. if (scene.lightsEnabled && !this.disableLighting) {
  20567. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20568. }
  20569. // View
  20570. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20571. this._effect.setMatrix("view", scene.getViewMatrix());
  20572. }
  20573. // Fog
  20574. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20575. // Log. depth
  20576. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20577. }
  20578. _super.prototype.bind.call(this, world, mesh);
  20579. };
  20580. StandardMaterial.prototype.getAnimatables = function () {
  20581. var results = [];
  20582. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20583. results.push(this.diffuseTexture);
  20584. }
  20585. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20586. results.push(this.ambientTexture);
  20587. }
  20588. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20589. results.push(this.opacityTexture);
  20590. }
  20591. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20592. results.push(this.reflectionTexture);
  20593. }
  20594. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20595. results.push(this.emissiveTexture);
  20596. }
  20597. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20598. results.push(this.specularTexture);
  20599. }
  20600. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20601. results.push(this.bumpTexture);
  20602. }
  20603. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20604. results.push(this.lightmapTexture);
  20605. }
  20606. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20607. results.push(this.refractionTexture);
  20608. }
  20609. return results;
  20610. };
  20611. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20612. if (this.diffuseTexture) {
  20613. this.diffuseTexture.dispose();
  20614. }
  20615. if (this.ambientTexture) {
  20616. this.ambientTexture.dispose();
  20617. }
  20618. if (this.opacityTexture) {
  20619. this.opacityTexture.dispose();
  20620. }
  20621. if (this.reflectionTexture) {
  20622. this.reflectionTexture.dispose();
  20623. }
  20624. if (this.emissiveTexture) {
  20625. this.emissiveTexture.dispose();
  20626. }
  20627. if (this.specularTexture) {
  20628. this.specularTexture.dispose();
  20629. }
  20630. if (this.bumpTexture) {
  20631. this.bumpTexture.dispose();
  20632. }
  20633. if (this.lightmapTexture) {
  20634. this.lightmapTexture.dispose();
  20635. }
  20636. if (this.refractionTexture) {
  20637. this.refractionTexture.dispose();
  20638. }
  20639. _super.prototype.dispose.call(this, forceDisposeEffect);
  20640. };
  20641. StandardMaterial.prototype.clone = function (name) {
  20642. var _this = this;
  20643. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20644. };
  20645. StandardMaterial.prototype.serialize = function () {
  20646. return BABYLON.SerializationHelper.Serialize(this);
  20647. };
  20648. // Statics
  20649. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20650. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20651. };
  20652. // Flags used to enable or disable a type of texture for all Standard Materials
  20653. StandardMaterial.DiffuseTextureEnabled = true;
  20654. StandardMaterial.AmbientTextureEnabled = true;
  20655. StandardMaterial.OpacityTextureEnabled = true;
  20656. StandardMaterial.ReflectionTextureEnabled = true;
  20657. StandardMaterial.EmissiveTextureEnabled = true;
  20658. StandardMaterial.SpecularTextureEnabled = true;
  20659. StandardMaterial.BumpTextureEnabled = true;
  20660. StandardMaterial.FresnelEnabled = true;
  20661. StandardMaterial.LightmapTextureEnabled = true;
  20662. StandardMaterial.RefractionTextureEnabled = true;
  20663. __decorate([
  20664. BABYLON.serializeAsTexture()
  20665. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20666. __decorate([
  20667. BABYLON.serializeAsTexture()
  20668. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20669. __decorate([
  20670. BABYLON.serializeAsTexture()
  20671. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20672. __decorate([
  20673. BABYLON.serializeAsTexture()
  20674. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20675. __decorate([
  20676. BABYLON.serializeAsTexture()
  20677. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20678. __decorate([
  20679. BABYLON.serializeAsTexture()
  20680. ], StandardMaterial.prototype, "specularTexture", void 0);
  20681. __decorate([
  20682. BABYLON.serializeAsTexture()
  20683. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20684. __decorate([
  20685. BABYLON.serializeAsTexture()
  20686. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20687. __decorate([
  20688. BABYLON.serializeAsTexture()
  20689. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20690. __decorate([
  20691. BABYLON.serializeAsColor3("ambient")
  20692. ], StandardMaterial.prototype, "ambientColor", void 0);
  20693. __decorate([
  20694. BABYLON.serializeAsColor3("diffuse")
  20695. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20696. __decorate([
  20697. BABYLON.serializeAsColor3("specular")
  20698. ], StandardMaterial.prototype, "specularColor", void 0);
  20699. __decorate([
  20700. BABYLON.serializeAsColor3("emissive")
  20701. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20702. __decorate([
  20703. BABYLON.serialize()
  20704. ], StandardMaterial.prototype, "specularPower", void 0);
  20705. __decorate([
  20706. BABYLON.serialize()
  20707. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20708. __decorate([
  20709. BABYLON.serialize()
  20710. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20711. __decorate([
  20712. BABYLON.serialize()
  20713. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20714. __decorate([
  20715. BABYLON.serialize()
  20716. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20717. __decorate([
  20718. BABYLON.serialize()
  20719. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20720. __decorate([
  20721. BABYLON.serialize()
  20722. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20723. __decorate([
  20724. BABYLON.serialize()
  20725. ], StandardMaterial.prototype, "disableLighting", void 0);
  20726. __decorate([
  20727. BABYLON.serialize()
  20728. ], StandardMaterial.prototype, "roughness", void 0);
  20729. __decorate([
  20730. BABYLON.serialize()
  20731. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20732. __decorate([
  20733. BABYLON.serialize()
  20734. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20735. __decorate([
  20736. BABYLON.serialize()
  20737. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20738. __decorate([
  20739. BABYLON.serializeAsFresnelParameters()
  20740. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20741. __decorate([
  20742. BABYLON.serializeAsFresnelParameters()
  20743. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20744. __decorate([
  20745. BABYLON.serializeAsFresnelParameters()
  20746. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20747. __decorate([
  20748. BABYLON.serializeAsFresnelParameters()
  20749. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20750. __decorate([
  20751. BABYLON.serializeAsFresnelParameters()
  20752. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20753. __decorate([
  20754. BABYLON.serialize()
  20755. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20756. __decorate([
  20757. BABYLON.serialize()
  20758. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20759. return StandardMaterial;
  20760. })(BABYLON.Material);
  20761. BABYLON.StandardMaterial = StandardMaterial;
  20762. })(BABYLON || (BABYLON = {}));
  20763. var BABYLON;
  20764. (function (BABYLON) {
  20765. var MultiMaterial = (function (_super) {
  20766. __extends(MultiMaterial, _super);
  20767. function MultiMaterial(name, scene) {
  20768. _super.call(this, name, scene, true);
  20769. this.subMaterials = new Array();
  20770. scene.multiMaterials.push(this);
  20771. }
  20772. // Properties
  20773. MultiMaterial.prototype.getSubMaterial = function (index) {
  20774. if (index < 0 || index >= this.subMaterials.length) {
  20775. return this.getScene().defaultMaterial;
  20776. }
  20777. return this.subMaterials[index];
  20778. };
  20779. // Methods
  20780. MultiMaterial.prototype.isReady = function (mesh) {
  20781. for (var index = 0; index < this.subMaterials.length; index++) {
  20782. var subMaterial = this.subMaterials[index];
  20783. if (subMaterial) {
  20784. if (!this.subMaterials[index].isReady(mesh)) {
  20785. return false;
  20786. }
  20787. }
  20788. }
  20789. return true;
  20790. };
  20791. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20792. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20793. for (var index = 0; index < this.subMaterials.length; index++) {
  20794. var subMaterial = null;
  20795. if (cloneChildren) {
  20796. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20797. }
  20798. else {
  20799. subMaterial = this.subMaterials[index];
  20800. }
  20801. newMultiMaterial.subMaterials.push(subMaterial);
  20802. }
  20803. return newMultiMaterial;
  20804. };
  20805. MultiMaterial.prototype.serialize = function () {
  20806. var serializationObject = {};
  20807. serializationObject.name = this.name;
  20808. serializationObject.id = this.id;
  20809. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20810. serializationObject.materials = [];
  20811. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20812. var subMat = this.subMaterials[matIndex];
  20813. if (subMat) {
  20814. serializationObject.materials.push(subMat.id);
  20815. }
  20816. else {
  20817. serializationObject.materials.push(null);
  20818. }
  20819. }
  20820. return serializationObject;
  20821. };
  20822. return MultiMaterial;
  20823. })(BABYLON.Material);
  20824. BABYLON.MultiMaterial = MultiMaterial;
  20825. })(BABYLON || (BABYLON = {}));
  20826. var BABYLON;
  20827. (function (BABYLON) {
  20828. var SceneLoader = (function () {
  20829. function SceneLoader() {
  20830. }
  20831. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20832. get: function () {
  20833. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20834. },
  20835. set: function (value) {
  20836. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20837. },
  20838. enumerable: true,
  20839. configurable: true
  20840. });
  20841. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20842. get: function () {
  20843. return SceneLoader._ShowLoadingScreen;
  20844. },
  20845. set: function (value) {
  20846. SceneLoader._ShowLoadingScreen = value;
  20847. },
  20848. enumerable: true,
  20849. configurable: true
  20850. });
  20851. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20852. var dotPosition = sceneFilename.lastIndexOf(".");
  20853. var queryStringPosition = sceneFilename.indexOf("?");
  20854. if (queryStringPosition === -1) {
  20855. queryStringPosition = sceneFilename.length;
  20856. }
  20857. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20858. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20859. var plugin = this._registeredPlugins[index];
  20860. if (plugin.extensions.indexOf(extension) !== -1) {
  20861. return plugin;
  20862. }
  20863. }
  20864. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20865. };
  20866. // Public functions
  20867. SceneLoader.GetPluginForExtension = function (extension) {
  20868. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20869. var plugin = this._registeredPlugins[index];
  20870. if (plugin.extensions.indexOf(extension) !== -1) {
  20871. return plugin;
  20872. }
  20873. }
  20874. return null;
  20875. };
  20876. SceneLoader.RegisterPlugin = function (plugin) {
  20877. plugin.extensions = plugin.extensions.toLowerCase();
  20878. SceneLoader._registeredPlugins.push(plugin);
  20879. };
  20880. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20881. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20882. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20883. return;
  20884. }
  20885. var loadingToken = {};
  20886. scene._addPendingData(loadingToken);
  20887. var manifestChecked = function (success) {
  20888. scene.database = database;
  20889. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20890. var importMeshFromData = function (data) {
  20891. var meshes = [];
  20892. var particleSystems = [];
  20893. var skeletons = [];
  20894. try {
  20895. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20896. if (onerror) {
  20897. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20898. }
  20899. scene._removePendingData(loadingToken);
  20900. return;
  20901. }
  20902. }
  20903. catch (e) {
  20904. if (onerror) {
  20905. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20906. }
  20907. scene._removePendingData(loadingToken);
  20908. return;
  20909. }
  20910. if (onsuccess) {
  20911. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20912. onsuccess(meshes, particleSystems, skeletons);
  20913. scene._removePendingData(loadingToken);
  20914. }
  20915. };
  20916. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20917. // Direct load
  20918. importMeshFromData(sceneFilename.substr(5));
  20919. return;
  20920. }
  20921. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20922. importMeshFromData(data);
  20923. }, progressCallBack, database);
  20924. };
  20925. if (scene.getEngine().enableOfflineSupport) {
  20926. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20927. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20928. }
  20929. else {
  20930. manifestChecked(true);
  20931. }
  20932. };
  20933. /**
  20934. * Load a scene
  20935. * @param rootUrl a string that defines the root url for scene and resources
  20936. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20937. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20938. */
  20939. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20940. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20941. };
  20942. /**
  20943. * Append a scene
  20944. * @param rootUrl a string that defines the root url for scene and resources
  20945. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20946. * @param scene is the instance of BABYLON.Scene to append to
  20947. */
  20948. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20949. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20950. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20951. return;
  20952. }
  20953. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20954. var database;
  20955. var loadingToken = {};
  20956. scene._addPendingData(loadingToken);
  20957. if (SceneLoader.ShowLoadingScreen) {
  20958. scene.getEngine().displayLoadingUI();
  20959. }
  20960. var loadSceneFromData = function (data) {
  20961. scene.database = database;
  20962. if (!plugin.load(scene, data, rootUrl)) {
  20963. if (onerror) {
  20964. onerror(scene);
  20965. }
  20966. scene._removePendingData(loadingToken);
  20967. scene.getEngine().hideLoadingUI();
  20968. return;
  20969. }
  20970. if (onsuccess) {
  20971. onsuccess(scene);
  20972. }
  20973. scene._removePendingData(loadingToken);
  20974. if (SceneLoader.ShowLoadingScreen) {
  20975. scene.executeWhenReady(function () {
  20976. scene.getEngine().hideLoadingUI();
  20977. });
  20978. }
  20979. };
  20980. var manifestChecked = function (success) {
  20981. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20982. };
  20983. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20984. // Direct load
  20985. loadSceneFromData(sceneFilename.substr(5));
  20986. return;
  20987. }
  20988. if (rootUrl.indexOf("file:") === -1) {
  20989. if (scene.getEngine().enableOfflineSupport) {
  20990. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20991. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20992. }
  20993. else {
  20994. manifestChecked(true);
  20995. }
  20996. }
  20997. else {
  20998. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20999. }
  21000. };
  21001. // Flags
  21002. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21003. SceneLoader._ShowLoadingScreen = true;
  21004. // Members
  21005. SceneLoader._registeredPlugins = new Array();
  21006. return SceneLoader;
  21007. })();
  21008. BABYLON.SceneLoader = SceneLoader;
  21009. ;
  21010. })(BABYLON || (BABYLON = {}));
  21011. var BABYLON;
  21012. (function (BABYLON) {
  21013. var Internals;
  21014. (function (Internals) {
  21015. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21016. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21017. var parsedMaterial = parsedData.materials[index];
  21018. if (parsedMaterial.id === id) {
  21019. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21020. }
  21021. }
  21022. return null;
  21023. };
  21024. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21025. names = (names instanceof Array) ? names : [names];
  21026. for (var i in names) {
  21027. if (mesh.name === names[i]) {
  21028. hierarchyIds.push(mesh.id);
  21029. return true;
  21030. }
  21031. }
  21032. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21033. hierarchyIds.push(mesh.id);
  21034. return true;
  21035. }
  21036. return false;
  21037. };
  21038. BABYLON.SceneLoader.RegisterPlugin({
  21039. extensions: ".babylon",
  21040. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21041. var parsedData = JSON.parse(data);
  21042. var loadedSkeletonsIds = [];
  21043. var loadedMaterialsIds = [];
  21044. var hierarchyIds = [];
  21045. var index;
  21046. var cache;
  21047. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21048. var parsedMesh = parsedData.meshes[index];
  21049. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21050. if (meshesNames instanceof Array) {
  21051. // Remove found mesh name from list.
  21052. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21053. }
  21054. //Geometry?
  21055. if (parsedMesh.geometryId) {
  21056. //does the file contain geometries?
  21057. if (parsedData.geometries) {
  21058. //find the correct geometry and add it to the scene
  21059. var found = false;
  21060. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21061. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21062. return;
  21063. }
  21064. else {
  21065. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21066. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21067. switch (geometryType) {
  21068. case "boxes":
  21069. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21070. break;
  21071. case "spheres":
  21072. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21073. break;
  21074. case "cylinders":
  21075. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21076. break;
  21077. case "toruses":
  21078. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21079. break;
  21080. case "grounds":
  21081. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21082. break;
  21083. case "planes":
  21084. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21085. break;
  21086. case "torusKnots":
  21087. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21088. break;
  21089. case "vertexData":
  21090. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21091. break;
  21092. }
  21093. found = true;
  21094. }
  21095. });
  21096. }
  21097. });
  21098. if (!found) {
  21099. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21100. }
  21101. }
  21102. }
  21103. // Material ?
  21104. if (parsedMesh.materialId) {
  21105. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21106. if (!materialFound && parsedData.multiMaterials) {
  21107. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21108. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21109. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21110. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21111. var subMatId = parsedMultiMaterial.materials[matIndex];
  21112. loadedMaterialsIds.push(subMatId);
  21113. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21114. }
  21115. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21116. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21117. materialFound = true;
  21118. break;
  21119. }
  21120. }
  21121. }
  21122. if (!materialFound) {
  21123. loadedMaterialsIds.push(parsedMesh.materialId);
  21124. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21125. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21126. }
  21127. }
  21128. }
  21129. // Skeleton ?
  21130. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21131. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21132. if (!skeletonAlreadyLoaded) {
  21133. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21134. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21135. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21136. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21137. loadedSkeletonsIds.push(parsedSkeleton.id);
  21138. }
  21139. }
  21140. }
  21141. }
  21142. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21143. meshes.push(mesh);
  21144. }
  21145. }
  21146. // Connecting parents
  21147. var currentMesh;
  21148. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21149. currentMesh = scene.meshes[index];
  21150. if (currentMesh._waitingParentId) {
  21151. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21152. currentMesh._waitingParentId = undefined;
  21153. }
  21154. }
  21155. // freeze and compute world matrix application
  21156. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21157. currentMesh = scene.meshes[index];
  21158. if (currentMesh._waitingFreezeWorldMatrix) {
  21159. currentMesh.freezeWorldMatrix();
  21160. currentMesh._waitingFreezeWorldMatrix = undefined;
  21161. }
  21162. else {
  21163. currentMesh.computeWorldMatrix(true);
  21164. }
  21165. }
  21166. // Particles
  21167. if (parsedData.particleSystems) {
  21168. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21169. var parsedParticleSystem = parsedData.particleSystems[index];
  21170. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21171. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21172. }
  21173. }
  21174. }
  21175. return true;
  21176. },
  21177. load: function (scene, data, rootUrl) {
  21178. var parsedData = JSON.parse(data);
  21179. // Scene
  21180. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21181. scene.autoClear = parsedData.autoClear;
  21182. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21183. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21184. if (parsedData.gravity) {
  21185. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21186. }
  21187. // Fog
  21188. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21189. scene.fogMode = parsedData.fogMode;
  21190. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21191. scene.fogStart = parsedData.fogStart;
  21192. scene.fogEnd = parsedData.fogEnd;
  21193. scene.fogDensity = parsedData.fogDensity;
  21194. }
  21195. //Physics
  21196. if (parsedData.physicsEnabled) {
  21197. var physicsPlugin;
  21198. if (parsedData.physicsEngine === "cannon") {
  21199. physicsPlugin = new BABYLON.CannonJSPlugin();
  21200. }
  21201. else if (parsedData.physicsEngine === "oimo") {
  21202. physicsPlugin = new BABYLON.OimoJSPlugin();
  21203. }
  21204. //else - default engine, which is currently oimo
  21205. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21206. scene.enablePhysics(physicsGravity, physicsPlugin);
  21207. }
  21208. //collisions, if defined. otherwise, default is true
  21209. if (parsedData.collisionsEnabled != undefined) {
  21210. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21211. }
  21212. scene.workerCollisions = !!parsedData.workerCollisions;
  21213. var index;
  21214. var cache;
  21215. // Lights
  21216. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21217. var parsedLight = parsedData.lights[index];
  21218. BABYLON.Light.Parse(parsedLight, scene);
  21219. }
  21220. // Animations
  21221. if (parsedData.animations) {
  21222. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21223. var parsedAnimation = parsedData.animations[index];
  21224. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21225. }
  21226. }
  21227. // Materials
  21228. if (parsedData.materials) {
  21229. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21230. var parsedMaterial = parsedData.materials[index];
  21231. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21232. }
  21233. }
  21234. if (parsedData.multiMaterials) {
  21235. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21236. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21237. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21238. }
  21239. }
  21240. // Skeletons
  21241. if (parsedData.skeletons) {
  21242. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21243. var parsedSkeleton = parsedData.skeletons[index];
  21244. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21245. }
  21246. }
  21247. // Geometries
  21248. var geometries = parsedData.geometries;
  21249. if (geometries) {
  21250. // Boxes
  21251. var boxes = geometries.boxes;
  21252. if (boxes) {
  21253. for (index = 0, cache = boxes.length; index < cache; index++) {
  21254. var parsedBox = boxes[index];
  21255. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21256. }
  21257. }
  21258. // Spheres
  21259. var spheres = geometries.spheres;
  21260. if (spheres) {
  21261. for (index = 0, cache = spheres.length; index < cache; index++) {
  21262. var parsedSphere = spheres[index];
  21263. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21264. }
  21265. }
  21266. // Cylinders
  21267. var cylinders = geometries.cylinders;
  21268. if (cylinders) {
  21269. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21270. var parsedCylinder = cylinders[index];
  21271. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21272. }
  21273. }
  21274. // Toruses
  21275. var toruses = geometries.toruses;
  21276. if (toruses) {
  21277. for (index = 0, cache = toruses.length; index < cache; index++) {
  21278. var parsedTorus = toruses[index];
  21279. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21280. }
  21281. }
  21282. // Grounds
  21283. var grounds = geometries.grounds;
  21284. if (grounds) {
  21285. for (index = 0, cache = grounds.length; index < cache; index++) {
  21286. var parsedGround = grounds[index];
  21287. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21288. }
  21289. }
  21290. // Planes
  21291. var planes = geometries.planes;
  21292. if (planes) {
  21293. for (index = 0, cache = planes.length; index < cache; index++) {
  21294. var parsedPlane = planes[index];
  21295. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21296. }
  21297. }
  21298. // TorusKnots
  21299. var torusKnots = geometries.torusKnots;
  21300. if (torusKnots) {
  21301. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21302. var parsedTorusKnot = torusKnots[index];
  21303. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21304. }
  21305. }
  21306. // VertexData
  21307. var vertexData = geometries.vertexData;
  21308. if (vertexData) {
  21309. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21310. var parsedVertexData = vertexData[index];
  21311. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21312. }
  21313. }
  21314. }
  21315. // Meshes
  21316. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21317. var parsedMesh = parsedData.meshes[index];
  21318. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21319. }
  21320. // Cameras
  21321. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21322. var parsedCamera = parsedData.cameras[index];
  21323. BABYLON.Camera.Parse(parsedCamera, scene);
  21324. }
  21325. if (parsedData.activeCameraID) {
  21326. scene.setActiveCameraByID(parsedData.activeCameraID);
  21327. }
  21328. // Browsing all the graph to connect the dots
  21329. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21330. var camera = scene.cameras[index];
  21331. if (camera._waitingParentId) {
  21332. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21333. camera._waitingParentId = undefined;
  21334. }
  21335. }
  21336. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21337. var light = scene.lights[index];
  21338. if (light._waitingParentId) {
  21339. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21340. light._waitingParentId = undefined;
  21341. }
  21342. }
  21343. // Sounds
  21344. var loadedSounds = [];
  21345. var loadedSound;
  21346. if (BABYLON.AudioEngine && parsedData.sounds) {
  21347. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21348. var parsedSound = parsedData.sounds[index];
  21349. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21350. if (!parsedSound.url)
  21351. parsedSound.url = parsedSound.name;
  21352. if (!loadedSounds[parsedSound.url]) {
  21353. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21354. loadedSounds[parsedSound.url] = loadedSound;
  21355. }
  21356. else {
  21357. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21358. }
  21359. }
  21360. else {
  21361. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21362. }
  21363. }
  21364. }
  21365. loadedSounds = [];
  21366. // Connect parents & children and parse actions
  21367. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21368. var mesh = scene.meshes[index];
  21369. if (mesh._waitingParentId) {
  21370. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21371. mesh._waitingParentId = undefined;
  21372. }
  21373. if (mesh._waitingActions) {
  21374. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21375. mesh._waitingActions = undefined;
  21376. }
  21377. }
  21378. // freeze world matrix application
  21379. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21380. var currentMesh = scene.meshes[index];
  21381. if (currentMesh._waitingFreezeWorldMatrix) {
  21382. currentMesh.freezeWorldMatrix();
  21383. currentMesh._waitingFreezeWorldMatrix = undefined;
  21384. }
  21385. else {
  21386. currentMesh.computeWorldMatrix(true);
  21387. }
  21388. }
  21389. // Particles Systems
  21390. if (parsedData.particleSystems) {
  21391. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21392. var parsedParticleSystem = parsedData.particleSystems[index];
  21393. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21394. }
  21395. }
  21396. // Lens flares
  21397. if (parsedData.lensFlareSystems) {
  21398. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21399. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21400. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21401. }
  21402. }
  21403. // Shadows
  21404. if (parsedData.shadowGenerators) {
  21405. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21406. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21407. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21408. }
  21409. }
  21410. // Actions (scene)
  21411. if (parsedData.actions) {
  21412. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21413. }
  21414. // Finish
  21415. return true;
  21416. }
  21417. });
  21418. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21419. })(BABYLON || (BABYLON = {}));
  21420. var BABYLON;
  21421. (function (BABYLON) {
  21422. var SpriteManager = (function () {
  21423. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21425. this.name = name;
  21426. this.cellSize = cellSize;
  21427. this.sprites = new Array();
  21428. this.renderingGroupId = 0;
  21429. this.layerMask = 0x0FFFFFFF;
  21430. this.fogEnabled = true;
  21431. this.isPickable = false;
  21432. this._vertexDeclaration = [4, 4, 4, 4];
  21433. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21434. this._capacity = capacity;
  21435. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21436. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21437. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21438. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21439. this._scene = scene;
  21440. this._scene.spriteManagers.push(this);
  21441. // VBO
  21442. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21443. var indices = [];
  21444. var index = 0;
  21445. for (var count = 0; count < capacity; count++) {
  21446. indices.push(index);
  21447. indices.push(index + 1);
  21448. indices.push(index + 2);
  21449. indices.push(index);
  21450. indices.push(index + 2);
  21451. indices.push(index + 3);
  21452. index += 4;
  21453. }
  21454. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21455. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21456. // Effects
  21457. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21458. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21459. }
  21460. Object.defineProperty(SpriteManager.prototype, "texture", {
  21461. get: function () {
  21462. return this._spriteTexture;
  21463. },
  21464. set: function (value) {
  21465. this._spriteTexture = value;
  21466. },
  21467. enumerable: true,
  21468. configurable: true
  21469. });
  21470. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21471. var arrayOffset = index * 16;
  21472. if (offsetX === 0)
  21473. offsetX = this._epsilon;
  21474. else if (offsetX === 1)
  21475. offsetX = 1 - this._epsilon;
  21476. if (offsetY === 0)
  21477. offsetY = this._epsilon;
  21478. else if (offsetY === 1)
  21479. offsetY = 1 - this._epsilon;
  21480. this._vertices[arrayOffset] = sprite.position.x;
  21481. this._vertices[arrayOffset + 1] = sprite.position.y;
  21482. this._vertices[arrayOffset + 2] = sprite.position.z;
  21483. this._vertices[arrayOffset + 3] = sprite.angle;
  21484. this._vertices[arrayOffset + 4] = sprite.width;
  21485. this._vertices[arrayOffset + 5] = sprite.height;
  21486. this._vertices[arrayOffset + 6] = offsetX;
  21487. this._vertices[arrayOffset + 7] = offsetY;
  21488. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21489. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21490. var offset = (sprite.cellIndex / rowSize) >> 0;
  21491. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21492. this._vertices[arrayOffset + 11] = offset;
  21493. // Color
  21494. this._vertices[arrayOffset + 12] = sprite.color.r;
  21495. this._vertices[arrayOffset + 13] = sprite.color.g;
  21496. this._vertices[arrayOffset + 14] = sprite.color.b;
  21497. this._vertices[arrayOffset + 15] = sprite.color.a;
  21498. };
  21499. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21500. var count = Math.min(this._capacity, this.sprites.length);
  21501. var min = BABYLON.Vector3.Zero();
  21502. var max = BABYLON.Vector3.Zero();
  21503. var distance = Number.MAX_VALUE;
  21504. var currentSprite;
  21505. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21506. var cameraView = camera.getViewMatrix();
  21507. for (var index = 0; index < count; index++) {
  21508. var sprite = this.sprites[index];
  21509. if (!sprite) {
  21510. continue;
  21511. }
  21512. if (predicate) {
  21513. if (!predicate(sprite)) {
  21514. continue;
  21515. }
  21516. }
  21517. else if (!sprite.isPickable) {
  21518. continue;
  21519. }
  21520. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21521. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21522. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21523. if (ray.intersectsBoxMinMax(min, max)) {
  21524. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21525. if (distance > currentDistance) {
  21526. distance = currentDistance;
  21527. currentSprite = sprite;
  21528. if (fastCheck) {
  21529. break;
  21530. }
  21531. }
  21532. }
  21533. }
  21534. if (currentSprite) {
  21535. var result = new BABYLON.PickingInfo();
  21536. result.hit = true;
  21537. result.pickedSprite = currentSprite;
  21538. result.distance = distance;
  21539. return result;
  21540. }
  21541. return null;
  21542. };
  21543. SpriteManager.prototype.render = function () {
  21544. // Check
  21545. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21546. return;
  21547. var engine = this._scene.getEngine();
  21548. var baseSize = this._spriteTexture.getBaseSize();
  21549. // Sprites
  21550. var deltaTime = engine.getDeltaTime();
  21551. var max = Math.min(this._capacity, this.sprites.length);
  21552. var rowSize = baseSize.width / this.cellSize;
  21553. var offset = 0;
  21554. for (var index = 0; index < max; index++) {
  21555. var sprite = this.sprites[index];
  21556. if (!sprite) {
  21557. continue;
  21558. }
  21559. sprite._animate(deltaTime);
  21560. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21561. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21562. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21563. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21564. }
  21565. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21566. // Render
  21567. var effect = this._effectBase;
  21568. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21569. effect = this._effectFog;
  21570. }
  21571. engine.enableEffect(effect);
  21572. var viewMatrix = this._scene.getViewMatrix();
  21573. effect.setTexture("diffuseSampler", this._spriteTexture);
  21574. effect.setMatrix("view", viewMatrix);
  21575. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21576. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21577. // Fog
  21578. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21579. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21580. effect.setColor3("vFogColor", this._scene.fogColor);
  21581. }
  21582. // VBOs
  21583. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21584. // Draw order
  21585. engine.setDepthFunctionToLessOrEqual();
  21586. effect.setBool("alphaTest", true);
  21587. engine.setColorWrite(false);
  21588. engine.draw(true, 0, max * 6);
  21589. engine.setColorWrite(true);
  21590. effect.setBool("alphaTest", false);
  21591. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21592. engine.draw(true, 0, max * 6);
  21593. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21594. };
  21595. SpriteManager.prototype.dispose = function () {
  21596. if (this._vertexBuffer) {
  21597. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21598. this._vertexBuffer = null;
  21599. }
  21600. if (this._indexBuffer) {
  21601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21602. this._indexBuffer = null;
  21603. }
  21604. if (this._spriteTexture) {
  21605. this._spriteTexture.dispose();
  21606. this._spriteTexture = null;
  21607. }
  21608. // Remove from scene
  21609. var index = this._scene.spriteManagers.indexOf(this);
  21610. this._scene.spriteManagers.splice(index, 1);
  21611. // Callback
  21612. if (this.onDispose) {
  21613. this.onDispose();
  21614. }
  21615. };
  21616. return SpriteManager;
  21617. })();
  21618. BABYLON.SpriteManager = SpriteManager;
  21619. })(BABYLON || (BABYLON = {}));
  21620. var BABYLON;
  21621. (function (BABYLON) {
  21622. var Sprite = (function () {
  21623. function Sprite(name, manager) {
  21624. this.name = name;
  21625. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21626. this.width = 1.0;
  21627. this.height = 1.0;
  21628. this.angle = 0;
  21629. this.cellIndex = 0;
  21630. this.invertU = 0;
  21631. this.invertV = 0;
  21632. this.animations = new Array();
  21633. this.isPickable = false;
  21634. this._animationStarted = false;
  21635. this._loopAnimation = false;
  21636. this._fromIndex = 0;
  21637. this._toIndex = 0;
  21638. this._delay = 0;
  21639. this._direction = 1;
  21640. this._frameCount = 0;
  21641. this._time = 0;
  21642. this._manager = manager;
  21643. this._manager.sprites.push(this);
  21644. this.position = BABYLON.Vector3.Zero();
  21645. }
  21646. Object.defineProperty(Sprite.prototype, "size", {
  21647. get: function () {
  21648. return this.width;
  21649. },
  21650. set: function (value) {
  21651. this.width = value;
  21652. this.height = value;
  21653. },
  21654. enumerable: true,
  21655. configurable: true
  21656. });
  21657. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21658. this._fromIndex = from;
  21659. this._toIndex = to;
  21660. this._loopAnimation = loop;
  21661. this._delay = delay;
  21662. this._animationStarted = true;
  21663. this._direction = from < to ? 1 : -1;
  21664. this.cellIndex = from;
  21665. this._time = 0;
  21666. };
  21667. Sprite.prototype.stopAnimation = function () {
  21668. this._animationStarted = false;
  21669. };
  21670. Sprite.prototype._animate = function (deltaTime) {
  21671. if (!this._animationStarted)
  21672. return;
  21673. this._time += deltaTime;
  21674. if (this._time > this._delay) {
  21675. this._time = this._time % this._delay;
  21676. this.cellIndex += this._direction;
  21677. if (this.cellIndex == this._toIndex) {
  21678. if (this._loopAnimation) {
  21679. this.cellIndex = this._fromIndex;
  21680. }
  21681. else {
  21682. this._animationStarted = false;
  21683. if (this.disposeWhenFinishedAnimating) {
  21684. this.dispose();
  21685. }
  21686. }
  21687. }
  21688. }
  21689. };
  21690. Sprite.prototype.dispose = function () {
  21691. for (var i = 0; i < this._manager.sprites.length; i++) {
  21692. if (this._manager.sprites[i] == this) {
  21693. this._manager.sprites.splice(i, 1);
  21694. }
  21695. }
  21696. };
  21697. return Sprite;
  21698. })();
  21699. BABYLON.Sprite = Sprite;
  21700. })(BABYLON || (BABYLON = {}));
  21701. var BABYLON;
  21702. (function (BABYLON) {
  21703. var Layer = (function () {
  21704. function Layer(name, imgUrl, scene, isBackground, color) {
  21705. this.name = name;
  21706. this.scale = new BABYLON.Vector2(1, 1);
  21707. this.offset = new BABYLON.Vector2(0, 0);
  21708. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21709. this._vertexDeclaration = [2];
  21710. this._vertexStrideSize = 2 * 4;
  21711. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21712. this.isBackground = isBackground === undefined ? true : isBackground;
  21713. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21714. this._scene = scene;
  21715. this._scene.layers.push(this);
  21716. // VBO
  21717. var vertices = [];
  21718. vertices.push(1, 1);
  21719. vertices.push(-1, 1);
  21720. vertices.push(-1, -1);
  21721. vertices.push(1, -1);
  21722. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21723. // Indices
  21724. var indices = [];
  21725. indices.push(0);
  21726. indices.push(1);
  21727. indices.push(2);
  21728. indices.push(0);
  21729. indices.push(2);
  21730. indices.push(3);
  21731. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21732. // Effects
  21733. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21734. }
  21735. Layer.prototype.render = function () {
  21736. // Check
  21737. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21738. return;
  21739. var engine = this._scene.getEngine();
  21740. // Render
  21741. engine.enableEffect(this._effect);
  21742. engine.setState(false);
  21743. // Texture
  21744. this._effect.setTexture("textureSampler", this.texture);
  21745. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21746. // Color
  21747. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21748. // Scale / offset
  21749. this._effect.setVector2("offset", this.offset);
  21750. this._effect.setVector2("scale", this.scale);
  21751. // VBOs
  21752. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21753. // Draw order
  21754. engine.setAlphaMode(this.alphaBlendingMode);
  21755. engine.draw(true, 0, 6);
  21756. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21757. };
  21758. Layer.prototype.dispose = function () {
  21759. if (this._vertexBuffer) {
  21760. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21761. this._vertexBuffer = null;
  21762. }
  21763. if (this._indexBuffer) {
  21764. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21765. this._indexBuffer = null;
  21766. }
  21767. if (this.texture) {
  21768. this.texture.dispose();
  21769. this.texture = null;
  21770. }
  21771. // Remove from scene
  21772. var index = this._scene.layers.indexOf(this);
  21773. this._scene.layers.splice(index, 1);
  21774. // Callback
  21775. if (this.onDispose) {
  21776. this.onDispose();
  21777. }
  21778. };
  21779. return Layer;
  21780. })();
  21781. BABYLON.Layer = Layer;
  21782. })(BABYLON || (BABYLON = {}));
  21783. var BABYLON;
  21784. (function (BABYLON) {
  21785. var Particle = (function () {
  21786. function Particle() {
  21787. this.position = BABYLON.Vector3.Zero();
  21788. this.direction = BABYLON.Vector3.Zero();
  21789. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21790. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21791. this.lifeTime = 1.0;
  21792. this.age = 0;
  21793. this.size = 0;
  21794. this.angle = 0;
  21795. this.angularSpeed = 0;
  21796. }
  21797. Particle.prototype.copyTo = function (other) {
  21798. other.position.copyFrom(this.position);
  21799. other.direction.copyFrom(this.direction);
  21800. other.color.copyFrom(this.color);
  21801. other.colorStep.copyFrom(this.colorStep);
  21802. other.lifeTime = this.lifeTime;
  21803. other.age = this.age;
  21804. other.size = this.size;
  21805. other.angle = this.angle;
  21806. other.angularSpeed = this.angularSpeed;
  21807. };
  21808. return Particle;
  21809. })();
  21810. BABYLON.Particle = Particle;
  21811. })(BABYLON || (BABYLON = {}));
  21812. var BABYLON;
  21813. (function (BABYLON) {
  21814. var randomNumber = function (min, max) {
  21815. if (min === max) {
  21816. return (min);
  21817. }
  21818. var random = Math.random();
  21819. return ((random * (max - min)) + min);
  21820. };
  21821. var ParticleSystem = (function () {
  21822. function ParticleSystem(name, capacity, scene, customEffect) {
  21823. var _this = this;
  21824. this.name = name;
  21825. // Members
  21826. this.animations = [];
  21827. this.renderingGroupId = 0;
  21828. this.emitter = null;
  21829. this.emitRate = 10;
  21830. this.manualEmitCount = -1;
  21831. this.updateSpeed = 0.01;
  21832. this.targetStopDuration = 0;
  21833. this.disposeOnStop = false;
  21834. this.minEmitPower = 1;
  21835. this.maxEmitPower = 1;
  21836. this.minLifeTime = 1;
  21837. this.maxLifeTime = 1;
  21838. this.minSize = 1;
  21839. this.maxSize = 1;
  21840. this.minAngularSpeed = 0;
  21841. this.maxAngularSpeed = 0;
  21842. this.layerMask = 0x0FFFFFFF;
  21843. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21844. this.forceDepthWrite = false;
  21845. this.gravity = BABYLON.Vector3.Zero();
  21846. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21847. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21848. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21849. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21850. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21851. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21852. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21853. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21854. this.particles = new Array();
  21855. this._vertexDeclaration = [3, 4, 4];
  21856. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21857. this._stockParticles = new Array();
  21858. this._newPartsExcess = 0;
  21859. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21860. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21861. this._scaledDirection = BABYLON.Vector3.Zero();
  21862. this._scaledGravity = BABYLON.Vector3.Zero();
  21863. this._currentRenderId = -1;
  21864. this._started = false;
  21865. this._stopped = false;
  21866. this._actualFrame = 0;
  21867. this.id = name;
  21868. this._capacity = capacity;
  21869. this._scene = scene;
  21870. this._customEffect = customEffect;
  21871. scene.particleSystems.push(this);
  21872. // VBO
  21873. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21874. var indices = [];
  21875. var index = 0;
  21876. for (var count = 0; count < capacity; count++) {
  21877. indices.push(index);
  21878. indices.push(index + 1);
  21879. indices.push(index + 2);
  21880. indices.push(index);
  21881. indices.push(index + 2);
  21882. indices.push(index + 3);
  21883. index += 4;
  21884. }
  21885. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21886. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21887. // Default behaviors
  21888. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21889. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21890. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21891. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21892. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21893. };
  21894. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21895. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21896. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21897. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21898. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21899. };
  21900. this.updateFunction = function (particles) {
  21901. for (var index = 0; index < particles.length; index++) {
  21902. var particle = particles[index];
  21903. particle.age += _this._scaledUpdateSpeed;
  21904. if (particle.age >= particle.lifeTime) {
  21905. _this.recycleParticle(particle);
  21906. index--;
  21907. continue;
  21908. }
  21909. else {
  21910. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21911. particle.color.addInPlace(_this._scaledColorStep);
  21912. if (particle.color.a < 0)
  21913. particle.color.a = 0;
  21914. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21915. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21916. particle.position.addInPlace(_this._scaledDirection);
  21917. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21918. particle.direction.addInPlace(_this._scaledGravity);
  21919. }
  21920. }
  21921. };
  21922. }
  21923. ParticleSystem.prototype.recycleParticle = function (particle) {
  21924. var lastParticle = this.particles.pop();
  21925. if (lastParticle !== particle) {
  21926. lastParticle.copyTo(particle);
  21927. this._stockParticles.push(lastParticle);
  21928. }
  21929. };
  21930. ParticleSystem.prototype.getCapacity = function () {
  21931. return this._capacity;
  21932. };
  21933. ParticleSystem.prototype.isAlive = function () {
  21934. return this._alive;
  21935. };
  21936. ParticleSystem.prototype.isStarted = function () {
  21937. return this._started;
  21938. };
  21939. ParticleSystem.prototype.start = function () {
  21940. this._started = true;
  21941. this._stopped = false;
  21942. this._actualFrame = 0;
  21943. };
  21944. ParticleSystem.prototype.stop = function () {
  21945. this._stopped = true;
  21946. };
  21947. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21948. var offset = index * 11;
  21949. this._vertices[offset] = particle.position.x;
  21950. this._vertices[offset + 1] = particle.position.y;
  21951. this._vertices[offset + 2] = particle.position.z;
  21952. this._vertices[offset + 3] = particle.color.r;
  21953. this._vertices[offset + 4] = particle.color.g;
  21954. this._vertices[offset + 5] = particle.color.b;
  21955. this._vertices[offset + 6] = particle.color.a;
  21956. this._vertices[offset + 7] = particle.angle;
  21957. this._vertices[offset + 8] = particle.size;
  21958. this._vertices[offset + 9] = offsetX;
  21959. this._vertices[offset + 10] = offsetY;
  21960. };
  21961. ParticleSystem.prototype._update = function (newParticles) {
  21962. // Update current
  21963. this._alive = this.particles.length > 0;
  21964. this.updateFunction(this.particles);
  21965. // Add new ones
  21966. var worldMatrix;
  21967. if (this.emitter.position) {
  21968. worldMatrix = this.emitter.getWorldMatrix();
  21969. }
  21970. else {
  21971. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21972. }
  21973. var particle;
  21974. for (var index = 0; index < newParticles; index++) {
  21975. if (this.particles.length === this._capacity) {
  21976. break;
  21977. }
  21978. if (this._stockParticles.length !== 0) {
  21979. particle = this._stockParticles.pop();
  21980. particle.age = 0;
  21981. }
  21982. else {
  21983. particle = new BABYLON.Particle();
  21984. }
  21985. this.particles.push(particle);
  21986. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21987. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21988. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21989. particle.size = randomNumber(this.minSize, this.maxSize);
  21990. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21991. this.startPositionFunction(worldMatrix, particle.position, particle);
  21992. var step = randomNumber(0, 1.0);
  21993. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21994. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21995. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21996. }
  21997. };
  21998. ParticleSystem.prototype._getEffect = function () {
  21999. if (this._customEffect) {
  22000. return this._customEffect;
  22001. }
  22002. ;
  22003. var defines = [];
  22004. if (this._scene.clipPlane) {
  22005. defines.push("#define CLIPPLANE");
  22006. }
  22007. // Effect
  22008. var join = defines.join("\n");
  22009. if (this._cachedDefines !== join) {
  22010. this._cachedDefines = join;
  22011. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22012. }
  22013. return this._effect;
  22014. };
  22015. ParticleSystem.prototype.animate = function () {
  22016. if (!this._started)
  22017. return;
  22018. var effect = this._getEffect();
  22019. // Check
  22020. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22021. return;
  22022. if (this._currentRenderId === this._scene.getRenderId()) {
  22023. return;
  22024. }
  22025. this._currentRenderId = this._scene.getRenderId();
  22026. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22027. // determine the number of particles we need to create
  22028. var newParticles;
  22029. if (this.manualEmitCount > -1) {
  22030. newParticles = this.manualEmitCount;
  22031. this._newPartsExcess = 0;
  22032. this.manualEmitCount = 0;
  22033. }
  22034. else {
  22035. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22036. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22037. }
  22038. if (this._newPartsExcess > 1.0) {
  22039. newParticles += this._newPartsExcess >> 0;
  22040. this._newPartsExcess -= this._newPartsExcess >> 0;
  22041. }
  22042. this._alive = false;
  22043. if (!this._stopped) {
  22044. this._actualFrame += this._scaledUpdateSpeed;
  22045. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22046. this.stop();
  22047. }
  22048. else {
  22049. newParticles = 0;
  22050. }
  22051. this._update(newParticles);
  22052. // Stopped?
  22053. if (this._stopped) {
  22054. if (!this._alive) {
  22055. this._started = false;
  22056. if (this.disposeOnStop) {
  22057. this._scene._toBeDisposed.push(this);
  22058. }
  22059. }
  22060. }
  22061. // Update VBO
  22062. var offset = 0;
  22063. for (var index = 0; index < this.particles.length; index++) {
  22064. var particle = this.particles[index];
  22065. this._appendParticleVertex(offset++, particle, 0, 0);
  22066. this._appendParticleVertex(offset++, particle, 1, 0);
  22067. this._appendParticleVertex(offset++, particle, 1, 1);
  22068. this._appendParticleVertex(offset++, particle, 0, 1);
  22069. }
  22070. var engine = this._scene.getEngine();
  22071. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22072. };
  22073. ParticleSystem.prototype.render = function () {
  22074. var effect = this._getEffect();
  22075. // Check
  22076. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22077. return 0;
  22078. var engine = this._scene.getEngine();
  22079. // Render
  22080. engine.enableEffect(effect);
  22081. engine.setState(false);
  22082. var viewMatrix = this._scene.getViewMatrix();
  22083. effect.setTexture("diffuseSampler", this.particleTexture);
  22084. effect.setMatrix("view", viewMatrix);
  22085. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22086. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22087. if (this._scene.clipPlane) {
  22088. var clipPlane = this._scene.clipPlane;
  22089. var invView = viewMatrix.clone();
  22090. invView.invert();
  22091. effect.setMatrix("invView", invView);
  22092. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22093. }
  22094. // VBOs
  22095. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22096. // Draw order
  22097. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22098. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22099. }
  22100. else {
  22101. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22102. }
  22103. if (this.forceDepthWrite) {
  22104. engine.setDepthWrite(true);
  22105. }
  22106. engine.draw(true, 0, this.particles.length * 6);
  22107. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22108. return this.particles.length;
  22109. };
  22110. ParticleSystem.prototype.dispose = function () {
  22111. if (this._vertexBuffer) {
  22112. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22113. this._vertexBuffer = null;
  22114. }
  22115. if (this._indexBuffer) {
  22116. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22117. this._indexBuffer = null;
  22118. }
  22119. if (this.particleTexture) {
  22120. this.particleTexture.dispose();
  22121. this.particleTexture = null;
  22122. }
  22123. // Remove from scene
  22124. var index = this._scene.particleSystems.indexOf(this);
  22125. this._scene.particleSystems.splice(index, 1);
  22126. // Callback
  22127. if (this.onDispose) {
  22128. this.onDispose();
  22129. }
  22130. };
  22131. // Clone
  22132. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22133. var result = new ParticleSystem(name, this._capacity, this._scene);
  22134. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22135. if (newEmitter === undefined) {
  22136. newEmitter = this.emitter;
  22137. }
  22138. result.emitter = newEmitter;
  22139. if (this.particleTexture) {
  22140. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22141. }
  22142. result.start();
  22143. return result;
  22144. };
  22145. ParticleSystem.prototype.serialize = function () {
  22146. var serializationObject = {};
  22147. serializationObject.name = this.name;
  22148. serializationObject.id = this.id;
  22149. // Emitter
  22150. if (this.emitter.position) {
  22151. serializationObject.emitterId = this.emitter.id;
  22152. }
  22153. else {
  22154. serializationObject.emitter = this.emitter.asArray();
  22155. }
  22156. serializationObject.capacity = this.getCapacity();
  22157. if (this.particleTexture) {
  22158. serializationObject.textureName = this.particleTexture.name;
  22159. }
  22160. // Animations
  22161. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22162. // Particle system
  22163. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22164. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22165. serializationObject.minSize = this.minSize;
  22166. serializationObject.maxSize = this.maxSize;
  22167. serializationObject.minEmitPower = this.minEmitPower;
  22168. serializationObject.maxEmitPower = this.maxEmitPower;
  22169. serializationObject.minLifeTime = this.minLifeTime;
  22170. serializationObject.maxLifeTime = this.maxLifeTime;
  22171. serializationObject.emitRate = this.emitRate;
  22172. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22173. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22174. serializationObject.gravity = this.gravity.asArray();
  22175. serializationObject.direction1 = this.direction1.asArray();
  22176. serializationObject.direction2 = this.direction2.asArray();
  22177. serializationObject.color1 = this.color1.asArray();
  22178. serializationObject.color2 = this.color2.asArray();
  22179. serializationObject.colorDead = this.colorDead.asArray();
  22180. serializationObject.updateSpeed = this.updateSpeed;
  22181. serializationObject.targetStopDuration = this.targetStopDuration;
  22182. serializationObject.textureMask = this.textureMask.asArray();
  22183. serializationObject.blendMode = this.blendMode;
  22184. return serializationObject;
  22185. };
  22186. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22187. var name = parsedParticleSystem.name;
  22188. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22189. if (parsedParticleSystem.id) {
  22190. particleSystem.id = parsedParticleSystem.id;
  22191. }
  22192. // Texture
  22193. if (parsedParticleSystem.textureName) {
  22194. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22195. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22196. }
  22197. // Emitter
  22198. if (parsedParticleSystem.emitterId) {
  22199. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22200. }
  22201. else {
  22202. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22203. }
  22204. // Animations
  22205. if (parsedParticleSystem.animations) {
  22206. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22207. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22208. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22209. }
  22210. }
  22211. // Particle system
  22212. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22213. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22214. particleSystem.minSize = parsedParticleSystem.minSize;
  22215. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22216. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22217. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22218. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22219. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22220. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22221. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22222. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22223. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22224. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22225. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22226. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22227. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22228. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22229. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22230. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22231. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22232. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22233. particleSystem.start();
  22234. return particleSystem;
  22235. };
  22236. // Statics
  22237. ParticleSystem.BLENDMODE_ONEONE = 0;
  22238. ParticleSystem.BLENDMODE_STANDARD = 1;
  22239. return ParticleSystem;
  22240. })();
  22241. BABYLON.ParticleSystem = ParticleSystem;
  22242. })(BABYLON || (BABYLON = {}));
  22243. var BABYLON;
  22244. (function (BABYLON) {
  22245. var AnimationRange = (function () {
  22246. function AnimationRange(name, from, to) {
  22247. this.name = name;
  22248. this.from = from;
  22249. this.to = to;
  22250. }
  22251. return AnimationRange;
  22252. })();
  22253. BABYLON.AnimationRange = AnimationRange;
  22254. /**
  22255. * Composed of a frame, and an action function
  22256. */
  22257. var AnimationEvent = (function () {
  22258. function AnimationEvent(frame, action, onlyOnce) {
  22259. this.frame = frame;
  22260. this.action = action;
  22261. this.onlyOnce = onlyOnce;
  22262. this.isDone = false;
  22263. }
  22264. return AnimationEvent;
  22265. })();
  22266. BABYLON.AnimationEvent = AnimationEvent;
  22267. var Animation = (function () {
  22268. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22269. this.name = name;
  22270. this.targetProperty = targetProperty;
  22271. this.framePerSecond = framePerSecond;
  22272. this.dataType = dataType;
  22273. this.loopMode = loopMode;
  22274. this._offsetsCache = {};
  22275. this._highLimitsCache = {};
  22276. this._stopped = false;
  22277. // The set of event that will be linked to this animation
  22278. this._events = new Array();
  22279. this.allowMatricesInterpolation = false;
  22280. this._ranges = {};
  22281. this.targetPropertyPath = targetProperty.split(".");
  22282. this.dataType = dataType;
  22283. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22284. }
  22285. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22286. var dataType = undefined;
  22287. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22288. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22289. }
  22290. else if (from instanceof BABYLON.Quaternion) {
  22291. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22292. }
  22293. else if (from instanceof BABYLON.Vector3) {
  22294. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22295. }
  22296. else if (from instanceof BABYLON.Vector2) {
  22297. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22298. }
  22299. else if (from instanceof BABYLON.Color3) {
  22300. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22301. }
  22302. if (dataType == undefined) {
  22303. return null;
  22304. }
  22305. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22306. var keys = [];
  22307. keys.push({ frame: 0, value: from });
  22308. keys.push({ frame: totalFrame, value: to });
  22309. animation.setKeys(keys);
  22310. if (easingFunction !== undefined) {
  22311. animation.setEasingFunction(easingFunction);
  22312. }
  22313. return animation;
  22314. };
  22315. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22316. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22317. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22318. };
  22319. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22320. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22321. node.animations.push(animation);
  22322. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22323. };
  22324. // Methods
  22325. /**
  22326. * Add an event to this animation.
  22327. */
  22328. Animation.prototype.addEvent = function (event) {
  22329. this._events.push(event);
  22330. };
  22331. /**
  22332. * Remove all events found at the given frame
  22333. * @param frame
  22334. */
  22335. Animation.prototype.removeEvents = function (frame) {
  22336. for (var index = 0; index < this._events.length; index++) {
  22337. if (this._events[index].frame === frame) {
  22338. this._events.splice(index, 1);
  22339. index--;
  22340. }
  22341. }
  22342. };
  22343. Animation.prototype.createRange = function (name, from, to) {
  22344. // check name not already in use; could happen for bones after serialized
  22345. if (!this._ranges[name]) {
  22346. this._ranges[name] = new AnimationRange(name, from, to);
  22347. }
  22348. };
  22349. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22350. if (deleteFrames === void 0) { deleteFrames = true; }
  22351. if (this._ranges[name]) {
  22352. if (deleteFrames) {
  22353. var from = this._ranges[name].from;
  22354. var to = this._ranges[name].to;
  22355. // this loop MUST go high to low for multiple splices to work
  22356. for (var key = this._keys.length - 1; key >= 0; key--) {
  22357. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22358. this._keys.splice(key, 1);
  22359. }
  22360. }
  22361. }
  22362. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22363. }
  22364. };
  22365. Animation.prototype.getRange = function (name) {
  22366. return this._ranges[name];
  22367. };
  22368. Animation.prototype.reset = function () {
  22369. this._offsetsCache = {};
  22370. this._highLimitsCache = {};
  22371. this.currentFrame = 0;
  22372. };
  22373. Animation.prototype.isStopped = function () {
  22374. return this._stopped;
  22375. };
  22376. Animation.prototype.getKeys = function () {
  22377. return this._keys;
  22378. };
  22379. Animation.prototype.getHighestFrame = function () {
  22380. var ret = 0;
  22381. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22382. if (ret < this._keys[key].frame) {
  22383. ret = this._keys[key].frame;
  22384. }
  22385. }
  22386. return ret;
  22387. };
  22388. Animation.prototype.getEasingFunction = function () {
  22389. return this._easingFunction;
  22390. };
  22391. Animation.prototype.setEasingFunction = function (easingFunction) {
  22392. this._easingFunction = easingFunction;
  22393. };
  22394. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22395. return startValue + (endValue - startValue) * gradient;
  22396. };
  22397. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22398. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22399. };
  22400. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22401. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22402. };
  22403. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22404. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22405. };
  22406. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22407. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22408. };
  22409. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22410. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22411. };
  22412. Animation.prototype.clone = function () {
  22413. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22414. if (this._keys) {
  22415. clone.setKeys(this._keys);
  22416. }
  22417. return clone;
  22418. };
  22419. Animation.prototype.setKeys = function (values) {
  22420. this._keys = values.slice(0);
  22421. this._offsetsCache = {};
  22422. this._highLimitsCache = {};
  22423. };
  22424. Animation.prototype._getKeyValue = function (value) {
  22425. if (typeof value === "function") {
  22426. return value();
  22427. }
  22428. return value;
  22429. };
  22430. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22431. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22432. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22433. }
  22434. this.currentFrame = currentFrame;
  22435. // Try to get a hash to find the right key
  22436. 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));
  22437. if (this._keys[startKey].frame >= currentFrame) {
  22438. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22439. startKey--;
  22440. }
  22441. }
  22442. for (var key = startKey; key < this._keys.length; key++) {
  22443. if (this._keys[key + 1].frame >= currentFrame) {
  22444. var startValue = this._getKeyValue(this._keys[key].value);
  22445. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22446. // gradient : percent of currentFrame between the frame inf and the frame sup
  22447. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22448. // check for easingFunction and correction of gradient
  22449. if (this._easingFunction != null) {
  22450. gradient = this._easingFunction.ease(gradient);
  22451. }
  22452. switch (this.dataType) {
  22453. // Float
  22454. case Animation.ANIMATIONTYPE_FLOAT:
  22455. switch (loopMode) {
  22456. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22457. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22458. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22459. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22460. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22461. }
  22462. break;
  22463. // Quaternion
  22464. case Animation.ANIMATIONTYPE_QUATERNION:
  22465. var quaternion = null;
  22466. switch (loopMode) {
  22467. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22468. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22469. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22470. break;
  22471. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22472. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22473. break;
  22474. }
  22475. return quaternion;
  22476. // Vector3
  22477. case Animation.ANIMATIONTYPE_VECTOR3:
  22478. switch (loopMode) {
  22479. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22480. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22481. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22482. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22483. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22484. }
  22485. // Vector2
  22486. case Animation.ANIMATIONTYPE_VECTOR2:
  22487. switch (loopMode) {
  22488. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22489. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22490. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22491. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22492. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22493. }
  22494. // Color3
  22495. case Animation.ANIMATIONTYPE_COLOR3:
  22496. switch (loopMode) {
  22497. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22498. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22499. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22500. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22501. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22502. }
  22503. // Matrix
  22504. case Animation.ANIMATIONTYPE_MATRIX:
  22505. switch (loopMode) {
  22506. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22507. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22508. if (this.allowMatricesInterpolation) {
  22509. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22510. }
  22511. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22512. return startValue;
  22513. }
  22514. default:
  22515. break;
  22516. }
  22517. break;
  22518. }
  22519. }
  22520. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22521. };
  22522. Animation.prototype.setValue = function (currentValue) {
  22523. // Set value
  22524. if (this.targetPropertyPath.length > 1) {
  22525. var property = this._target[this.targetPropertyPath[0]];
  22526. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22527. property = property[this.targetPropertyPath[index]];
  22528. }
  22529. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22530. }
  22531. else {
  22532. this._target[this.targetPropertyPath[0]] = currentValue;
  22533. }
  22534. if (this._target.markAsDirty) {
  22535. this._target.markAsDirty(this.targetProperty);
  22536. }
  22537. };
  22538. Animation.prototype.goToFrame = function (frame) {
  22539. if (frame < this._keys[0].frame) {
  22540. frame = this._keys[0].frame;
  22541. }
  22542. else if (frame > this._keys[this._keys.length - 1].frame) {
  22543. frame = this._keys[this._keys.length - 1].frame;
  22544. }
  22545. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22546. this.setValue(currentValue);
  22547. };
  22548. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22549. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22550. this._stopped = true;
  22551. return false;
  22552. }
  22553. var returnValue = true;
  22554. // Adding a start key at frame 0 if missing
  22555. if (this._keys[0].frame !== 0) {
  22556. var newKey = { frame: 0, value: this._keys[0].value };
  22557. this._keys.splice(0, 0, newKey);
  22558. }
  22559. // Check limits
  22560. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22561. from = this._keys[0].frame;
  22562. }
  22563. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22564. to = this._keys[this._keys.length - 1].frame;
  22565. }
  22566. // Compute ratio
  22567. var range = to - from;
  22568. var offsetValue;
  22569. // ratio represents the frame delta between from and to
  22570. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22571. var highLimitValue = 0;
  22572. if (ratio > range && !loop) {
  22573. returnValue = false;
  22574. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22575. }
  22576. else {
  22577. // Get max value if required
  22578. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22579. var keyOffset = to.toString() + from.toString();
  22580. if (!this._offsetsCache[keyOffset]) {
  22581. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22582. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22583. switch (this.dataType) {
  22584. // Float
  22585. case Animation.ANIMATIONTYPE_FLOAT:
  22586. this._offsetsCache[keyOffset] = toValue - fromValue;
  22587. break;
  22588. // Quaternion
  22589. case Animation.ANIMATIONTYPE_QUATERNION:
  22590. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22591. break;
  22592. // Vector3
  22593. case Animation.ANIMATIONTYPE_VECTOR3:
  22594. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22595. // Vector2
  22596. case Animation.ANIMATIONTYPE_VECTOR2:
  22597. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22598. // Color3
  22599. case Animation.ANIMATIONTYPE_COLOR3:
  22600. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22601. default:
  22602. break;
  22603. }
  22604. this._highLimitsCache[keyOffset] = toValue;
  22605. }
  22606. highLimitValue = this._highLimitsCache[keyOffset];
  22607. offsetValue = this._offsetsCache[keyOffset];
  22608. }
  22609. }
  22610. if (offsetValue === undefined) {
  22611. switch (this.dataType) {
  22612. // Float
  22613. case Animation.ANIMATIONTYPE_FLOAT:
  22614. offsetValue = 0;
  22615. break;
  22616. // Quaternion
  22617. case Animation.ANIMATIONTYPE_QUATERNION:
  22618. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22619. break;
  22620. // Vector3
  22621. case Animation.ANIMATIONTYPE_VECTOR3:
  22622. offsetValue = BABYLON.Vector3.Zero();
  22623. break;
  22624. // Vector2
  22625. case Animation.ANIMATIONTYPE_VECTOR2:
  22626. offsetValue = BABYLON.Vector2.Zero();
  22627. break;
  22628. // Color3
  22629. case Animation.ANIMATIONTYPE_COLOR3:
  22630. offsetValue = BABYLON.Color3.Black();
  22631. }
  22632. }
  22633. // Compute value
  22634. var repeatCount = (ratio / range) >> 0;
  22635. var currentFrame = returnValue ? from + ratio % range : to;
  22636. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22637. // Set value
  22638. this.setValue(currentValue);
  22639. // Check events
  22640. for (var index = 0; index < this._events.length; index++) {
  22641. if (currentFrame >= this._events[index].frame) {
  22642. var event = this._events[index];
  22643. if (!event.isDone) {
  22644. // If event should be done only once, remove it.
  22645. if (event.onlyOnce) {
  22646. this._events.splice(index, 1);
  22647. index--;
  22648. }
  22649. event.isDone = true;
  22650. event.action();
  22651. } // Don't do anything if the event has already be done.
  22652. }
  22653. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22654. // reset event, the animation is looping
  22655. this._events[index].isDone = false;
  22656. }
  22657. }
  22658. if (!returnValue) {
  22659. this._stopped = true;
  22660. }
  22661. return returnValue;
  22662. };
  22663. Animation.prototype.serialize = function () {
  22664. var serializationObject = {};
  22665. serializationObject.name = this.name;
  22666. serializationObject.property = this.targetProperty;
  22667. serializationObject.framePerSecond = this.framePerSecond;
  22668. serializationObject.dataType = this.dataType;
  22669. serializationObject.loopBehavior = this.loopMode;
  22670. var dataType = this.dataType;
  22671. serializationObject.keys = [];
  22672. var keys = this.getKeys();
  22673. for (var index = 0; index < keys.length; index++) {
  22674. var animationKey = keys[index];
  22675. var key = {};
  22676. key.frame = animationKey.frame;
  22677. switch (dataType) {
  22678. case Animation.ANIMATIONTYPE_FLOAT:
  22679. key.values = [animationKey.value];
  22680. break;
  22681. case Animation.ANIMATIONTYPE_QUATERNION:
  22682. case Animation.ANIMATIONTYPE_MATRIX:
  22683. case Animation.ANIMATIONTYPE_VECTOR3:
  22684. case Animation.ANIMATIONTYPE_COLOR3:
  22685. key.values = animationKey.value.asArray();
  22686. break;
  22687. }
  22688. serializationObject.keys.push(key);
  22689. }
  22690. serializationObject.ranges = [];
  22691. for (var name in this._ranges) {
  22692. var range = {};
  22693. range.name = name;
  22694. range.from = this._ranges[name].from;
  22695. range.to = this._ranges[name].to;
  22696. serializationObject.ranges.push(range);
  22697. }
  22698. return serializationObject;
  22699. };
  22700. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22701. get: function () {
  22702. return Animation._ANIMATIONTYPE_FLOAT;
  22703. },
  22704. enumerable: true,
  22705. configurable: true
  22706. });
  22707. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22708. get: function () {
  22709. return Animation._ANIMATIONTYPE_VECTOR3;
  22710. },
  22711. enumerable: true,
  22712. configurable: true
  22713. });
  22714. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22715. get: function () {
  22716. return Animation._ANIMATIONTYPE_VECTOR2;
  22717. },
  22718. enumerable: true,
  22719. configurable: true
  22720. });
  22721. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22722. get: function () {
  22723. return Animation._ANIMATIONTYPE_QUATERNION;
  22724. },
  22725. enumerable: true,
  22726. configurable: true
  22727. });
  22728. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22729. get: function () {
  22730. return Animation._ANIMATIONTYPE_MATRIX;
  22731. },
  22732. enumerable: true,
  22733. configurable: true
  22734. });
  22735. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22736. get: function () {
  22737. return Animation._ANIMATIONTYPE_COLOR3;
  22738. },
  22739. enumerable: true,
  22740. configurable: true
  22741. });
  22742. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22743. get: function () {
  22744. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22745. },
  22746. enumerable: true,
  22747. configurable: true
  22748. });
  22749. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22750. get: function () {
  22751. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22752. },
  22753. enumerable: true,
  22754. configurable: true
  22755. });
  22756. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22757. get: function () {
  22758. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22759. },
  22760. enumerable: true,
  22761. configurable: true
  22762. });
  22763. Animation.Parse = function (parsedAnimation) {
  22764. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22765. var dataType = parsedAnimation.dataType;
  22766. var keys = [];
  22767. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22768. var key = parsedAnimation.keys[index];
  22769. var data;
  22770. switch (dataType) {
  22771. case Animation.ANIMATIONTYPE_FLOAT:
  22772. data = key.values[0];
  22773. break;
  22774. case Animation.ANIMATIONTYPE_QUATERNION:
  22775. data = BABYLON.Quaternion.FromArray(key.values);
  22776. break;
  22777. case Animation.ANIMATIONTYPE_MATRIX:
  22778. data = BABYLON.Matrix.FromArray(key.values);
  22779. break;
  22780. case Animation.ANIMATIONTYPE_COLOR3:
  22781. data = BABYLON.Color3.FromArray(key.values);
  22782. break;
  22783. case Animation.ANIMATIONTYPE_VECTOR3:
  22784. default:
  22785. data = BABYLON.Vector3.FromArray(key.values);
  22786. break;
  22787. }
  22788. keys.push({
  22789. frame: key.frame,
  22790. value: data
  22791. });
  22792. }
  22793. animation.setKeys(keys);
  22794. if (parsedAnimation.ranges) {
  22795. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22796. data = parsedAnimation.ranges[index];
  22797. animation.createRange(data.name, data.from, data.to);
  22798. }
  22799. }
  22800. return animation;
  22801. };
  22802. Animation.AppendSerializedAnimations = function (source, destination) {
  22803. if (source.animations) {
  22804. destination.animations = [];
  22805. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22806. var animation = source.animations[animationIndex];
  22807. destination.animations.push(animation.serialize());
  22808. }
  22809. }
  22810. };
  22811. // Statics
  22812. Animation._ANIMATIONTYPE_FLOAT = 0;
  22813. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22814. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22815. Animation._ANIMATIONTYPE_MATRIX = 3;
  22816. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22817. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22818. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22819. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22820. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22821. return Animation;
  22822. })();
  22823. BABYLON.Animation = Animation;
  22824. })(BABYLON || (BABYLON = {}));
  22825. var BABYLON;
  22826. (function (BABYLON) {
  22827. var Animatable = (function () {
  22828. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22829. if (fromFrame === void 0) { fromFrame = 0; }
  22830. if (toFrame === void 0) { toFrame = 100; }
  22831. if (loopAnimation === void 0) { loopAnimation = false; }
  22832. if (speedRatio === void 0) { speedRatio = 1.0; }
  22833. this.target = target;
  22834. this.fromFrame = fromFrame;
  22835. this.toFrame = toFrame;
  22836. this.loopAnimation = loopAnimation;
  22837. this.speedRatio = speedRatio;
  22838. this.onAnimationEnd = onAnimationEnd;
  22839. this._animations = new Array();
  22840. this._paused = false;
  22841. this.animationStarted = false;
  22842. if (animations) {
  22843. this.appendAnimations(target, animations);
  22844. }
  22845. this._scene = scene;
  22846. scene._activeAnimatables.push(this);
  22847. }
  22848. // Methods
  22849. Animatable.prototype.getAnimations = function () {
  22850. return this._animations;
  22851. };
  22852. Animatable.prototype.appendAnimations = function (target, animations) {
  22853. for (var index = 0; index < animations.length; index++) {
  22854. var animation = animations[index];
  22855. animation._target = target;
  22856. this._animations.push(animation);
  22857. }
  22858. };
  22859. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22860. var animations = this._animations;
  22861. for (var index = 0; index < animations.length; index++) {
  22862. if (animations[index].targetProperty === property) {
  22863. return animations[index];
  22864. }
  22865. }
  22866. return null;
  22867. };
  22868. Animatable.prototype.reset = function () {
  22869. var animations = this._animations;
  22870. for (var index = 0; index < animations.length; index++) {
  22871. animations[index].reset();
  22872. }
  22873. this._localDelayOffset = null;
  22874. this._pausedDelay = null;
  22875. };
  22876. Animatable.prototype.goToFrame = function (frame) {
  22877. var animations = this._animations;
  22878. for (var index = 0; index < animations.length; index++) {
  22879. animations[index].goToFrame(frame);
  22880. }
  22881. };
  22882. Animatable.prototype.pause = function () {
  22883. if (this._paused) {
  22884. return;
  22885. }
  22886. this._paused = true;
  22887. };
  22888. Animatable.prototype.restart = function () {
  22889. this._paused = false;
  22890. };
  22891. Animatable.prototype.stop = function () {
  22892. var index = this._scene._activeAnimatables.indexOf(this);
  22893. if (index > -1) {
  22894. this._scene._activeAnimatables.splice(index, 1);
  22895. if (this.onAnimationEnd) {
  22896. this.onAnimationEnd();
  22897. }
  22898. }
  22899. };
  22900. Animatable.prototype._animate = function (delay) {
  22901. if (this._paused) {
  22902. this.animationStarted = false;
  22903. if (!this._pausedDelay) {
  22904. this._pausedDelay = delay;
  22905. }
  22906. return true;
  22907. }
  22908. if (!this._localDelayOffset) {
  22909. this._localDelayOffset = delay;
  22910. }
  22911. else if (this._pausedDelay) {
  22912. this._localDelayOffset += delay - this._pausedDelay;
  22913. this._pausedDelay = null;
  22914. }
  22915. // Animating
  22916. var running = false;
  22917. var animations = this._animations;
  22918. var index;
  22919. for (index = 0; index < animations.length; index++) {
  22920. var animation = animations[index];
  22921. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22922. running = running || isRunning;
  22923. }
  22924. this.animationStarted = running;
  22925. if (!running) {
  22926. // Remove from active animatables
  22927. index = this._scene._activeAnimatables.indexOf(this);
  22928. this._scene._activeAnimatables.splice(index, 1);
  22929. }
  22930. if (!running && this.onAnimationEnd) {
  22931. this.onAnimationEnd();
  22932. this.onAnimationEnd = null;
  22933. }
  22934. return running;
  22935. };
  22936. return Animatable;
  22937. })();
  22938. BABYLON.Animatable = Animatable;
  22939. })(BABYLON || (BABYLON = {}));
  22940. var BABYLON;
  22941. (function (BABYLON) {
  22942. var EasingFunction = (function () {
  22943. function EasingFunction() {
  22944. // Properties
  22945. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22946. }
  22947. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22948. get: function () {
  22949. return EasingFunction._EASINGMODE_EASEIN;
  22950. },
  22951. enumerable: true,
  22952. configurable: true
  22953. });
  22954. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22955. get: function () {
  22956. return EasingFunction._EASINGMODE_EASEOUT;
  22957. },
  22958. enumerable: true,
  22959. configurable: true
  22960. });
  22961. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22962. get: function () {
  22963. return EasingFunction._EASINGMODE_EASEINOUT;
  22964. },
  22965. enumerable: true,
  22966. configurable: true
  22967. });
  22968. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22969. var n = Math.min(Math.max(easingMode, 0), 2);
  22970. this._easingMode = n;
  22971. };
  22972. EasingFunction.prototype.getEasingMode = function () {
  22973. return this._easingMode;
  22974. };
  22975. EasingFunction.prototype.easeInCore = function (gradient) {
  22976. throw new Error('You must implement this method');
  22977. };
  22978. EasingFunction.prototype.ease = function (gradient) {
  22979. switch (this._easingMode) {
  22980. case EasingFunction.EASINGMODE_EASEIN:
  22981. return this.easeInCore(gradient);
  22982. case EasingFunction.EASINGMODE_EASEOUT:
  22983. return (1 - this.easeInCore(1 - gradient));
  22984. }
  22985. if (gradient >= 0.5) {
  22986. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22987. }
  22988. return (this.easeInCore(gradient * 2) * 0.5);
  22989. };
  22990. //Statics
  22991. EasingFunction._EASINGMODE_EASEIN = 0;
  22992. EasingFunction._EASINGMODE_EASEOUT = 1;
  22993. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22994. return EasingFunction;
  22995. })();
  22996. BABYLON.EasingFunction = EasingFunction;
  22997. var CircleEase = (function (_super) {
  22998. __extends(CircleEase, _super);
  22999. function CircleEase() {
  23000. _super.apply(this, arguments);
  23001. }
  23002. CircleEase.prototype.easeInCore = function (gradient) {
  23003. gradient = Math.max(0, Math.min(1, gradient));
  23004. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23005. };
  23006. return CircleEase;
  23007. })(EasingFunction);
  23008. BABYLON.CircleEase = CircleEase;
  23009. var BackEase = (function (_super) {
  23010. __extends(BackEase, _super);
  23011. function BackEase(amplitude) {
  23012. if (amplitude === void 0) { amplitude = 1; }
  23013. _super.call(this);
  23014. this.amplitude = amplitude;
  23015. }
  23016. BackEase.prototype.easeInCore = function (gradient) {
  23017. var num = Math.max(0, this.amplitude);
  23018. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23019. };
  23020. return BackEase;
  23021. })(EasingFunction);
  23022. BABYLON.BackEase = BackEase;
  23023. var BounceEase = (function (_super) {
  23024. __extends(BounceEase, _super);
  23025. function BounceEase(bounces, bounciness) {
  23026. if (bounces === void 0) { bounces = 3; }
  23027. if (bounciness === void 0) { bounciness = 2; }
  23028. _super.call(this);
  23029. this.bounces = bounces;
  23030. this.bounciness = bounciness;
  23031. }
  23032. BounceEase.prototype.easeInCore = function (gradient) {
  23033. var y = Math.max(0.0, this.bounces);
  23034. var bounciness = this.bounciness;
  23035. if (bounciness <= 1.0) {
  23036. bounciness = 1.001;
  23037. }
  23038. var num9 = Math.pow(bounciness, y);
  23039. var num5 = 1.0 - bounciness;
  23040. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23041. var num15 = gradient * num4;
  23042. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23043. var num3 = Math.floor(num65);
  23044. var num13 = num3 + 1.0;
  23045. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23046. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23047. var num7 = (num8 + num12) * 0.5;
  23048. var num6 = gradient - num7;
  23049. var num2 = num7 - num8;
  23050. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23051. };
  23052. return BounceEase;
  23053. })(EasingFunction);
  23054. BABYLON.BounceEase = BounceEase;
  23055. var CubicEase = (function (_super) {
  23056. __extends(CubicEase, _super);
  23057. function CubicEase() {
  23058. _super.apply(this, arguments);
  23059. }
  23060. CubicEase.prototype.easeInCore = function (gradient) {
  23061. return (gradient * gradient * gradient);
  23062. };
  23063. return CubicEase;
  23064. })(EasingFunction);
  23065. BABYLON.CubicEase = CubicEase;
  23066. var ElasticEase = (function (_super) {
  23067. __extends(ElasticEase, _super);
  23068. function ElasticEase(oscillations, springiness) {
  23069. if (oscillations === void 0) { oscillations = 3; }
  23070. if (springiness === void 0) { springiness = 3; }
  23071. _super.call(this);
  23072. this.oscillations = oscillations;
  23073. this.springiness = springiness;
  23074. }
  23075. ElasticEase.prototype.easeInCore = function (gradient) {
  23076. var num2;
  23077. var num3 = Math.max(0.0, this.oscillations);
  23078. var num = Math.max(0.0, this.springiness);
  23079. if (num == 0) {
  23080. num2 = gradient;
  23081. }
  23082. else {
  23083. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23084. }
  23085. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23086. };
  23087. return ElasticEase;
  23088. })(EasingFunction);
  23089. BABYLON.ElasticEase = ElasticEase;
  23090. var ExponentialEase = (function (_super) {
  23091. __extends(ExponentialEase, _super);
  23092. function ExponentialEase(exponent) {
  23093. if (exponent === void 0) { exponent = 2; }
  23094. _super.call(this);
  23095. this.exponent = exponent;
  23096. }
  23097. ExponentialEase.prototype.easeInCore = function (gradient) {
  23098. if (this.exponent <= 0) {
  23099. return gradient;
  23100. }
  23101. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23102. };
  23103. return ExponentialEase;
  23104. })(EasingFunction);
  23105. BABYLON.ExponentialEase = ExponentialEase;
  23106. var PowerEase = (function (_super) {
  23107. __extends(PowerEase, _super);
  23108. function PowerEase(power) {
  23109. if (power === void 0) { power = 2; }
  23110. _super.call(this);
  23111. this.power = power;
  23112. }
  23113. PowerEase.prototype.easeInCore = function (gradient) {
  23114. var y = Math.max(0.0, this.power);
  23115. return Math.pow(gradient, y);
  23116. };
  23117. return PowerEase;
  23118. })(EasingFunction);
  23119. BABYLON.PowerEase = PowerEase;
  23120. var QuadraticEase = (function (_super) {
  23121. __extends(QuadraticEase, _super);
  23122. function QuadraticEase() {
  23123. _super.apply(this, arguments);
  23124. }
  23125. QuadraticEase.prototype.easeInCore = function (gradient) {
  23126. return (gradient * gradient);
  23127. };
  23128. return QuadraticEase;
  23129. })(EasingFunction);
  23130. BABYLON.QuadraticEase = QuadraticEase;
  23131. var QuarticEase = (function (_super) {
  23132. __extends(QuarticEase, _super);
  23133. function QuarticEase() {
  23134. _super.apply(this, arguments);
  23135. }
  23136. QuarticEase.prototype.easeInCore = function (gradient) {
  23137. return (gradient * gradient * gradient * gradient);
  23138. };
  23139. return QuarticEase;
  23140. })(EasingFunction);
  23141. BABYLON.QuarticEase = QuarticEase;
  23142. var QuinticEase = (function (_super) {
  23143. __extends(QuinticEase, _super);
  23144. function QuinticEase() {
  23145. _super.apply(this, arguments);
  23146. }
  23147. QuinticEase.prototype.easeInCore = function (gradient) {
  23148. return (gradient * gradient * gradient * gradient * gradient);
  23149. };
  23150. return QuinticEase;
  23151. })(EasingFunction);
  23152. BABYLON.QuinticEase = QuinticEase;
  23153. var SineEase = (function (_super) {
  23154. __extends(SineEase, _super);
  23155. function SineEase() {
  23156. _super.apply(this, arguments);
  23157. }
  23158. SineEase.prototype.easeInCore = function (gradient) {
  23159. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23160. };
  23161. return SineEase;
  23162. })(EasingFunction);
  23163. BABYLON.SineEase = SineEase;
  23164. var BezierCurveEase = (function (_super) {
  23165. __extends(BezierCurveEase, _super);
  23166. function BezierCurveEase(x1, y1, x2, y2) {
  23167. if (x1 === void 0) { x1 = 0; }
  23168. if (y1 === void 0) { y1 = 0; }
  23169. if (x2 === void 0) { x2 = 1; }
  23170. if (y2 === void 0) { y2 = 1; }
  23171. _super.call(this);
  23172. this.x1 = x1;
  23173. this.y1 = y1;
  23174. this.x2 = x2;
  23175. this.y2 = y2;
  23176. }
  23177. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23178. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23179. };
  23180. return BezierCurveEase;
  23181. })(EasingFunction);
  23182. BABYLON.BezierCurveEase = BezierCurveEase;
  23183. })(BABYLON || (BABYLON = {}));
  23184. var BABYLON;
  23185. (function (BABYLON) {
  23186. var Bone = (function (_super) {
  23187. __extends(Bone, _super);
  23188. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23189. _super.call(this, name, skeleton.getScene());
  23190. this.name = name;
  23191. this.children = new Array();
  23192. this.animations = new Array();
  23193. this._worldTransform = new BABYLON.Matrix();
  23194. this._absoluteTransform = new BABYLON.Matrix();
  23195. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23196. this._skeleton = skeleton;
  23197. this._matrix = matrix;
  23198. this._baseMatrix = matrix;
  23199. this._restPose = restPose ? restPose : matrix.clone();
  23200. skeleton.bones.push(this);
  23201. if (parentBone) {
  23202. this._parent = parentBone;
  23203. parentBone.children.push(this);
  23204. }
  23205. else {
  23206. this._parent = null;
  23207. }
  23208. this._updateDifferenceMatrix();
  23209. }
  23210. // Members
  23211. Bone.prototype.getParent = function () {
  23212. return this._parent;
  23213. };
  23214. Bone.prototype.getLocalMatrix = function () {
  23215. return this._matrix;
  23216. };
  23217. Bone.prototype.getBaseMatrix = function () {
  23218. return this._baseMatrix;
  23219. };
  23220. Bone.prototype.getRestPose = function () {
  23221. return this._restPose;
  23222. };
  23223. Bone.prototype.returnToRest = function () {
  23224. this.updateMatrix(this._restPose.clone());
  23225. };
  23226. Bone.prototype.getWorldMatrix = function () {
  23227. return this._worldTransform;
  23228. };
  23229. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23230. return this._invertedAbsoluteTransform;
  23231. };
  23232. Bone.prototype.getAbsoluteTransform = function () {
  23233. return this._absoluteTransform;
  23234. };
  23235. // Methods
  23236. Bone.prototype.updateMatrix = function (matrix) {
  23237. this._baseMatrix = matrix.clone();
  23238. this._matrix = matrix.clone();
  23239. this._skeleton._markAsDirty();
  23240. this._updateDifferenceMatrix();
  23241. };
  23242. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23243. if (!rootMatrix) {
  23244. rootMatrix = this._baseMatrix;
  23245. }
  23246. if (this._parent) {
  23247. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23248. }
  23249. else {
  23250. this._absoluteTransform.copyFrom(rootMatrix);
  23251. }
  23252. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23253. for (var index = 0; index < this.children.length; index++) {
  23254. this.children[index]._updateDifferenceMatrix();
  23255. }
  23256. };
  23257. Bone.prototype.markAsDirty = function () {
  23258. this._currentRenderId++;
  23259. this._skeleton._markAsDirty();
  23260. };
  23261. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23262. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23263. // all animation may be coming from a library skeleton, so may need to create animation
  23264. if (this.animations.length === 0) {
  23265. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23266. }
  23267. // get animation info / verify there is such a range from the source bone
  23268. var sourceRange = source.animations[0].getRange(rangeName);
  23269. if (!sourceRange) {
  23270. return false;
  23271. }
  23272. var from = sourceRange.from;
  23273. var to = sourceRange.to;
  23274. var sourceKeys = source.animations[0].getKeys();
  23275. // rescaling prep
  23276. var sourceBoneLength = source.length;
  23277. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23278. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23279. var destKeys = this.animations[0].getKeys();
  23280. // loop vars declaration / initialization
  23281. var orig;
  23282. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23283. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23284. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23285. var mat;
  23286. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23287. orig = sourceKeys[key];
  23288. if (orig.frame >= from && orig.frame <= to) {
  23289. if (scalingReqd) {
  23290. orig.value.decompose(origScale, origRotation, origTranslation);
  23291. origTranslation.scaleInPlace(ratio);
  23292. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23293. }
  23294. else {
  23295. mat = orig.value;
  23296. }
  23297. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23298. }
  23299. }
  23300. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23301. return true;
  23302. };
  23303. return Bone;
  23304. })(BABYLON.Node);
  23305. BABYLON.Bone = Bone;
  23306. })(BABYLON || (BABYLON = {}));
  23307. var BABYLON;
  23308. (function (BABYLON) {
  23309. var Skeleton = (function () {
  23310. function Skeleton(name, id, scene) {
  23311. this.name = name;
  23312. this.id = id;
  23313. this.bones = new Array();
  23314. this.needInitialSkinMatrix = false;
  23315. this._isDirty = true;
  23316. this._meshesWithPoseMatrix = new Array();
  23317. this._identity = BABYLON.Matrix.Identity();
  23318. this._ranges = {};
  23319. this.bones = [];
  23320. this._scene = scene;
  23321. scene.skeletons.push(this);
  23322. this.prepare();
  23323. //make sure it will recalculate the matrix next time prepare is called.
  23324. this._isDirty = true;
  23325. }
  23326. // Members
  23327. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23328. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23329. return mesh._bonesTransformMatrices;
  23330. }
  23331. return this._transformMatrices;
  23332. };
  23333. Skeleton.prototype.getScene = function () {
  23334. return this._scene;
  23335. };
  23336. // Methods
  23337. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23338. // check name not already in use
  23339. if (!this._ranges[name]) {
  23340. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23341. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23342. if (this.bones[i].animations[0]) {
  23343. this.bones[i].animations[0].createRange(name, from, to);
  23344. }
  23345. }
  23346. }
  23347. };
  23348. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23349. if (deleteFrames === void 0) { deleteFrames = true; }
  23350. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23351. if (this.bones[i].animations[0]) {
  23352. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23353. }
  23354. }
  23355. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23356. };
  23357. Skeleton.prototype.getAnimationRange = function (name) {
  23358. return this._ranges[name];
  23359. };
  23360. /**
  23361. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23362. */
  23363. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23364. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23365. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23366. return false;
  23367. }
  23368. var ret = true;
  23369. var frameOffset = this._getHighestAnimationFrame() + 1;
  23370. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23371. var boneDict = {};
  23372. var sourceBones = source.bones;
  23373. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23374. boneDict[sourceBones[i].name] = sourceBones[i];
  23375. }
  23376. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23377. var boneName = this.bones[i].name;
  23378. var sourceBone = boneDict[boneName];
  23379. if (sourceBone) {
  23380. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23381. }
  23382. else {
  23383. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23384. ret = false;
  23385. }
  23386. }
  23387. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23388. var range = source.getAnimationRange(name);
  23389. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23390. return ret;
  23391. };
  23392. Skeleton.prototype.returnToRest = function () {
  23393. for (var index = 0; index < this.bones.length; index++) {
  23394. this.bones[index].returnToRest();
  23395. }
  23396. };
  23397. Skeleton.prototype._getHighestAnimationFrame = function () {
  23398. var ret = 0;
  23399. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23400. if (this.bones[i].animations[0]) {
  23401. var highest = this.bones[i].animations[0].getHighestFrame();
  23402. if (ret < highest) {
  23403. ret = highest;
  23404. }
  23405. }
  23406. }
  23407. return ret;
  23408. };
  23409. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23410. var range = this.getAnimationRange(name);
  23411. if (!range) {
  23412. return null;
  23413. }
  23414. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23415. };
  23416. Skeleton.prototype._markAsDirty = function () {
  23417. this._isDirty = true;
  23418. };
  23419. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23420. this._meshesWithPoseMatrix.push(mesh);
  23421. };
  23422. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23423. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23424. if (index > -1) {
  23425. this._meshesWithPoseMatrix.splice(index, 1);
  23426. }
  23427. };
  23428. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23429. for (var index = 0; index < this.bones.length; index++) {
  23430. var bone = this.bones[index];
  23431. var parentBone = bone.getParent();
  23432. if (parentBone) {
  23433. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23434. }
  23435. else {
  23436. if (initialSkinMatrix) {
  23437. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23438. }
  23439. else {
  23440. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23441. }
  23442. }
  23443. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23444. }
  23445. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23446. };
  23447. Skeleton.prototype.prepare = function () {
  23448. if (!this._isDirty) {
  23449. return;
  23450. }
  23451. if (this.needInitialSkinMatrix) {
  23452. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23453. var mesh = this._meshesWithPoseMatrix[index];
  23454. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23455. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23456. }
  23457. var poseMatrix = mesh.getPoseMatrix();
  23458. // Prepare bones
  23459. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23460. var bone = this.bones[boneIndex];
  23461. if (!bone.getParent()) {
  23462. var matrix = bone.getBaseMatrix();
  23463. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23464. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23465. }
  23466. }
  23467. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23468. }
  23469. }
  23470. else {
  23471. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23472. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23473. }
  23474. this._computeTransformMatrices(this._transformMatrices, null);
  23475. }
  23476. this._isDirty = false;
  23477. this._scene._activeBones += this.bones.length;
  23478. };
  23479. Skeleton.prototype.getAnimatables = function () {
  23480. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23481. this._animatables = [];
  23482. for (var index = 0; index < this.bones.length; index++) {
  23483. this._animatables.push(this.bones[index]);
  23484. }
  23485. }
  23486. return this._animatables;
  23487. };
  23488. Skeleton.prototype.clone = function (name, id) {
  23489. var result = new Skeleton(name, id || name, this._scene);
  23490. for (var index = 0; index < this.bones.length; index++) {
  23491. var source = this.bones[index];
  23492. var parentBone = null;
  23493. if (source.getParent()) {
  23494. var parentIndex = this.bones.indexOf(source.getParent());
  23495. parentBone = result.bones[parentIndex];
  23496. }
  23497. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23498. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23499. }
  23500. return result;
  23501. };
  23502. Skeleton.prototype.dispose = function () {
  23503. this._meshesWithPoseMatrix = [];
  23504. // Animations
  23505. this.getScene().stopAnimation(this);
  23506. // Remove from scene
  23507. this.getScene().removeSkeleton(this);
  23508. };
  23509. Skeleton.prototype.serialize = function () {
  23510. var serializationObject = {};
  23511. serializationObject.name = this.name;
  23512. serializationObject.id = this.id;
  23513. serializationObject.bones = [];
  23514. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23515. for (var index = 0; index < this.bones.length; index++) {
  23516. var bone = this.bones[index];
  23517. var serializedBone = {
  23518. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23519. name: bone.name,
  23520. matrix: bone.getLocalMatrix().toArray(),
  23521. rest: bone.getRestPose().toArray()
  23522. };
  23523. serializationObject.bones.push(serializedBone);
  23524. if (bone.length) {
  23525. serializedBone.length = bone.length;
  23526. }
  23527. if (bone.animations && bone.animations.length > 0) {
  23528. serializedBone.animation = bone.animations[0].serialize();
  23529. }
  23530. serializationObject.ranges = [];
  23531. for (var name in this._ranges) {
  23532. var range = {};
  23533. range.name = name;
  23534. range.from = this._ranges[name].from;
  23535. range.to = this._ranges[name].to;
  23536. serializationObject.ranges.push(range);
  23537. }
  23538. }
  23539. return serializationObject;
  23540. };
  23541. Skeleton.Parse = function (parsedSkeleton, scene) {
  23542. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23543. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23544. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23545. var parsedBone = parsedSkeleton.bones[index];
  23546. var parentBone = null;
  23547. if (parsedBone.parentBoneIndex > -1) {
  23548. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23549. }
  23550. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23551. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23552. if (parsedBone.length) {
  23553. bone.length = parsedBone.length;
  23554. }
  23555. if (parsedBone.animation) {
  23556. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23557. }
  23558. }
  23559. // placed after bones, so createAnimationRange can cascade down
  23560. if (parsedSkeleton.ranges) {
  23561. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23562. var data = parsedSkeleton.ranges[index];
  23563. skeleton.createAnimationRange(data.name, data.from, data.to);
  23564. }
  23565. }
  23566. return skeleton;
  23567. };
  23568. return Skeleton;
  23569. })();
  23570. BABYLON.Skeleton = Skeleton;
  23571. })(BABYLON || (BABYLON = {}));
  23572. var BABYLON;
  23573. (function (BABYLON) {
  23574. var PostProcess = (function () {
  23575. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23577. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23578. this.name = name;
  23579. this.width = -1;
  23580. this.height = -1;
  23581. this._reusable = false;
  23582. this._textures = new BABYLON.SmartArray(2);
  23583. this._currentRenderTextureInd = 0;
  23584. if (camera != null) {
  23585. this._camera = camera;
  23586. this._scene = camera.getScene();
  23587. camera.attachPostProcess(this);
  23588. this._engine = this._scene.getEngine();
  23589. }
  23590. else {
  23591. this._engine = engine;
  23592. }
  23593. this._renderRatio = ratio;
  23594. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23595. this._reusable = reusable || false;
  23596. this._textureType = textureType;
  23597. this._samplers = samplers || [];
  23598. this._samplers.push("textureSampler");
  23599. this._fragmentUrl = fragmentUrl;
  23600. this._parameters = parameters || [];
  23601. this.updateEffect(defines);
  23602. }
  23603. PostProcess.prototype.updateEffect = function (defines) {
  23604. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23605. };
  23606. PostProcess.prototype.isReusable = function () {
  23607. return this._reusable;
  23608. };
  23609. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23610. camera = camera || this._camera;
  23611. var scene = camera.getScene();
  23612. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23613. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23614. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23615. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23616. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23617. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23618. if (this._textures.length > 0) {
  23619. for (var i = 0; i < this._textures.length; i++) {
  23620. this._engine._releaseTexture(this._textures.data[i]);
  23621. }
  23622. this._textures.reset();
  23623. }
  23624. this.width = desiredWidth;
  23625. this.height = desiredHeight;
  23626. 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 }));
  23627. if (this._reusable) {
  23628. 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 }));
  23629. }
  23630. if (this.onSizeChanged) {
  23631. this.onSizeChanged();
  23632. }
  23633. }
  23634. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23635. if (this.onActivate) {
  23636. this.onActivate(camera);
  23637. }
  23638. // Clear
  23639. if (this.clearColor) {
  23640. this._engine.clear(this.clearColor, true, true);
  23641. }
  23642. else {
  23643. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23644. }
  23645. if (this._reusable) {
  23646. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23647. }
  23648. };
  23649. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23650. get: function () {
  23651. return this._effect.isSupported;
  23652. },
  23653. enumerable: true,
  23654. configurable: true
  23655. });
  23656. PostProcess.prototype.apply = function () {
  23657. // Check
  23658. if (!this._effect.isReady())
  23659. return null;
  23660. // States
  23661. this._engine.enableEffect(this._effect);
  23662. this._engine.setState(false);
  23663. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23664. this._engine.setDepthBuffer(false);
  23665. this._engine.setDepthWrite(false);
  23666. // Texture
  23667. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23668. // Parameters
  23669. if (this.onApply) {
  23670. this.onApply(this._effect);
  23671. }
  23672. return this._effect;
  23673. };
  23674. PostProcess.prototype.dispose = function (camera) {
  23675. camera = camera || this._camera;
  23676. if (this._textures.length > 0) {
  23677. for (var i = 0; i < this._textures.length; i++) {
  23678. this._engine._releaseTexture(this._textures.data[i]);
  23679. }
  23680. this._textures.reset();
  23681. }
  23682. if (!camera) {
  23683. return;
  23684. }
  23685. camera.detachPostProcess(this);
  23686. var index = camera._postProcesses.indexOf(this);
  23687. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23688. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23689. }
  23690. };
  23691. return PostProcess;
  23692. })();
  23693. BABYLON.PostProcess = PostProcess;
  23694. })(BABYLON || (BABYLON = {}));
  23695. var BABYLON;
  23696. (function (BABYLON) {
  23697. var PostProcessManager = (function () {
  23698. function PostProcessManager(scene) {
  23699. this._vertexDeclaration = [2];
  23700. this._vertexStrideSize = 2 * 4;
  23701. this._scene = scene;
  23702. }
  23703. PostProcessManager.prototype._prepareBuffers = function () {
  23704. if (this._vertexBuffer) {
  23705. return;
  23706. }
  23707. // VBO
  23708. var vertices = [];
  23709. vertices.push(1, 1);
  23710. vertices.push(-1, 1);
  23711. vertices.push(-1, -1);
  23712. vertices.push(1, -1);
  23713. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23714. // Indices
  23715. var indices = [];
  23716. indices.push(0);
  23717. indices.push(1);
  23718. indices.push(2);
  23719. indices.push(0);
  23720. indices.push(2);
  23721. indices.push(3);
  23722. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23723. };
  23724. // Methods
  23725. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23726. var postProcesses = this._scene.activeCamera._postProcesses;
  23727. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23728. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23729. return false;
  23730. }
  23731. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23732. return true;
  23733. };
  23734. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23735. var engine = this._scene.getEngine();
  23736. for (var index = 0; index < postProcesses.length; index++) {
  23737. if (index < postProcesses.length - 1) {
  23738. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23739. }
  23740. else {
  23741. if (targetTexture) {
  23742. engine.bindFramebuffer(targetTexture);
  23743. }
  23744. else {
  23745. engine.restoreDefaultFramebuffer();
  23746. }
  23747. }
  23748. var pp = postProcesses[index];
  23749. var effect = pp.apply();
  23750. if (effect) {
  23751. if (pp.onBeforeRender) {
  23752. pp.onBeforeRender(effect);
  23753. }
  23754. // VBOs
  23755. this._prepareBuffers();
  23756. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23757. // Draw order
  23758. engine.draw(true, 0, 6);
  23759. if (pp.onAfterRender) {
  23760. pp.onAfterRender(effect);
  23761. }
  23762. }
  23763. }
  23764. // Restore depth buffer
  23765. engine.setDepthBuffer(true);
  23766. engine.setDepthWrite(true);
  23767. };
  23768. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23769. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23770. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23771. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23772. return;
  23773. }
  23774. var engine = this._scene.getEngine();
  23775. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23776. if (index < postProcessesTakenIndices.length - 1) {
  23777. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23778. }
  23779. else {
  23780. if (targetTexture) {
  23781. engine.bindFramebuffer(targetTexture, faceIndex);
  23782. }
  23783. else {
  23784. engine.restoreDefaultFramebuffer();
  23785. }
  23786. }
  23787. if (doNotPresent) {
  23788. break;
  23789. }
  23790. var pp = postProcesses[postProcessesTakenIndices[index]];
  23791. var effect = pp.apply();
  23792. if (effect) {
  23793. if (pp.onBeforeRender) {
  23794. pp.onBeforeRender(effect);
  23795. }
  23796. // VBOs
  23797. this._prepareBuffers();
  23798. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23799. // Draw order
  23800. engine.draw(true, 0, 6);
  23801. if (pp.onAfterRender) {
  23802. pp.onAfterRender(effect);
  23803. }
  23804. }
  23805. }
  23806. // Restore depth buffer
  23807. engine.setDepthBuffer(true);
  23808. engine.setDepthWrite(true);
  23809. };
  23810. PostProcessManager.prototype.dispose = function () {
  23811. if (this._vertexBuffer) {
  23812. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23813. this._vertexBuffer = null;
  23814. }
  23815. if (this._indexBuffer) {
  23816. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23817. this._indexBuffer = null;
  23818. }
  23819. };
  23820. return PostProcessManager;
  23821. })();
  23822. BABYLON.PostProcessManager = PostProcessManager;
  23823. })(BABYLON || (BABYLON = {}));
  23824. var BABYLON;
  23825. (function (BABYLON) {
  23826. var PassPostProcess = (function (_super) {
  23827. __extends(PassPostProcess, _super);
  23828. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23829. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23830. }
  23831. return PassPostProcess;
  23832. })(BABYLON.PostProcess);
  23833. BABYLON.PassPostProcess = PassPostProcess;
  23834. })(BABYLON || (BABYLON = {}));
  23835. var BABYLON;
  23836. (function (BABYLON) {
  23837. var PhysicsEngine = (function () {
  23838. function PhysicsEngine(plugin) {
  23839. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23840. }
  23841. PhysicsEngine.prototype._initialize = function (gravity) {
  23842. this._currentPlugin.initialize();
  23843. this._setGravity(gravity);
  23844. };
  23845. PhysicsEngine.prototype._runOneStep = function (delta) {
  23846. if (delta > 0.1) {
  23847. delta = 0.1;
  23848. }
  23849. else if (delta <= 0) {
  23850. delta = 1.0 / 60.0;
  23851. }
  23852. this._currentPlugin.runOneStep(delta);
  23853. };
  23854. PhysicsEngine.prototype._setGravity = function (gravity) {
  23855. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23856. this._currentPlugin.setGravity(this.gravity);
  23857. };
  23858. PhysicsEngine.prototype._getGravity = function () {
  23859. return this._currentPlugin.getGravity();
  23860. };
  23861. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23862. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23863. };
  23864. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23865. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23866. };
  23867. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23868. this._currentPlugin.unregisterMesh(mesh);
  23869. };
  23870. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23871. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23872. };
  23873. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23874. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23875. };
  23876. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23877. this._currentPlugin.updateBodyPosition(mesh);
  23878. };
  23879. PhysicsEngine.prototype.dispose = function () {
  23880. this._currentPlugin.dispose();
  23881. };
  23882. PhysicsEngine.prototype.isSupported = function () {
  23883. return this._currentPlugin.isSupported();
  23884. };
  23885. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23886. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23887. };
  23888. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23889. return this._currentPlugin.name;
  23890. };
  23891. PhysicsEngine.prototype.getWorldObject = function () {
  23892. return this._currentPlugin.getWorldObject();
  23893. };
  23894. // Statics
  23895. PhysicsEngine.NoImpostor = 0;
  23896. PhysicsEngine.SphereImpostor = 1;
  23897. PhysicsEngine.BoxImpostor = 2;
  23898. PhysicsEngine.PlaneImpostor = 3;
  23899. PhysicsEngine.MeshImpostor = 4;
  23900. PhysicsEngine.CapsuleImpostor = 5;
  23901. PhysicsEngine.ConeImpostor = 6;
  23902. PhysicsEngine.CylinderImpostor = 7;
  23903. PhysicsEngine.ConvexHullImpostor = 8;
  23904. PhysicsEngine.HeightmapImpostor = 9;
  23905. PhysicsEngine.Epsilon = 0.001;
  23906. return PhysicsEngine;
  23907. })();
  23908. BABYLON.PhysicsEngine = PhysicsEngine;
  23909. })(BABYLON || (BABYLON = {}));
  23910. var BABYLON;
  23911. (function (BABYLON) {
  23912. var VertexData = (function () {
  23913. function VertexData() {
  23914. }
  23915. VertexData.prototype.set = function (data, kind) {
  23916. switch (kind) {
  23917. case BABYLON.VertexBuffer.PositionKind:
  23918. this.positions = data;
  23919. break;
  23920. case BABYLON.VertexBuffer.NormalKind:
  23921. this.normals = data;
  23922. break;
  23923. case BABYLON.VertexBuffer.UVKind:
  23924. this.uvs = data;
  23925. break;
  23926. case BABYLON.VertexBuffer.UV2Kind:
  23927. this.uvs2 = data;
  23928. break;
  23929. case BABYLON.VertexBuffer.UV3Kind:
  23930. this.uvs3 = data;
  23931. break;
  23932. case BABYLON.VertexBuffer.UV4Kind:
  23933. this.uvs4 = data;
  23934. break;
  23935. case BABYLON.VertexBuffer.UV5Kind:
  23936. this.uvs5 = data;
  23937. break;
  23938. case BABYLON.VertexBuffer.UV6Kind:
  23939. this.uvs6 = data;
  23940. break;
  23941. case BABYLON.VertexBuffer.ColorKind:
  23942. this.colors = data;
  23943. break;
  23944. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23945. this.matricesIndices = data;
  23946. break;
  23947. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23948. this.matricesWeights = data;
  23949. break;
  23950. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23951. this.matricesIndicesExtra = data;
  23952. break;
  23953. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23954. this.matricesWeightsExtra = data;
  23955. break;
  23956. }
  23957. };
  23958. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23959. this._applyTo(mesh, updatable);
  23960. };
  23961. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23962. this._applyTo(geometry, updatable);
  23963. };
  23964. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23965. this._update(mesh);
  23966. };
  23967. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23968. this._update(geometry);
  23969. };
  23970. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23971. if (this.positions) {
  23972. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23973. }
  23974. if (this.normals) {
  23975. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23976. }
  23977. if (this.uvs) {
  23978. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23979. }
  23980. if (this.uvs2) {
  23981. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23982. }
  23983. if (this.uvs3) {
  23984. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23985. }
  23986. if (this.uvs4) {
  23987. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23988. }
  23989. if (this.uvs5) {
  23990. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23991. }
  23992. if (this.uvs6) {
  23993. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23994. }
  23995. if (this.colors) {
  23996. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23997. }
  23998. if (this.matricesIndices) {
  23999. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24000. }
  24001. if (this.matricesWeights) {
  24002. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24003. }
  24004. if (this.matricesIndicesExtra) {
  24005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24006. }
  24007. if (this.matricesWeightsExtra) {
  24008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24009. }
  24010. if (this.indices) {
  24011. meshOrGeometry.setIndices(this.indices);
  24012. }
  24013. };
  24014. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24015. if (this.positions) {
  24016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24017. }
  24018. if (this.normals) {
  24019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24020. }
  24021. if (this.uvs) {
  24022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24023. }
  24024. if (this.uvs2) {
  24025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24026. }
  24027. if (this.uvs3) {
  24028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24029. }
  24030. if (this.uvs4) {
  24031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24032. }
  24033. if (this.uvs5) {
  24034. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24035. }
  24036. if (this.uvs6) {
  24037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24038. }
  24039. if (this.colors) {
  24040. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24041. }
  24042. if (this.matricesIndices) {
  24043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24044. }
  24045. if (this.matricesWeights) {
  24046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24047. }
  24048. if (this.matricesIndicesExtra) {
  24049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24050. }
  24051. if (this.matricesWeightsExtra) {
  24052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24053. }
  24054. if (this.indices) {
  24055. meshOrGeometry.setIndices(this.indices);
  24056. }
  24057. };
  24058. VertexData.prototype.transform = function (matrix) {
  24059. var transformed = BABYLON.Vector3.Zero();
  24060. var index;
  24061. if (this.positions) {
  24062. var position = BABYLON.Vector3.Zero();
  24063. for (index = 0; index < this.positions.length; index += 3) {
  24064. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24065. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24066. this.positions[index] = transformed.x;
  24067. this.positions[index + 1] = transformed.y;
  24068. this.positions[index + 2] = transformed.z;
  24069. }
  24070. }
  24071. if (this.normals) {
  24072. var normal = BABYLON.Vector3.Zero();
  24073. for (index = 0; index < this.normals.length; index += 3) {
  24074. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24075. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24076. this.normals[index] = transformed.x;
  24077. this.normals[index + 1] = transformed.y;
  24078. this.normals[index + 2] = transformed.z;
  24079. }
  24080. }
  24081. };
  24082. VertexData.prototype.merge = function (other) {
  24083. if (other.indices) {
  24084. if (!this.indices) {
  24085. this.indices = [];
  24086. }
  24087. var offset = this.positions ? this.positions.length / 3 : 0;
  24088. for (var index = 0; index < other.indices.length; index++) {
  24089. //TODO check type - if Int32Array!
  24090. this.indices.push(other.indices[index] + offset);
  24091. }
  24092. }
  24093. this.positions = this._mergeElement(this.positions, other.positions);
  24094. this.normals = this._mergeElement(this.normals, other.normals);
  24095. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24096. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24097. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24098. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24099. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24100. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24101. this.colors = this._mergeElement(this.colors, other.colors);
  24102. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24103. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24104. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24105. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24106. };
  24107. VertexData.prototype._mergeElement = function (source, other) {
  24108. if (!other)
  24109. return source;
  24110. if (!source)
  24111. return other;
  24112. var len = other.length + source.length;
  24113. var isSrcTypedArray = source instanceof Float32Array;
  24114. var isOthTypedArray = other instanceof Float32Array;
  24115. // use non-loop method when the source is Float32Array
  24116. if (isSrcTypedArray) {
  24117. var ret32 = new Float32Array(len);
  24118. ret32.set(source);
  24119. ret32.set(other, source.length);
  24120. return ret32;
  24121. }
  24122. else if (!isOthTypedArray) {
  24123. return source.concat(other);
  24124. }
  24125. else {
  24126. var ret = source.slice(0); // copy source to a separate array
  24127. for (var i = 0, len = other.length; i < len; i++) {
  24128. ret.push(other[i]);
  24129. }
  24130. return ret;
  24131. }
  24132. };
  24133. VertexData.prototype.serialize = function () {
  24134. var serializationObject = this.serialize();
  24135. if (this.positions) {
  24136. serializationObject.positions = this.positions;
  24137. }
  24138. if (this.normals) {
  24139. serializationObject.normals = this.normals;
  24140. }
  24141. if (this.uvs) {
  24142. serializationObject.uvs = this.uvs;
  24143. }
  24144. if (this.uvs2) {
  24145. serializationObject.uvs2 = this.uvs2;
  24146. }
  24147. if (this.uvs3) {
  24148. serializationObject.uvs3 = this.uvs3;
  24149. }
  24150. if (this.uvs4) {
  24151. serializationObject.uvs4 = this.uvs4;
  24152. }
  24153. if (this.uvs5) {
  24154. serializationObject.uvs5 = this.uvs5;
  24155. }
  24156. if (this.uvs6) {
  24157. serializationObject.uvs6 = this.uvs6;
  24158. }
  24159. if (this.colors) {
  24160. serializationObject.colors = this.colors;
  24161. }
  24162. if (this.matricesIndices) {
  24163. serializationObject.matricesIndices = this.matricesIndices;
  24164. serializationObject.matricesIndices._isExpanded = true;
  24165. }
  24166. if (this.matricesWeights) {
  24167. serializationObject.matricesWeights = this.matricesWeights;
  24168. }
  24169. if (this.matricesIndicesExtra) {
  24170. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24171. serializationObject.matricesIndicesExtra._isExpanded = true;
  24172. }
  24173. if (this.matricesWeightsExtra) {
  24174. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24175. }
  24176. serializationObject.indices = this.indices;
  24177. return serializationObject;
  24178. };
  24179. // Statics
  24180. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24181. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24182. };
  24183. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24184. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24185. };
  24186. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24187. var result = new VertexData();
  24188. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24189. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24190. }
  24191. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24192. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24193. }
  24194. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24195. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24196. }
  24197. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24198. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24199. }
  24200. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24201. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24202. }
  24203. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24204. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24205. }
  24206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24207. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24208. }
  24209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24210. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24211. }
  24212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24213. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24214. }
  24215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24216. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24217. }
  24218. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24219. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24220. }
  24221. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24222. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24223. }
  24224. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24225. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24226. }
  24227. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24228. return result;
  24229. };
  24230. VertexData.CreateRibbon = function (options) {
  24231. var pathArray = options.pathArray;
  24232. var closeArray = options.closeArray || false;
  24233. var closePath = options.closePath || false;
  24234. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24235. var offset = options.offset || defaultOffset;
  24236. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24237. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24238. var positions = [];
  24239. var indices = [];
  24240. var normals = [];
  24241. var uvs = [];
  24242. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24243. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24244. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24245. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24246. var minlg; // minimal length among all paths from pathArray
  24247. var lg = []; // array of path lengths : nb of vertex per path
  24248. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24249. var p; // path iterator
  24250. var i; // point iterator
  24251. var j; // point iterator
  24252. // if single path in pathArray
  24253. if (pathArray.length < 2) {
  24254. var ar1 = [];
  24255. var ar2 = [];
  24256. for (i = 0; i < pathArray[0].length - offset; i++) {
  24257. ar1.push(pathArray[0][i]);
  24258. ar2.push(pathArray[0][i + offset]);
  24259. }
  24260. pathArray = [ar1, ar2];
  24261. }
  24262. // positions and horizontal distances (u)
  24263. var idc = 0;
  24264. var closePathCorr = (closePath) ? 1 : 0;
  24265. var path;
  24266. var l;
  24267. minlg = pathArray[0].length;
  24268. var vectlg;
  24269. var dist;
  24270. for (p = 0; p < pathArray.length; p++) {
  24271. uTotalDistance[p] = 0;
  24272. us[p] = [0];
  24273. path = pathArray[p];
  24274. l = path.length;
  24275. minlg = (minlg < l) ? minlg : l;
  24276. j = 0;
  24277. while (j < l) {
  24278. positions.push(path[j].x, path[j].y, path[j].z);
  24279. if (j > 0) {
  24280. vectlg = path[j].subtract(path[j - 1]).length();
  24281. dist = vectlg + uTotalDistance[p];
  24282. us[p].push(dist);
  24283. uTotalDistance[p] = dist;
  24284. }
  24285. j++;
  24286. }
  24287. if (closePath) {
  24288. j--;
  24289. positions.push(path[0].x, path[0].y, path[0].z);
  24290. vectlg = path[j].subtract(path[0]).length();
  24291. dist = vectlg + uTotalDistance[p];
  24292. us[p].push(dist);
  24293. uTotalDistance[p] = dist;
  24294. }
  24295. lg[p] = l + closePathCorr;
  24296. idx[p] = idc;
  24297. idc += (l + closePathCorr);
  24298. }
  24299. // vertical distances (v)
  24300. var path1;
  24301. var path2;
  24302. var vertex1;
  24303. var vertex2;
  24304. for (i = 0; i < minlg + closePathCorr; i++) {
  24305. vTotalDistance[i] = 0;
  24306. vs[i] = [0];
  24307. for (p = 0; p < pathArray.length - 1; p++) {
  24308. path1 = pathArray[p];
  24309. path2 = pathArray[p + 1];
  24310. if (i === minlg) {
  24311. vertex1 = path1[0];
  24312. vertex2 = path2[0];
  24313. }
  24314. else {
  24315. vertex1 = path1[i];
  24316. vertex2 = path2[i];
  24317. }
  24318. vectlg = vertex2.subtract(vertex1).length();
  24319. dist = vectlg + vTotalDistance[i];
  24320. vs[i].push(dist);
  24321. vTotalDistance[i] = dist;
  24322. }
  24323. if (closeArray) {
  24324. path1 = pathArray[p];
  24325. path2 = pathArray[0];
  24326. if (i === minlg) {
  24327. vertex2 = path2[0];
  24328. }
  24329. vectlg = vertex2.subtract(vertex1).length();
  24330. dist = vectlg + vTotalDistance[i];
  24331. vTotalDistance[i] = dist;
  24332. }
  24333. }
  24334. // uvs
  24335. var u;
  24336. var v;
  24337. for (p = 0; p < pathArray.length; p++) {
  24338. for (i = 0; i < minlg + closePathCorr; i++) {
  24339. u = us[p][i] / uTotalDistance[p];
  24340. v = vs[i][p] / vTotalDistance[i];
  24341. uvs.push(u, v);
  24342. }
  24343. }
  24344. // indices
  24345. p = 0; // path index
  24346. var pi = 0; // positions array index
  24347. var l1 = lg[p] - 1; // path1 length
  24348. var l2 = lg[p + 1] - 1; // path2 length
  24349. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24350. var shft = idx[1] - idx[0]; // shift
  24351. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24352. while (pi <= min && p < path1nb) {
  24353. // 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
  24354. indices.push(pi, pi + shft, pi + 1);
  24355. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24356. pi += 1;
  24357. if (pi === min) {
  24358. p++;
  24359. if (p === lg.length - 1) {
  24360. shft = idx[0] - idx[p];
  24361. l1 = lg[p] - 1;
  24362. l2 = lg[0] - 1;
  24363. }
  24364. else {
  24365. shft = idx[p + 1] - idx[p];
  24366. l1 = lg[p] - 1;
  24367. l2 = lg[p + 1] - 1;
  24368. }
  24369. pi = idx[p];
  24370. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24371. }
  24372. }
  24373. // normals
  24374. VertexData.ComputeNormals(positions, indices, normals);
  24375. if (closePath) {
  24376. var indexFirst = 0;
  24377. var indexLast = 0;
  24378. for (p = 0; p < pathArray.length; p++) {
  24379. indexFirst = idx[p] * 3;
  24380. if (p + 1 < pathArray.length) {
  24381. indexLast = (idx[p + 1] - 1) * 3;
  24382. }
  24383. else {
  24384. indexLast = normals.length - 3;
  24385. }
  24386. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24387. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24388. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24389. normals[indexLast] = normals[indexFirst];
  24390. normals[indexLast + 1] = normals[indexFirst + 1];
  24391. normals[indexLast + 2] = normals[indexFirst + 2];
  24392. }
  24393. }
  24394. // sides
  24395. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24396. // Result
  24397. var vertexData = new VertexData();
  24398. vertexData.indices = indices;
  24399. vertexData.positions = positions;
  24400. vertexData.normals = normals;
  24401. vertexData.uvs = uvs;
  24402. if (closePath) {
  24403. vertexData._idx = idx;
  24404. }
  24405. return vertexData;
  24406. };
  24407. VertexData.CreateBox = function (options) {
  24408. var normalsSource = [
  24409. new BABYLON.Vector3(0, 0, 1),
  24410. new BABYLON.Vector3(0, 0, -1),
  24411. new BABYLON.Vector3(1, 0, 0),
  24412. new BABYLON.Vector3(-1, 0, 0),
  24413. new BABYLON.Vector3(0, 1, 0),
  24414. new BABYLON.Vector3(0, -1, 0)
  24415. ];
  24416. var indices = [];
  24417. var positions = [];
  24418. var normals = [];
  24419. var uvs = [];
  24420. var width = options.width || options.size || 1;
  24421. var height = options.height || options.size || 1;
  24422. var depth = options.depth || options.size || 1;
  24423. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24424. var faceUV = options.faceUV || new Array(6);
  24425. var faceColors = options.faceColors;
  24426. var colors = [];
  24427. // default face colors and UV if undefined
  24428. for (var f = 0; f < 6; f++) {
  24429. if (faceUV[f] === undefined) {
  24430. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24431. }
  24432. if (faceColors && faceColors[f] === undefined) {
  24433. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24434. }
  24435. }
  24436. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24437. // Create each face in turn.
  24438. for (var index = 0; index < normalsSource.length; index++) {
  24439. var normal = normalsSource[index];
  24440. // Get two vectors perpendicular to the face normal and to each other.
  24441. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24442. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24443. // Six indices (two triangles) per face.
  24444. var verticesLength = positions.length / 3;
  24445. indices.push(verticesLength);
  24446. indices.push(verticesLength + 1);
  24447. indices.push(verticesLength + 2);
  24448. indices.push(verticesLength);
  24449. indices.push(verticesLength + 2);
  24450. indices.push(verticesLength + 3);
  24451. // Four vertices per face.
  24452. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24453. positions.push(vertex.x, vertex.y, vertex.z);
  24454. normals.push(normal.x, normal.y, normal.z);
  24455. uvs.push(faceUV[index].z, faceUV[index].w);
  24456. if (faceColors) {
  24457. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24458. }
  24459. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24460. positions.push(vertex.x, vertex.y, vertex.z);
  24461. normals.push(normal.x, normal.y, normal.z);
  24462. uvs.push(faceUV[index].x, faceUV[index].w);
  24463. if (faceColors) {
  24464. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24465. }
  24466. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24467. positions.push(vertex.x, vertex.y, vertex.z);
  24468. normals.push(normal.x, normal.y, normal.z);
  24469. uvs.push(faceUV[index].x, faceUV[index].y);
  24470. if (faceColors) {
  24471. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24472. }
  24473. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24474. positions.push(vertex.x, vertex.y, vertex.z);
  24475. normals.push(normal.x, normal.y, normal.z);
  24476. uvs.push(faceUV[index].z, faceUV[index].y);
  24477. if (faceColors) {
  24478. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24479. }
  24480. }
  24481. // sides
  24482. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24483. // Result
  24484. var vertexData = new VertexData();
  24485. vertexData.indices = indices;
  24486. vertexData.positions = positions;
  24487. vertexData.normals = normals;
  24488. vertexData.uvs = uvs;
  24489. if (faceColors) {
  24490. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24491. vertexData.colors = totalColors;
  24492. }
  24493. return vertexData;
  24494. };
  24495. VertexData.CreateSphere = function (options) {
  24496. var segments = options.segments || 32;
  24497. var diameterX = options.diameterX || options.diameter || 1;
  24498. var diameterY = options.diameterY || options.diameter || 1;
  24499. var diameterZ = options.diameterZ || options.diameter || 1;
  24500. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24501. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24502. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24503. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24504. var totalZRotationSteps = 2 + segments;
  24505. var totalYRotationSteps = 2 * totalZRotationSteps;
  24506. var indices = [];
  24507. var positions = [];
  24508. var normals = [];
  24509. var uvs = [];
  24510. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24511. var normalizedZ = zRotationStep / totalZRotationSteps;
  24512. var angleZ = normalizedZ * Math.PI * slice;
  24513. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24514. var normalizedY = yRotationStep / totalYRotationSteps;
  24515. var angleY = normalizedY * Math.PI * 2 * arc;
  24516. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24517. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24518. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24519. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24520. var vertex = complete.multiply(radius);
  24521. var normal = complete.divide(radius).normalize();
  24522. positions.push(vertex.x, vertex.y, vertex.z);
  24523. normals.push(normal.x, normal.y, normal.z);
  24524. uvs.push(normalizedY, normalizedZ);
  24525. }
  24526. if (zRotationStep > 0) {
  24527. var verticesCount = positions.length / 3;
  24528. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24529. indices.push((firstIndex));
  24530. indices.push((firstIndex + 1));
  24531. indices.push(firstIndex + totalYRotationSteps + 1);
  24532. indices.push((firstIndex + totalYRotationSteps + 1));
  24533. indices.push((firstIndex + 1));
  24534. indices.push((firstIndex + totalYRotationSteps + 2));
  24535. }
  24536. }
  24537. }
  24538. // Sides
  24539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24540. // Result
  24541. var vertexData = new VertexData();
  24542. vertexData.indices = indices;
  24543. vertexData.positions = positions;
  24544. vertexData.normals = normals;
  24545. vertexData.uvs = uvs;
  24546. return vertexData;
  24547. };
  24548. // Cylinder and cone
  24549. VertexData.CreateCylinder = function (options) {
  24550. var height = options.height || 2;
  24551. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24552. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24553. var tessellation = options.tessellation || 24;
  24554. var subdivisions = options.subdivisions || 1;
  24555. var hasRings = options.hasRings;
  24556. var enclose = options.enclose;
  24557. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24558. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24559. var faceUV = options.faceUV || new Array(3);
  24560. var faceColors = options.faceColors;
  24561. // default face colors and UV if undefined
  24562. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24563. var ringNb = (hasRings) ? subdivisions : 1;
  24564. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24565. var f;
  24566. for (f = 0; f < surfaceNb; f++) {
  24567. if (faceColors && faceColors[f] === undefined) {
  24568. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24569. }
  24570. }
  24571. for (f = 0; f < surfaceNb; f++) {
  24572. if (faceUV && faceUV[f] === undefined) {
  24573. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24574. }
  24575. }
  24576. var indices = [];
  24577. var positions = [];
  24578. var normals = [];
  24579. var uvs = [];
  24580. var colors = [];
  24581. var angle_step = Math.PI * 2 * arc / tessellation;
  24582. var angle;
  24583. var h;
  24584. var radius;
  24585. var tan = (diameterBottom - diameterTop) / 2 / height;
  24586. var ringVertex = BABYLON.Vector3.Zero();
  24587. var ringNormal = BABYLON.Vector3.Zero();
  24588. var ringFirstVertex = BABYLON.Vector3.Zero();
  24589. var ringFirstNormal = BABYLON.Vector3.Zero();
  24590. var quadNormal = BABYLON.Vector3.Zero();
  24591. var Y = BABYLON.Axis.Y;
  24592. // positions, normals, uvs
  24593. var i;
  24594. var j;
  24595. var r;
  24596. var ringIdx = 1;
  24597. var s = 1; // surface index
  24598. var cs = 0;
  24599. var v = 0;
  24600. for (i = 0; i <= subdivisions; i++) {
  24601. h = i / subdivisions;
  24602. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24603. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24604. for (r = 0; r < ringIdx; r++) {
  24605. if (hasRings) {
  24606. s += r;
  24607. }
  24608. if (enclose) {
  24609. s += 2 * r;
  24610. }
  24611. for (j = 0; j <= tessellation; j++) {
  24612. angle = j * angle_step;
  24613. // position
  24614. ringVertex.x = Math.cos(-angle) * radius;
  24615. ringVertex.y = -height / 2 + h * height;
  24616. ringVertex.z = Math.sin(-angle) * radius;
  24617. // normal
  24618. if (diameterTop === 0 && i === subdivisions) {
  24619. // if no top cap, reuse former normals
  24620. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24621. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24622. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24623. }
  24624. else {
  24625. ringNormal.x = ringVertex.x;
  24626. ringNormal.z = ringVertex.z;
  24627. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24628. ringNormal.normalize();
  24629. }
  24630. // keep first ring vertex values for enclose
  24631. if (j === 0) {
  24632. ringFirstVertex.copyFrom(ringVertex);
  24633. ringFirstNormal.copyFrom(ringNormal);
  24634. }
  24635. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24636. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24637. if (hasRings) {
  24638. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24639. }
  24640. else {
  24641. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24642. }
  24643. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24644. if (faceColors) {
  24645. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24646. }
  24647. }
  24648. // if enclose, add four vertices and their dedicated normals
  24649. if (arc !== 1 && enclose) {
  24650. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24651. positions.push(0, ringVertex.y, 0);
  24652. positions.push(0, ringVertex.y, 0);
  24653. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24654. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24655. quadNormal.normalize();
  24656. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24657. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24658. quadNormal.normalize();
  24659. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24660. if (hasRings) {
  24661. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24662. }
  24663. else {
  24664. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24665. }
  24666. uvs.push(faceUV[s + 1].x, v);
  24667. uvs.push(faceUV[s + 1].z, v);
  24668. if (hasRings) {
  24669. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24670. }
  24671. else {
  24672. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24673. }
  24674. uvs.push(faceUV[s + 2].x, v);
  24675. uvs.push(faceUV[s + 2].z, v);
  24676. if (faceColors) {
  24677. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24678. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24679. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24680. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24681. }
  24682. }
  24683. if (cs !== s) {
  24684. cs = s;
  24685. }
  24686. }
  24687. }
  24688. // indices
  24689. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24690. var s;
  24691. i = 0;
  24692. for (s = 0; s < subdivisions; s++) {
  24693. for (j = 0; j < tessellation; j++) {
  24694. var i0 = i * (e + 1) + j;
  24695. var i1 = (i + 1) * (e + 1) + j;
  24696. var i2 = i * (e + 1) + (j + 1);
  24697. var i3 = (i + 1) * (e + 1) + (j + 1);
  24698. indices.push(i0, i1, i2);
  24699. indices.push(i3, i2, i1);
  24700. }
  24701. if (arc !== 1 && enclose) {
  24702. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24703. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24704. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24705. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24706. }
  24707. i = (hasRings) ? (i + 2) : (i + 1);
  24708. }
  24709. // Caps
  24710. var createCylinderCap = function (isTop) {
  24711. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24712. if (radius === 0) {
  24713. return;
  24714. }
  24715. // Cap positions, normals & uvs
  24716. var angle;
  24717. var circleVector;
  24718. var i;
  24719. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24720. var c;
  24721. if (faceColors) {
  24722. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24723. }
  24724. // cap center
  24725. var vbase = positions.length / 3;
  24726. var offset = isTop ? height / 2 : -height / 2;
  24727. var center = new BABYLON.Vector3(0, offset, 0);
  24728. positions.push(center.x, center.y, center.z);
  24729. normals.push(0, isTop ? 1 : -1, 0);
  24730. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24731. if (faceColors) {
  24732. colors.push(c.r, c.g, c.b, c.a);
  24733. }
  24734. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24735. for (i = 0; i <= tessellation; i++) {
  24736. angle = Math.PI * 2 * i * arc / tessellation;
  24737. var cos = Math.cos(-angle);
  24738. var sin = Math.sin(-angle);
  24739. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24740. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24741. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24742. normals.push(0, isTop ? 1 : -1, 0);
  24743. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24744. if (faceColors) {
  24745. colors.push(c.r, c.g, c.b, c.a);
  24746. }
  24747. }
  24748. // Cap indices
  24749. for (i = 0; i < tessellation; i++) {
  24750. if (!isTop) {
  24751. indices.push(vbase);
  24752. indices.push(vbase + (i + 1));
  24753. indices.push(vbase + (i + 2));
  24754. }
  24755. else {
  24756. indices.push(vbase);
  24757. indices.push(vbase + (i + 2));
  24758. indices.push(vbase + (i + 1));
  24759. }
  24760. }
  24761. };
  24762. // add caps to geometry
  24763. createCylinderCap(false);
  24764. createCylinderCap(true);
  24765. // Sides
  24766. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24767. var vertexData = new VertexData();
  24768. vertexData.indices = indices;
  24769. vertexData.positions = positions;
  24770. vertexData.normals = normals;
  24771. vertexData.uvs = uvs;
  24772. if (faceColors) {
  24773. vertexData.colors = colors;
  24774. }
  24775. return vertexData;
  24776. };
  24777. VertexData.CreateTorus = function (options) {
  24778. var indices = [];
  24779. var positions = [];
  24780. var normals = [];
  24781. var uvs = [];
  24782. var diameter = options.diameter || 1;
  24783. var thickness = options.thickness || 0.5;
  24784. var tessellation = options.tessellation || 16;
  24785. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24786. var stride = tessellation + 1;
  24787. for (var i = 0; i <= tessellation; i++) {
  24788. var u = i / tessellation;
  24789. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24790. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24791. for (var j = 0; j <= tessellation; j++) {
  24792. var v = 1 - j / tessellation;
  24793. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24794. var dx = Math.cos(innerAngle);
  24795. var dy = Math.sin(innerAngle);
  24796. // Create a vertex.
  24797. var normal = new BABYLON.Vector3(dx, dy, 0);
  24798. var position = normal.scale(thickness / 2);
  24799. var textureCoordinate = new BABYLON.Vector2(u, v);
  24800. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24801. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24802. positions.push(position.x, position.y, position.z);
  24803. normals.push(normal.x, normal.y, normal.z);
  24804. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24805. // And create indices for two triangles.
  24806. var nextI = (i + 1) % stride;
  24807. var nextJ = (j + 1) % stride;
  24808. indices.push(i * stride + j);
  24809. indices.push(i * stride + nextJ);
  24810. indices.push(nextI * stride + j);
  24811. indices.push(i * stride + nextJ);
  24812. indices.push(nextI * stride + nextJ);
  24813. indices.push(nextI * stride + j);
  24814. }
  24815. }
  24816. // Sides
  24817. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24818. // Result
  24819. var vertexData = new VertexData();
  24820. vertexData.indices = indices;
  24821. vertexData.positions = positions;
  24822. vertexData.normals = normals;
  24823. vertexData.uvs = uvs;
  24824. return vertexData;
  24825. };
  24826. VertexData.CreateLineSystem = function (options) {
  24827. var indices = [];
  24828. var positions = [];
  24829. var lines = options.lines;
  24830. var idx = 0;
  24831. for (var l = 0; l < lines.length; l++) {
  24832. var points = lines[l];
  24833. for (var index = 0; index < points.length; index++) {
  24834. positions.push(points[index].x, points[index].y, points[index].z);
  24835. if (index > 0) {
  24836. indices.push(idx - 1);
  24837. indices.push(idx);
  24838. }
  24839. idx++;
  24840. }
  24841. }
  24842. var vertexData = new VertexData();
  24843. vertexData.indices = indices;
  24844. vertexData.positions = positions;
  24845. return vertexData;
  24846. };
  24847. VertexData.CreateDashedLines = function (options) {
  24848. var dashSize = options.dashSize || 3;
  24849. var gapSize = options.gapSize || 1;
  24850. var dashNb = options.dashNb || 200;
  24851. var points = options.points;
  24852. var positions = new Array();
  24853. var indices = new Array();
  24854. var curvect = BABYLON.Vector3.Zero();
  24855. var lg = 0;
  24856. var nb = 0;
  24857. var shft = 0;
  24858. var dashshft = 0;
  24859. var curshft = 0;
  24860. var idx = 0;
  24861. var i = 0;
  24862. for (i = 0; i < points.length - 1; i++) {
  24863. points[i + 1].subtractToRef(points[i], curvect);
  24864. lg += curvect.length();
  24865. }
  24866. shft = lg / dashNb;
  24867. dashshft = dashSize * shft / (dashSize + gapSize);
  24868. for (i = 0; i < points.length - 1; i++) {
  24869. points[i + 1].subtractToRef(points[i], curvect);
  24870. nb = Math.floor(curvect.length() / shft);
  24871. curvect.normalize();
  24872. for (var j = 0; j < nb; j++) {
  24873. curshft = shft * j;
  24874. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24875. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24876. indices.push(idx, idx + 1);
  24877. idx += 2;
  24878. }
  24879. }
  24880. // Result
  24881. var vertexData = new VertexData();
  24882. vertexData.positions = positions;
  24883. vertexData.indices = indices;
  24884. return vertexData;
  24885. };
  24886. VertexData.CreateGround = function (options) {
  24887. var indices = [];
  24888. var positions = [];
  24889. var normals = [];
  24890. var uvs = [];
  24891. var row, col;
  24892. var width = options.width || 1;
  24893. var height = options.height || 1;
  24894. var subdivisions = options.subdivisions || 1;
  24895. for (row = 0; row <= subdivisions; row++) {
  24896. for (col = 0; col <= subdivisions; col++) {
  24897. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24898. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24899. positions.push(position.x, position.y, position.z);
  24900. normals.push(normal.x, normal.y, normal.z);
  24901. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24902. }
  24903. }
  24904. for (row = 0; row < subdivisions; row++) {
  24905. for (col = 0; col < subdivisions; col++) {
  24906. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24907. indices.push(col + 1 + row * (subdivisions + 1));
  24908. indices.push(col + row * (subdivisions + 1));
  24909. indices.push(col + (row + 1) * (subdivisions + 1));
  24910. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24911. indices.push(col + row * (subdivisions + 1));
  24912. }
  24913. }
  24914. // Result
  24915. var vertexData = new VertexData();
  24916. vertexData.indices = indices;
  24917. vertexData.positions = positions;
  24918. vertexData.normals = normals;
  24919. vertexData.uvs = uvs;
  24920. return vertexData;
  24921. };
  24922. VertexData.CreateTiledGround = function (options) {
  24923. var xmin = options.xmin;
  24924. var zmin = options.zmin;
  24925. var xmax = options.xmax;
  24926. var zmax = options.zmax;
  24927. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24928. var precision = options.precision || { w: 1, h: 1 };
  24929. var indices = [];
  24930. var positions = [];
  24931. var normals = [];
  24932. var uvs = [];
  24933. var row, col, tileRow, tileCol;
  24934. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24935. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24936. precision.w = (precision.w < 1) ? 1 : precision.w;
  24937. precision.h = (precision.h < 1) ? 1 : precision.h;
  24938. var tileSize = {
  24939. 'w': (xmax - xmin) / subdivisions.w,
  24940. 'h': (zmax - zmin) / subdivisions.h
  24941. };
  24942. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24943. // Indices
  24944. var base = positions.length / 3;
  24945. var rowLength = precision.w + 1;
  24946. for (row = 0; row < precision.h; row++) {
  24947. for (col = 0; col < precision.w; col++) {
  24948. var square = [
  24949. base + col + row * rowLength,
  24950. base + (col + 1) + row * rowLength,
  24951. base + (col + 1) + (row + 1) * rowLength,
  24952. base + col + (row + 1) * rowLength
  24953. ];
  24954. indices.push(square[1]);
  24955. indices.push(square[2]);
  24956. indices.push(square[3]);
  24957. indices.push(square[0]);
  24958. indices.push(square[1]);
  24959. indices.push(square[3]);
  24960. }
  24961. }
  24962. // Position, normals and uvs
  24963. var position = BABYLON.Vector3.Zero();
  24964. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24965. for (row = 0; row <= precision.h; row++) {
  24966. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24967. for (col = 0; col <= precision.w; col++) {
  24968. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24969. position.y = 0;
  24970. positions.push(position.x, position.y, position.z);
  24971. normals.push(normal.x, normal.y, normal.z);
  24972. uvs.push(col / precision.w, row / precision.h);
  24973. }
  24974. }
  24975. }
  24976. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24977. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24978. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24979. }
  24980. }
  24981. // Result
  24982. var vertexData = new VertexData();
  24983. vertexData.indices = indices;
  24984. vertexData.positions = positions;
  24985. vertexData.normals = normals;
  24986. vertexData.uvs = uvs;
  24987. return vertexData;
  24988. };
  24989. VertexData.CreateGroundFromHeightMap = function (options) {
  24990. var indices = [];
  24991. var positions = [];
  24992. var normals = [];
  24993. var uvs = [];
  24994. var row, col;
  24995. // Vertices
  24996. for (row = 0; row <= options.subdivisions; row++) {
  24997. for (col = 0; col <= options.subdivisions; col++) {
  24998. 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));
  24999. // Compute height
  25000. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25001. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25002. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25003. var r = options.buffer[pos] / 255.0;
  25004. var g = options.buffer[pos + 1] / 255.0;
  25005. var b = options.buffer[pos + 2] / 255.0;
  25006. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25007. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25008. // Add vertex
  25009. positions.push(position.x, position.y, position.z);
  25010. normals.push(0, 0, 0);
  25011. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25012. }
  25013. }
  25014. // Indices
  25015. for (row = 0; row < options.subdivisions; row++) {
  25016. for (col = 0; col < options.subdivisions; col++) {
  25017. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25018. indices.push(col + 1 + row * (options.subdivisions + 1));
  25019. indices.push(col + row * (options.subdivisions + 1));
  25020. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25021. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25022. indices.push(col + row * (options.subdivisions + 1));
  25023. }
  25024. }
  25025. // Normals
  25026. VertexData.ComputeNormals(positions, indices, normals);
  25027. // Result
  25028. var vertexData = new VertexData();
  25029. vertexData.indices = indices;
  25030. vertexData.positions = positions;
  25031. vertexData.normals = normals;
  25032. vertexData.uvs = uvs;
  25033. return vertexData;
  25034. };
  25035. VertexData.CreatePlane = function (options) {
  25036. var indices = [];
  25037. var positions = [];
  25038. var normals = [];
  25039. var uvs = [];
  25040. var width = options.width || options.size || 1;
  25041. var height = options.height || options.size || 1;
  25042. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25043. // Vertices
  25044. var halfWidth = width / 2.0;
  25045. var halfHeight = height / 2.0;
  25046. positions.push(-halfWidth, -halfHeight, 0);
  25047. normals.push(0, 0, -1.0);
  25048. uvs.push(0.0, 0.0);
  25049. positions.push(halfWidth, -halfHeight, 0);
  25050. normals.push(0, 0, -1.0);
  25051. uvs.push(1.0, 0.0);
  25052. positions.push(halfWidth, halfHeight, 0);
  25053. normals.push(0, 0, -1.0);
  25054. uvs.push(1.0, 1.0);
  25055. positions.push(-halfWidth, halfHeight, 0);
  25056. normals.push(0, 0, -1.0);
  25057. uvs.push(0.0, 1.0);
  25058. // Indices
  25059. indices.push(0);
  25060. indices.push(1);
  25061. indices.push(2);
  25062. indices.push(0);
  25063. indices.push(2);
  25064. indices.push(3);
  25065. // Sides
  25066. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25067. // Result
  25068. var vertexData = new VertexData();
  25069. vertexData.indices = indices;
  25070. vertexData.positions = positions;
  25071. vertexData.normals = normals;
  25072. vertexData.uvs = uvs;
  25073. return vertexData;
  25074. };
  25075. VertexData.CreateDisc = function (options) {
  25076. var positions = [];
  25077. var indices = [];
  25078. var normals = [];
  25079. var uvs = [];
  25080. var radius = options.radius || 0.5;
  25081. var tessellation = options.tessellation || 64;
  25082. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25083. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25084. // positions and uvs
  25085. positions.push(0, 0, 0); // disc center first
  25086. uvs.push(0.5, 0.5);
  25087. var theta = Math.PI * 2 * arc;
  25088. var step = theta / tessellation;
  25089. for (var a = 0; a < theta; a += step) {
  25090. var x = Math.cos(a);
  25091. var y = Math.sin(a);
  25092. var u = (x + 1) / 2;
  25093. var v = (1 - y) / 2;
  25094. positions.push(radius * x, radius * y, 0);
  25095. uvs.push(u, v);
  25096. }
  25097. if (arc === 1) {
  25098. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25099. uvs.push(uvs[2], uvs[3]);
  25100. }
  25101. //indices
  25102. var vertexNb = positions.length / 3;
  25103. for (var i = 1; i < vertexNb - 1; i++) {
  25104. indices.push(i + 1, 0, i);
  25105. }
  25106. // result
  25107. VertexData.ComputeNormals(positions, indices, normals);
  25108. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25109. var vertexData = new VertexData();
  25110. vertexData.indices = indices;
  25111. vertexData.positions = positions;
  25112. vertexData.normals = normals;
  25113. vertexData.uvs = uvs;
  25114. return vertexData;
  25115. };
  25116. VertexData.CreateIcoSphere = function (options) {
  25117. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25118. var radius = options.radius || 1;
  25119. var flat = (options.flat === undefined) ? true : options.flat;
  25120. var subdivisions = options.subdivisions || 4;
  25121. var radiusX = options.radiusX || radius;
  25122. var radiusY = options.radiusY || radius;
  25123. var radiusZ = options.radiusZ || radius;
  25124. var t = (1 + Math.sqrt(5)) / 2;
  25125. // 12 vertex x,y,z
  25126. var ico_vertices = [
  25127. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25128. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25129. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25130. ];
  25131. // index of 3 vertex makes a face of icopshere
  25132. var ico_indices = [
  25133. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25134. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25135. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25136. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25137. ];
  25138. // vertex for uv have aliased position, not for UV
  25139. var vertices_unalias_id = [
  25140. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25141. // vertex alias
  25142. 0,
  25143. 2,
  25144. 3,
  25145. 3,
  25146. 3,
  25147. 4,
  25148. 7,
  25149. 8,
  25150. 9,
  25151. 9,
  25152. 10,
  25153. 11 // 23: B + 12
  25154. ];
  25155. // uv as integer step (not pixels !)
  25156. var ico_vertexuv = [
  25157. 5, 1, 3, 1, 6, 4, 0, 0,
  25158. 5, 3, 4, 2, 2, 2, 4, 0,
  25159. 2, 0, 1, 1, 6, 0, 6, 2,
  25160. // vertex alias (for same vertex on different faces)
  25161. 0, 4,
  25162. 3, 3,
  25163. 4, 4,
  25164. 3, 1,
  25165. 4, 2,
  25166. 4, 4,
  25167. 0, 2,
  25168. 1, 1,
  25169. 2, 2,
  25170. 3, 3,
  25171. 1, 3,
  25172. 2, 4 // 23: B + 12
  25173. ];
  25174. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25175. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25176. // First island of uv mapping
  25177. // v = 4h 3+ 2
  25178. // v = 3h 9+ 4
  25179. // v = 2h 9+ 5 B
  25180. // v = 1h 9 1 0
  25181. // v = 0h 3 8 7 A
  25182. // u = 0 1 2 3 4 5 6 *a
  25183. // Second island of uv mapping
  25184. // v = 4h 0+ B+ 4+
  25185. // v = 3h A+ 2+
  25186. // v = 2h 7+ 6 3+
  25187. // v = 1h 8+ 3+
  25188. // v = 0h
  25189. // u = 0 1 2 3 4 5 6 *a
  25190. // Face layout on texture UV mapping
  25191. // ============
  25192. // \ 4 /\ 16 / ======
  25193. // \ / \ / /\ 11 /
  25194. // \/ 7 \/ / \ /
  25195. // ======= / 10 \/
  25196. // /\ 17 /\ =======
  25197. // / \ / \ \ 15 /\
  25198. // / 8 \/ 12 \ \ / \
  25199. // ============ \/ 6 \
  25200. // \ 18 /\ ============
  25201. // \ / \ \ 5 /\ 0 /
  25202. // \/ 13 \ \ / \ /
  25203. // ======= \/ 1 \/
  25204. // =============
  25205. // /\ 19 /\ 2 /\
  25206. // / \ / \ / \
  25207. // / 14 \/ 9 \/ 3 \
  25208. // ===================
  25209. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25210. var ustep = 138 / 1024;
  25211. var vstep = 239 / 1024;
  25212. var uoffset = 60 / 1024;
  25213. var voffset = 26 / 1024;
  25214. // Second island should have margin, not to touch the first island
  25215. // avoid any borderline artefact in pixel rounding
  25216. var island_u_offset = -40 / 1024;
  25217. var island_v_offset = +20 / 1024;
  25218. // face is either island 0 or 1 :
  25219. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25220. var island = [
  25221. 0, 0, 0, 0, 1,
  25222. 0, 0, 1, 1, 0,
  25223. 0, 0, 1, 1, 0,
  25224. 0, 1, 1, 1, 0 // 15 - 19
  25225. ];
  25226. var indices = [];
  25227. var positions = [];
  25228. var normals = [];
  25229. var uvs = [];
  25230. var current_indice = 0;
  25231. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25232. var face_vertex_pos = new Array(3);
  25233. var face_vertex_uv = new Array(3);
  25234. var v012;
  25235. for (v012 = 0; v012 < 3; v012++) {
  25236. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25237. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25238. }
  25239. // create all with normals
  25240. for (var face = 0; face < 20; face++) {
  25241. // 3 vertex per face
  25242. for (v012 = 0; v012 < 3; v012++) {
  25243. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25244. var v_id = ico_indices[3 * face + v012];
  25245. // vertex have 3D position (x,y,z)
  25246. 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]);
  25247. // Normalize to get normal, then scale to radius
  25248. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25249. // uv Coordinates from vertex ID
  25250. 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);
  25251. }
  25252. // Subdivide the face (interpolate pos, norm, uv)
  25253. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25254. // - norm is linear interpolation of vertex corner normal
  25255. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25256. // - uv is linear interpolation
  25257. //
  25258. // Topology is as below for sub-divide by 2
  25259. // vertex shown as v0,v1,v2
  25260. // interp index is i1 to progress in range [v0,v1[
  25261. // interp index is i2 to progress in range [v0,v2[
  25262. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25263. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25264. //
  25265. //
  25266. // i2 v2
  25267. // ^ ^
  25268. // / / \
  25269. // / / \
  25270. // / / \
  25271. // / / (0,1) \
  25272. // / #---------\
  25273. // / / \ (0,0)'/ \
  25274. // / / \ / \
  25275. // / / \ / \
  25276. // / / (0,0) \ / (1,0) \
  25277. // / #---------#---------\
  25278. // v0 v1
  25279. //
  25280. // --------------------> i1
  25281. //
  25282. // interp of (i1,i2):
  25283. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25284. // along i1 : lerp(x0,x1, i1/(S-i2))
  25285. //
  25286. // centroid of triangle is needed to get help normal computation
  25287. // (c1,c2) are used for centroid location
  25288. var interp_vertex = function (i1, i2, c1, c2) {
  25289. // vertex is interpolated from
  25290. // - face_vertex_pos[0..2]
  25291. // - face_vertex_uv[0..2]
  25292. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25293. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25294. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25295. pos_interp.normalize();
  25296. var vertex_normal;
  25297. if (flat) {
  25298. // in flat mode, recalculate normal as face centroid normal
  25299. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25300. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25301. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25302. }
  25303. else {
  25304. // in smooth mode, recalculate normal from each single vertex position
  25305. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25306. }
  25307. // Vertex normal need correction due to X,Y,Z radius scaling
  25308. vertex_normal.x /= radiusX;
  25309. vertex_normal.y /= radiusY;
  25310. vertex_normal.z /= radiusZ;
  25311. vertex_normal.normalize();
  25312. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25313. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25314. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25315. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25316. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25317. uvs.push(uv_interp.x, uv_interp.y);
  25318. // push each vertex has member of a face
  25319. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25320. indices.push(current_indice);
  25321. current_indice++;
  25322. };
  25323. for (var i2 = 0; i2 < subdivisions; i2++) {
  25324. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25325. // face : (i1,i2) for /\ :
  25326. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25327. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25328. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25329. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25330. if (i1 + i2 + 1 < subdivisions) {
  25331. // face : (i1,i2)' for \/ :
  25332. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25333. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25334. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25335. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25336. }
  25337. }
  25338. }
  25339. }
  25340. // Sides
  25341. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25342. // Result
  25343. var vertexData = new VertexData();
  25344. vertexData.indices = indices;
  25345. vertexData.positions = positions;
  25346. vertexData.normals = normals;
  25347. vertexData.uvs = uvs;
  25348. return vertexData;
  25349. };
  25350. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25351. VertexData.CreatePolyhedron = function (options) {
  25352. // provided polyhedron types :
  25353. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25354. // 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)
  25355. var polyhedra = [];
  25356. 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]] };
  25357. 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]] };
  25358. polyhedra[2] = {
  25359. 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]],
  25360. 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]]
  25361. };
  25362. polyhedra[3] = {
  25363. 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]],
  25364. 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]]
  25365. };
  25366. polyhedra[4] = {
  25367. 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]],
  25368. 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]]
  25369. };
  25370. 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]] };
  25371. 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]] };
  25372. 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]] };
  25373. 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]] };
  25374. 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]] };
  25375. 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]] };
  25376. 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]] };
  25377. 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]] };
  25378. 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]] };
  25379. polyhedra[14] = {
  25380. 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]],
  25381. 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]]
  25382. };
  25383. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25384. var size = options.size;
  25385. var sizeX = options.sizeX || size || 1;
  25386. var sizeY = options.sizeY || size || 1;
  25387. var sizeZ = options.sizeZ || size || 1;
  25388. var data = options.custom || polyhedra[type];
  25389. var nbfaces = data.face.length;
  25390. var faceUV = options.faceUV || new Array(nbfaces);
  25391. var faceColors = options.faceColors;
  25392. var flat = (options.flat === undefined) ? true : options.flat;
  25393. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25394. var positions = [];
  25395. var indices = [];
  25396. var normals = [];
  25397. var uvs = [];
  25398. var colors = [];
  25399. var index = 0;
  25400. var faceIdx = 0; // face cursor in the array "indexes"
  25401. var indexes = [];
  25402. var i = 0;
  25403. var f = 0;
  25404. var u, v, ang, x, y, tmp;
  25405. // default face colors and UV if undefined
  25406. if (flat) {
  25407. for (f = 0; f < nbfaces; f++) {
  25408. if (faceColors && faceColors[f] === undefined) {
  25409. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25410. }
  25411. if (faceUV && faceUV[f] === undefined) {
  25412. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25413. }
  25414. }
  25415. }
  25416. if (!flat) {
  25417. for (i = 0; i < data.vertex.length; i++) {
  25418. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25419. uvs.push(0, 0);
  25420. }
  25421. for (f = 0; f < nbfaces; f++) {
  25422. for (i = 0; i < data.face[f].length - 2; i++) {
  25423. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25424. }
  25425. }
  25426. }
  25427. else {
  25428. for (f = 0; f < nbfaces; f++) {
  25429. var fl = data.face[f].length; // number of vertices of the current face
  25430. ang = 2 * Math.PI / fl;
  25431. x = 0.5 * Math.tan(ang / 2);
  25432. y = 0.5;
  25433. // positions, uvs, colors
  25434. for (i = 0; i < fl; i++) {
  25435. // positions
  25436. 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);
  25437. indexes.push(index);
  25438. index++;
  25439. // uvs
  25440. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25441. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25442. uvs.push(u, v);
  25443. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25444. y = x * Math.sin(ang) + y * Math.cos(ang);
  25445. x = tmp;
  25446. // colors
  25447. if (faceColors) {
  25448. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25449. }
  25450. }
  25451. // indices from indexes
  25452. for (i = 0; i < fl - 2; i++) {
  25453. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25454. }
  25455. faceIdx += fl;
  25456. }
  25457. }
  25458. VertexData.ComputeNormals(positions, indices, normals);
  25459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25460. var vertexData = new VertexData();
  25461. vertexData.positions = positions;
  25462. vertexData.indices = indices;
  25463. vertexData.normals = normals;
  25464. vertexData.uvs = uvs;
  25465. if (faceColors && flat) {
  25466. vertexData.colors = colors;
  25467. }
  25468. return vertexData;
  25469. };
  25470. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25471. VertexData.CreateTorusKnot = function (options) {
  25472. var indices = [];
  25473. var positions = [];
  25474. var normals = [];
  25475. var uvs = [];
  25476. var radius = options.radius || 2;
  25477. var tube = options.tube || 0.5;
  25478. var radialSegments = options.radialSegments || 32;
  25479. var tubularSegments = options.tubularSegments || 32;
  25480. var p = options.p || 2;
  25481. var q = options.q || 3;
  25482. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25483. // Helper
  25484. var getPos = function (angle) {
  25485. var cu = Math.cos(angle);
  25486. var su = Math.sin(angle);
  25487. var quOverP = q / p * angle;
  25488. var cs = Math.cos(quOverP);
  25489. var tx = radius * (2 + cs) * 0.5 * cu;
  25490. var ty = radius * (2 + cs) * su * 0.5;
  25491. var tz = radius * Math.sin(quOverP) * 0.5;
  25492. return new BABYLON.Vector3(tx, ty, tz);
  25493. };
  25494. // Vertices
  25495. var i;
  25496. var j;
  25497. for (i = 0; i <= radialSegments; i++) {
  25498. var modI = i % radialSegments;
  25499. var u = modI / radialSegments * 2 * p * Math.PI;
  25500. var p1 = getPos(u);
  25501. var p2 = getPos(u + 0.01);
  25502. var tang = p2.subtract(p1);
  25503. var n = p2.add(p1);
  25504. var bitan = BABYLON.Vector3.Cross(tang, n);
  25505. n = BABYLON.Vector3.Cross(bitan, tang);
  25506. bitan.normalize();
  25507. n.normalize();
  25508. for (j = 0; j < tubularSegments; j++) {
  25509. var modJ = j % tubularSegments;
  25510. var v = modJ / tubularSegments * 2 * Math.PI;
  25511. var cx = -tube * Math.cos(v);
  25512. var cy = tube * Math.sin(v);
  25513. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25514. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25515. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25516. uvs.push(i / radialSegments);
  25517. uvs.push(j / tubularSegments);
  25518. }
  25519. }
  25520. for (i = 0; i < radialSegments; i++) {
  25521. for (j = 0; j < tubularSegments; j++) {
  25522. var jNext = (j + 1) % tubularSegments;
  25523. var a = i * tubularSegments + j;
  25524. var b = (i + 1) * tubularSegments + j;
  25525. var c = (i + 1) * tubularSegments + jNext;
  25526. var d = i * tubularSegments + jNext;
  25527. indices.push(d);
  25528. indices.push(b);
  25529. indices.push(a);
  25530. indices.push(d);
  25531. indices.push(c);
  25532. indices.push(b);
  25533. }
  25534. }
  25535. // Normals
  25536. VertexData.ComputeNormals(positions, indices, normals);
  25537. // Sides
  25538. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25539. // Result
  25540. var vertexData = new VertexData();
  25541. vertexData.indices = indices;
  25542. vertexData.positions = positions;
  25543. vertexData.normals = normals;
  25544. vertexData.uvs = uvs;
  25545. return vertexData;
  25546. };
  25547. // Tools
  25548. /**
  25549. * @param {any} - positions (number[] or Float32Array)
  25550. * @param {any} - indices (number[] or Uint16Array)
  25551. * @param {any} - normals (number[] or Float32Array)
  25552. */
  25553. VertexData.ComputeNormals = function (positions, indices, normals) {
  25554. var index = 0;
  25555. var p1p2x = 0.0;
  25556. var p1p2y = 0.0;
  25557. var p1p2z = 0.0;
  25558. var p3p2x = 0.0;
  25559. var p3p2y = 0.0;
  25560. var p3p2z = 0.0;
  25561. var faceNormalx = 0.0;
  25562. var faceNormaly = 0.0;
  25563. var faceNormalz = 0.0;
  25564. var length = 0.0;
  25565. var i1 = 0;
  25566. var i2 = 0;
  25567. var i3 = 0;
  25568. for (index = 0; index < positions.length; index++) {
  25569. normals[index] = 0.0;
  25570. }
  25571. // indice triplet = 1 face
  25572. var nbFaces = indices.length / 3;
  25573. for (index = 0; index < nbFaces; index++) {
  25574. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25575. i2 = indices[index * 3 + 1];
  25576. i3 = indices[index * 3 + 2];
  25577. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25578. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25579. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25580. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25581. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25582. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25583. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25584. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25585. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25586. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25587. length = (length === 0) ? 1.0 : length;
  25588. faceNormalx /= length; // normalize this normal
  25589. faceNormaly /= length;
  25590. faceNormalz /= length;
  25591. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25592. normals[i1 * 3 + 1] += faceNormaly;
  25593. normals[i1 * 3 + 2] += faceNormalz;
  25594. normals[i2 * 3] += faceNormalx;
  25595. normals[i2 * 3 + 1] += faceNormaly;
  25596. normals[i2 * 3 + 2] += faceNormalz;
  25597. normals[i3 * 3] += faceNormalx;
  25598. normals[i3 * 3 + 1] += faceNormaly;
  25599. normals[i3 * 3 + 2] += faceNormalz;
  25600. }
  25601. // last normalization of each normal
  25602. for (index = 0; index < normals.length / 3; index++) {
  25603. faceNormalx = normals[index * 3];
  25604. faceNormaly = normals[index * 3 + 1];
  25605. faceNormalz = normals[index * 3 + 2];
  25606. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25607. length = (length === 0) ? 1.0 : length;
  25608. faceNormalx /= length;
  25609. faceNormaly /= length;
  25610. faceNormalz /= length;
  25611. normals[index * 3] = faceNormalx;
  25612. normals[index * 3 + 1] = faceNormaly;
  25613. normals[index * 3 + 2] = faceNormalz;
  25614. }
  25615. };
  25616. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25617. var li = indices.length;
  25618. var ln = normals.length;
  25619. var i;
  25620. var n;
  25621. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25622. switch (sideOrientation) {
  25623. case BABYLON.Mesh.FRONTSIDE:
  25624. // nothing changed
  25625. break;
  25626. case BABYLON.Mesh.BACKSIDE:
  25627. var tmp;
  25628. // indices
  25629. for (i = 0; i < li; i += 3) {
  25630. tmp = indices[i];
  25631. indices[i] = indices[i + 2];
  25632. indices[i + 2] = tmp;
  25633. }
  25634. // normals
  25635. for (n = 0; n < ln; n++) {
  25636. normals[n] = -normals[n];
  25637. }
  25638. break;
  25639. case BABYLON.Mesh.DOUBLESIDE:
  25640. // positions
  25641. var lp = positions.length;
  25642. var l = lp / 3;
  25643. for (var p = 0; p < lp; p++) {
  25644. positions[lp + p] = positions[p];
  25645. }
  25646. // indices
  25647. for (i = 0; i < li; i += 3) {
  25648. indices[i + li] = indices[i + 2] + l;
  25649. indices[i + 1 + li] = indices[i + 1] + l;
  25650. indices[i + 2 + li] = indices[i] + l;
  25651. }
  25652. // normals
  25653. for (n = 0; n < ln; n++) {
  25654. normals[ln + n] = -normals[n];
  25655. }
  25656. // uvs
  25657. var lu = uvs.length;
  25658. for (var u = 0; u < lu; u++) {
  25659. uvs[u + lu] = uvs[u];
  25660. }
  25661. break;
  25662. }
  25663. };
  25664. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25665. var vertexData = new VertexData();
  25666. // positions
  25667. var positions = parsedVertexData.positions;
  25668. if (positions) {
  25669. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25670. }
  25671. // normals
  25672. var normals = parsedVertexData.normals;
  25673. if (normals) {
  25674. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25675. }
  25676. // uvs
  25677. var uvs = parsedVertexData.uvs;
  25678. if (uvs) {
  25679. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25680. }
  25681. // uv2s
  25682. var uv2s = parsedVertexData.uv2s;
  25683. if (uv2s) {
  25684. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25685. }
  25686. // uv3s
  25687. var uv3s = parsedVertexData.uv3s;
  25688. if (uv3s) {
  25689. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25690. }
  25691. // uv4s
  25692. var uv4s = parsedVertexData.uv4s;
  25693. if (uv4s) {
  25694. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25695. }
  25696. // uv5s
  25697. var uv5s = parsedVertexData.uv5s;
  25698. if (uv5s) {
  25699. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25700. }
  25701. // uv6s
  25702. var uv6s = parsedVertexData.uv6s;
  25703. if (uv6s) {
  25704. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25705. }
  25706. // colors
  25707. var colors = parsedVertexData.colors;
  25708. if (colors) {
  25709. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25710. }
  25711. // matricesIndices
  25712. var matricesIndices = parsedVertexData.matricesIndices;
  25713. if (matricesIndices) {
  25714. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25715. }
  25716. // matricesWeights
  25717. var matricesWeights = parsedVertexData.matricesWeights;
  25718. if (matricesWeights) {
  25719. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25720. }
  25721. // indices
  25722. var indices = parsedVertexData.indices;
  25723. if (indices) {
  25724. vertexData.indices = indices;
  25725. }
  25726. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25727. };
  25728. return VertexData;
  25729. })();
  25730. BABYLON.VertexData = VertexData;
  25731. })(BABYLON || (BABYLON = {}));
  25732. var BABYLON;
  25733. (function (BABYLON) {
  25734. var Tags = (function () {
  25735. function Tags() {
  25736. }
  25737. Tags.EnableFor = function (obj) {
  25738. obj._tags = obj._tags || {};
  25739. obj.hasTags = function () {
  25740. return Tags.HasTags(obj);
  25741. };
  25742. obj.addTags = function (tagsString) {
  25743. return Tags.AddTagsTo(obj, tagsString);
  25744. };
  25745. obj.removeTags = function (tagsString) {
  25746. return Tags.RemoveTagsFrom(obj, tagsString);
  25747. };
  25748. obj.matchesTagsQuery = function (tagsQuery) {
  25749. return Tags.MatchesQuery(obj, tagsQuery);
  25750. };
  25751. };
  25752. Tags.DisableFor = function (obj) {
  25753. delete obj._tags;
  25754. delete obj.hasTags;
  25755. delete obj.addTags;
  25756. delete obj.removeTags;
  25757. delete obj.matchesTagsQuery;
  25758. };
  25759. Tags.HasTags = function (obj) {
  25760. if (!obj._tags) {
  25761. return false;
  25762. }
  25763. return !BABYLON.Tools.IsEmpty(obj._tags);
  25764. };
  25765. Tags.GetTags = function (obj, asString) {
  25766. if (asString === void 0) { asString = true; }
  25767. if (!obj._tags) {
  25768. return null;
  25769. }
  25770. if (asString) {
  25771. var tagsArray = [];
  25772. for (var tag in obj._tags) {
  25773. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  25774. tagsArray.push(tag);
  25775. }
  25776. }
  25777. return tagsArray.join(" ");
  25778. }
  25779. else {
  25780. return obj._tags;
  25781. }
  25782. };
  25783. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25784. // a tag cannot start with '||', '&&', and '!'
  25785. // it cannot contain whitespaces
  25786. Tags.AddTagsTo = function (obj, tagsString) {
  25787. if (!tagsString) {
  25788. return;
  25789. }
  25790. if (typeof tagsString !== "string") {
  25791. return;
  25792. }
  25793. var tags = tagsString.split(" ");
  25794. for (var t in tags) {
  25795. Tags._AddTagTo(obj, tags[t]);
  25796. }
  25797. };
  25798. Tags._AddTagTo = function (obj, tag) {
  25799. tag = tag.trim();
  25800. if (tag === "" || tag === "true" || tag === "false") {
  25801. return;
  25802. }
  25803. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25804. return;
  25805. }
  25806. Tags.EnableFor(obj);
  25807. obj._tags[tag] = true;
  25808. };
  25809. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25810. if (!Tags.HasTags(obj)) {
  25811. return;
  25812. }
  25813. var tags = tagsString.split(" ");
  25814. for (var t in tags) {
  25815. Tags._RemoveTagFrom(obj, tags[t]);
  25816. }
  25817. };
  25818. Tags._RemoveTagFrom = function (obj, tag) {
  25819. delete obj._tags[tag];
  25820. };
  25821. Tags.MatchesQuery = function (obj, tagsQuery) {
  25822. if (tagsQuery === undefined) {
  25823. return true;
  25824. }
  25825. if (tagsQuery === "") {
  25826. return Tags.HasTags(obj);
  25827. }
  25828. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25829. };
  25830. return Tags;
  25831. })();
  25832. BABYLON.Tags = Tags;
  25833. })(BABYLON || (BABYLON = {}));
  25834. var BABYLON;
  25835. (function (BABYLON) {
  25836. var Internals;
  25837. (function (Internals) {
  25838. var AndOrNotEvaluator = (function () {
  25839. function AndOrNotEvaluator() {
  25840. }
  25841. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25842. if (!query.match(/\([^\(\)]*\)/g)) {
  25843. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25844. }
  25845. else {
  25846. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25847. // remove parenthesis
  25848. r = r.slice(1, r.length - 1);
  25849. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25850. });
  25851. }
  25852. if (query === "true") {
  25853. return true;
  25854. }
  25855. if (query === "false") {
  25856. return false;
  25857. }
  25858. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25859. };
  25860. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25861. evaluateCallback = evaluateCallback || (function (r) {
  25862. return r === "true" ? true : false;
  25863. });
  25864. var result;
  25865. var or = parenthesisContent.split("||");
  25866. for (var i in or) {
  25867. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25868. var and = ori.split("&&");
  25869. if (and.length > 1) {
  25870. for (var j = 0; j < and.length; ++j) {
  25871. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25872. if (andj !== "true" && andj !== "false") {
  25873. if (andj[0] === "!") {
  25874. result = !evaluateCallback(andj.substring(1));
  25875. }
  25876. else {
  25877. result = evaluateCallback(andj);
  25878. }
  25879. }
  25880. else {
  25881. result = andj === "true" ? true : false;
  25882. }
  25883. if (!result) {
  25884. ori = "false";
  25885. break;
  25886. }
  25887. }
  25888. }
  25889. if (result || ori === "true") {
  25890. result = true;
  25891. break;
  25892. }
  25893. // result equals false (or undefined)
  25894. if (ori !== "true" && ori !== "false") {
  25895. if (ori[0] === "!") {
  25896. result = !evaluateCallback(ori.substring(1));
  25897. }
  25898. else {
  25899. result = evaluateCallback(ori);
  25900. }
  25901. }
  25902. else {
  25903. result = ori === "true" ? true : false;
  25904. }
  25905. }
  25906. // the whole parenthesis scope is replaced by 'true' or 'false'
  25907. return result ? "true" : "false";
  25908. };
  25909. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25910. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25911. // remove whitespaces
  25912. r = r.replace(/[\s]/g, function () { return ""; });
  25913. return r.length % 2 ? "!" : "";
  25914. });
  25915. booleanString = booleanString.trim();
  25916. if (booleanString === "!true") {
  25917. booleanString = "false";
  25918. }
  25919. else if (booleanString === "!false") {
  25920. booleanString = "true";
  25921. }
  25922. return booleanString;
  25923. };
  25924. return AndOrNotEvaluator;
  25925. })();
  25926. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25927. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25928. })(BABYLON || (BABYLON = {}));
  25929. var BABYLON;
  25930. (function (BABYLON) {
  25931. var PostProcessRenderPass = (function () {
  25932. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25933. this._enabled = true;
  25934. this._refCount = 0;
  25935. this._name = name;
  25936. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25937. this.setRenderList(renderList);
  25938. this._renderTexture.onBeforeRender = beforeRender;
  25939. this._renderTexture.onAfterRender = afterRender;
  25940. this._scene = scene;
  25941. this._renderList = renderList;
  25942. }
  25943. // private
  25944. PostProcessRenderPass.prototype._incRefCount = function () {
  25945. if (this._refCount === 0) {
  25946. this._scene.customRenderTargets.push(this._renderTexture);
  25947. }
  25948. return ++this._refCount;
  25949. };
  25950. PostProcessRenderPass.prototype._decRefCount = function () {
  25951. this._refCount--;
  25952. if (this._refCount <= 0) {
  25953. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25954. }
  25955. return this._refCount;
  25956. };
  25957. PostProcessRenderPass.prototype._update = function () {
  25958. this.setRenderList(this._renderList);
  25959. };
  25960. // public
  25961. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25962. this._renderTexture.renderList = renderList;
  25963. };
  25964. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25965. return this._renderTexture;
  25966. };
  25967. return PostProcessRenderPass;
  25968. })();
  25969. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25970. })(BABYLON || (BABYLON = {}));
  25971. var BABYLON;
  25972. (function (BABYLON) {
  25973. var PostProcessRenderEffect = (function () {
  25974. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25975. this._engine = engine;
  25976. this._name = name;
  25977. this._singleInstance = singleInstance || true;
  25978. this._getPostProcess = getPostProcess;
  25979. this._cameras = [];
  25980. this._indicesForCamera = [];
  25981. this._postProcesses = {};
  25982. this._renderPasses = {};
  25983. this._renderEffectAsPasses = {};
  25984. }
  25985. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25986. get: function () {
  25987. for (var index in this._postProcesses) {
  25988. if (!this._postProcesses[index].isSupported) {
  25989. return false;
  25990. }
  25991. }
  25992. return true;
  25993. },
  25994. enumerable: true,
  25995. configurable: true
  25996. });
  25997. PostProcessRenderEffect.prototype._update = function () {
  25998. for (var renderPassName in this._renderPasses) {
  25999. this._renderPasses[renderPassName]._update();
  26000. }
  26001. };
  26002. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26003. this._renderPasses[renderPass._name] = renderPass;
  26004. this._linkParameters();
  26005. };
  26006. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26007. delete this._renderPasses[renderPass._name];
  26008. this._linkParameters();
  26009. };
  26010. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26011. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26012. this._linkParameters();
  26013. };
  26014. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26015. for (var renderPassName in this._renderPasses) {
  26016. if (renderPassName === passName) {
  26017. return this._renderPasses[passName];
  26018. }
  26019. }
  26020. };
  26021. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26022. this._renderPasses = {};
  26023. this._linkParameters();
  26024. };
  26025. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26026. var cameraKey;
  26027. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26028. for (var i = 0; i < _cam.length; i++) {
  26029. var camera = _cam[i];
  26030. var cameraName = camera.name;
  26031. if (this._singleInstance) {
  26032. cameraKey = 0;
  26033. }
  26034. else {
  26035. cameraKey = cameraName;
  26036. }
  26037. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26038. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26039. if (!this._indicesForCamera[cameraName]) {
  26040. this._indicesForCamera[cameraName] = [];
  26041. }
  26042. this._indicesForCamera[cameraName].push(index);
  26043. if (this._cameras.indexOf(camera) === -1) {
  26044. this._cameras[cameraName] = camera;
  26045. }
  26046. for (var passName in this._renderPasses) {
  26047. this._renderPasses[passName]._incRefCount();
  26048. }
  26049. }
  26050. this._linkParameters();
  26051. };
  26052. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26053. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26054. for (var i = 0; i < _cam.length; i++) {
  26055. var camera = _cam[i];
  26056. var cameraName = camera.name;
  26057. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26058. var index = this._cameras.indexOf(cameraName);
  26059. this._indicesForCamera.splice(index, 1);
  26060. this._cameras.splice(index, 1);
  26061. for (var passName in this._renderPasses) {
  26062. this._renderPasses[passName]._decRefCount();
  26063. }
  26064. }
  26065. };
  26066. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26067. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26068. for (var i = 0; i < _cam.length; i++) {
  26069. var camera = _cam[i];
  26070. var cameraName = camera.name;
  26071. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26072. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26073. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26074. }
  26075. }
  26076. for (var passName in this._renderPasses) {
  26077. this._renderPasses[passName]._incRefCount();
  26078. }
  26079. }
  26080. };
  26081. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26082. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26083. for (var i = 0; i < _cam.length; i++) {
  26084. var camera = _cam[i];
  26085. var cameraName = camera.Name;
  26086. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26087. for (var passName in this._renderPasses) {
  26088. this._renderPasses[passName]._decRefCount();
  26089. }
  26090. }
  26091. };
  26092. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26093. if (this._singleInstance) {
  26094. return this._postProcesses[0];
  26095. }
  26096. else {
  26097. return this._postProcesses[camera.name];
  26098. }
  26099. };
  26100. PostProcessRenderEffect.prototype._linkParameters = function () {
  26101. var _this = this;
  26102. for (var index in this._postProcesses) {
  26103. if (this.applyParameters) {
  26104. this.applyParameters(this._postProcesses[index]);
  26105. }
  26106. this._postProcesses[index].onBeforeRender = function (effect) {
  26107. _this._linkTextures(effect);
  26108. };
  26109. }
  26110. };
  26111. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26112. for (var renderPassName in this._renderPasses) {
  26113. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26114. }
  26115. for (var renderEffectName in this._renderEffectAsPasses) {
  26116. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26117. }
  26118. };
  26119. return PostProcessRenderEffect;
  26120. })();
  26121. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26122. })(BABYLON || (BABYLON = {}));
  26123. var BABYLON;
  26124. (function (BABYLON) {
  26125. var PostProcessRenderPipeline = (function () {
  26126. function PostProcessRenderPipeline(engine, name) {
  26127. this._engine = engine;
  26128. this._name = name;
  26129. this._renderEffects = {};
  26130. this._renderEffectsForIsolatedPass = {};
  26131. this._cameras = [];
  26132. }
  26133. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26134. get: function () {
  26135. for (var renderEffectName in this._renderEffects) {
  26136. if (!this._renderEffects[renderEffectName].isSupported) {
  26137. return false;
  26138. }
  26139. }
  26140. return true;
  26141. },
  26142. enumerable: true,
  26143. configurable: true
  26144. });
  26145. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26146. this._renderEffects[renderEffect._name] = renderEffect;
  26147. };
  26148. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26149. var renderEffects = this._renderEffects[renderEffectName];
  26150. if (!renderEffects) {
  26151. return;
  26152. }
  26153. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26154. };
  26155. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26156. var renderEffects = this._renderEffects[renderEffectName];
  26157. if (!renderEffects) {
  26158. return;
  26159. }
  26160. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26161. };
  26162. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26163. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26164. var indicesToDelete = [];
  26165. var i;
  26166. for (i = 0; i < _cam.length; i++) {
  26167. var camera = _cam[i];
  26168. var cameraName = camera.name;
  26169. if (this._cameras.indexOf(camera) === -1) {
  26170. this._cameras[cameraName] = camera;
  26171. }
  26172. else if (unique) {
  26173. indicesToDelete.push(i);
  26174. }
  26175. }
  26176. for (i = 0; i < indicesToDelete.length; i++) {
  26177. cameras.splice(indicesToDelete[i], 1);
  26178. }
  26179. for (var renderEffectName in this._renderEffects) {
  26180. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26181. }
  26182. };
  26183. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26184. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26185. for (var renderEffectName in this._renderEffects) {
  26186. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26187. }
  26188. for (var i = 0; i < _cam.length; i++) {
  26189. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26190. }
  26191. };
  26192. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26193. var _this = this;
  26194. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26195. var pass = null;
  26196. var renderEffectName;
  26197. for (renderEffectName in this._renderEffects) {
  26198. pass = this._renderEffects[renderEffectName].getPass(passName);
  26199. if (pass != null) {
  26200. break;
  26201. }
  26202. }
  26203. if (pass === null) {
  26204. return;
  26205. }
  26206. for (renderEffectName in this._renderEffects) {
  26207. this._renderEffects[renderEffectName]._disable(_cam);
  26208. }
  26209. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26210. for (var i = 0; i < _cam.length; i++) {
  26211. var camera = _cam[i];
  26212. var cameraName = camera.name;
  26213. 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); });
  26214. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26215. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26216. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26217. }
  26218. };
  26219. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26220. var _this = this;
  26221. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26222. for (var i = 0; i < _cam.length; i++) {
  26223. var camera = _cam[i];
  26224. var cameraName = camera.name;
  26225. 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); });
  26226. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26227. }
  26228. for (var renderEffectName in this._renderEffects) {
  26229. this._renderEffects[renderEffectName]._enable(_cam);
  26230. }
  26231. };
  26232. PostProcessRenderPipeline.prototype._update = function () {
  26233. for (var renderEffectName in this._renderEffects) {
  26234. this._renderEffects[renderEffectName]._update();
  26235. }
  26236. for (var i = 0; i < this._cameras.length; i++) {
  26237. var cameraName = this._cameras[i].name;
  26238. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26239. this._renderEffectsForIsolatedPass[cameraName]._update();
  26240. }
  26241. }
  26242. };
  26243. PostProcessRenderPipeline.prototype.dispose = function () {
  26244. // Must be implemented by children
  26245. };
  26246. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26247. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26248. return PostProcessRenderPipeline;
  26249. })();
  26250. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26251. })(BABYLON || (BABYLON = {}));
  26252. var BABYLON;
  26253. (function (BABYLON) {
  26254. var PostProcessRenderPipelineManager = (function () {
  26255. function PostProcessRenderPipelineManager() {
  26256. this._renderPipelines = {};
  26257. }
  26258. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26259. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26260. };
  26261. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26262. var renderPipeline = this._renderPipelines[renderPipelineName];
  26263. if (!renderPipeline) {
  26264. return;
  26265. }
  26266. renderPipeline._attachCameras(cameras, unique);
  26267. };
  26268. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26269. var renderPipeline = this._renderPipelines[renderPipelineName];
  26270. if (!renderPipeline) {
  26271. return;
  26272. }
  26273. renderPipeline._detachCameras(cameras);
  26274. };
  26275. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26276. var renderPipeline = this._renderPipelines[renderPipelineName];
  26277. if (!renderPipeline) {
  26278. return;
  26279. }
  26280. renderPipeline._enableEffect(renderEffectName, cameras);
  26281. };
  26282. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26283. var renderPipeline = this._renderPipelines[renderPipelineName];
  26284. if (!renderPipeline) {
  26285. return;
  26286. }
  26287. renderPipeline._disableEffect(renderEffectName, cameras);
  26288. };
  26289. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26290. var renderPipeline = this._renderPipelines[renderPipelineName];
  26291. if (!renderPipeline) {
  26292. return;
  26293. }
  26294. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26295. };
  26296. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26297. var renderPipeline = this._renderPipelines[renderPipelineName];
  26298. if (!renderPipeline) {
  26299. return;
  26300. }
  26301. renderPipeline._disableDisplayOnlyPass(cameras);
  26302. };
  26303. PostProcessRenderPipelineManager.prototype.update = function () {
  26304. for (var renderPipelineName in this._renderPipelines) {
  26305. var pipeline = this._renderPipelines[renderPipelineName];
  26306. if (!pipeline.isSupported) {
  26307. pipeline.dispose();
  26308. delete this._renderPipelines[renderPipelineName];
  26309. }
  26310. else {
  26311. pipeline._update();
  26312. }
  26313. }
  26314. };
  26315. return PostProcessRenderPipelineManager;
  26316. })();
  26317. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26318. })(BABYLON || (BABYLON = {}));
  26319. var BABYLON;
  26320. (function (BABYLON) {
  26321. var BoundingBoxRenderer = (function () {
  26322. function BoundingBoxRenderer(scene) {
  26323. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26324. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26325. this.showBackLines = true;
  26326. this.renderList = new BABYLON.SmartArray(32);
  26327. this._scene = scene;
  26328. }
  26329. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26330. if (this._colorShader) {
  26331. return;
  26332. }
  26333. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26334. attributes: ["position"],
  26335. uniforms: ["worldViewProjection", "color"]
  26336. });
  26337. var engine = this._scene.getEngine();
  26338. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26339. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26340. 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]);
  26341. };
  26342. BoundingBoxRenderer.prototype.reset = function () {
  26343. this.renderList.reset();
  26344. };
  26345. BoundingBoxRenderer.prototype.render = function () {
  26346. if (this.renderList.length === 0) {
  26347. return;
  26348. }
  26349. this._prepareRessources();
  26350. if (!this._colorShader.isReady()) {
  26351. return;
  26352. }
  26353. var engine = this._scene.getEngine();
  26354. engine.setDepthWrite(false);
  26355. this._colorShader._preBind();
  26356. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26357. var boundingBox = this.renderList.data[boundingBoxIndex];
  26358. var min = boundingBox.minimum;
  26359. var max = boundingBox.maximum;
  26360. var diff = max.subtract(min);
  26361. var median = min.add(diff.scale(0.5));
  26362. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26363. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26364. .multiply(boundingBox.getWorldMatrix());
  26365. // VBOs
  26366. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26367. if (this.showBackLines) {
  26368. // Back
  26369. engine.setDepthFunctionToGreaterOrEqual();
  26370. this._scene.resetCachedMaterial();
  26371. this._colorShader.setColor4("color", this.backColor.toColor4());
  26372. this._colorShader.bind(worldMatrix);
  26373. // Draw order
  26374. engine.draw(false, 0, 24);
  26375. }
  26376. // Front
  26377. engine.setDepthFunctionToLess();
  26378. this._scene.resetCachedMaterial();
  26379. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26380. this._colorShader.bind(worldMatrix);
  26381. // Draw order
  26382. engine.draw(false, 0, 24);
  26383. }
  26384. this._colorShader.unbind();
  26385. engine.setDepthFunctionToLessOrEqual();
  26386. engine.setDepthWrite(true);
  26387. };
  26388. BoundingBoxRenderer.prototype.dispose = function () {
  26389. if (!this._colorShader) {
  26390. return;
  26391. }
  26392. this._colorShader.dispose();
  26393. this._vb.dispose();
  26394. this._scene.getEngine()._releaseBuffer(this._ib);
  26395. };
  26396. return BoundingBoxRenderer;
  26397. })();
  26398. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26399. })(BABYLON || (BABYLON = {}));
  26400. var BABYLON;
  26401. (function (BABYLON) {
  26402. var Condition = (function () {
  26403. function Condition(actionManager) {
  26404. this._actionManager = actionManager;
  26405. }
  26406. Condition.prototype.isValid = function () {
  26407. return true;
  26408. };
  26409. Condition.prototype._getProperty = function (propertyPath) {
  26410. return this._actionManager._getProperty(propertyPath);
  26411. };
  26412. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26413. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26414. };
  26415. return Condition;
  26416. })();
  26417. BABYLON.Condition = Condition;
  26418. var ValueCondition = (function (_super) {
  26419. __extends(ValueCondition, _super);
  26420. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26421. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26422. _super.call(this, actionManager);
  26423. this.propertyPath = propertyPath;
  26424. this.value = value;
  26425. this.operator = operator;
  26426. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26427. this._property = this._getProperty(this.propertyPath);
  26428. }
  26429. Object.defineProperty(ValueCondition, "IsEqual", {
  26430. get: function () {
  26431. return ValueCondition._IsEqual;
  26432. },
  26433. enumerable: true,
  26434. configurable: true
  26435. });
  26436. Object.defineProperty(ValueCondition, "IsDifferent", {
  26437. get: function () {
  26438. return ValueCondition._IsDifferent;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(ValueCondition, "IsGreater", {
  26444. get: function () {
  26445. return ValueCondition._IsGreater;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. Object.defineProperty(ValueCondition, "IsLesser", {
  26451. get: function () {
  26452. return ValueCondition._IsLesser;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. // Methods
  26458. ValueCondition.prototype.isValid = function () {
  26459. switch (this.operator) {
  26460. case ValueCondition.IsGreater:
  26461. return this._target[this._property] > this.value;
  26462. case ValueCondition.IsLesser:
  26463. return this._target[this._property] < this.value;
  26464. case ValueCondition.IsEqual:
  26465. case ValueCondition.IsDifferent:
  26466. var check;
  26467. if (this.value.equals) {
  26468. check = this.value.equals(this._target[this._property]);
  26469. }
  26470. else {
  26471. check = this.value === this._target[this._property];
  26472. }
  26473. return this.operator === ValueCondition.IsEqual ? check : !check;
  26474. }
  26475. return false;
  26476. };
  26477. // Statics
  26478. ValueCondition._IsEqual = 0;
  26479. ValueCondition._IsDifferent = 1;
  26480. ValueCondition._IsGreater = 2;
  26481. ValueCondition._IsLesser = 3;
  26482. return ValueCondition;
  26483. })(Condition);
  26484. BABYLON.ValueCondition = ValueCondition;
  26485. var PredicateCondition = (function (_super) {
  26486. __extends(PredicateCondition, _super);
  26487. function PredicateCondition(actionManager, predicate) {
  26488. _super.call(this, actionManager);
  26489. this.predicate = predicate;
  26490. }
  26491. PredicateCondition.prototype.isValid = function () {
  26492. return this.predicate();
  26493. };
  26494. return PredicateCondition;
  26495. })(Condition);
  26496. BABYLON.PredicateCondition = PredicateCondition;
  26497. var StateCondition = (function (_super) {
  26498. __extends(StateCondition, _super);
  26499. function StateCondition(actionManager, target, value) {
  26500. _super.call(this, actionManager);
  26501. this.value = value;
  26502. this._target = target;
  26503. }
  26504. // Methods
  26505. StateCondition.prototype.isValid = function () {
  26506. return this._target.state === this.value;
  26507. };
  26508. return StateCondition;
  26509. })(Condition);
  26510. BABYLON.StateCondition = StateCondition;
  26511. })(BABYLON || (BABYLON = {}));
  26512. var BABYLON;
  26513. (function (BABYLON) {
  26514. var Action = (function () {
  26515. function Action(triggerOptions, condition) {
  26516. this.triggerOptions = triggerOptions;
  26517. if (triggerOptions.parameter) {
  26518. this.trigger = triggerOptions.trigger;
  26519. this._triggerParameter = triggerOptions.parameter;
  26520. }
  26521. else {
  26522. this.trigger = triggerOptions;
  26523. }
  26524. this._nextActiveAction = this;
  26525. this._condition = condition;
  26526. }
  26527. // Methods
  26528. Action.prototype._prepare = function () {
  26529. };
  26530. Action.prototype.getTriggerParameter = function () {
  26531. return this._triggerParameter;
  26532. };
  26533. Action.prototype._executeCurrent = function (evt) {
  26534. if (this._nextActiveAction._condition) {
  26535. var condition = this._nextActiveAction._condition;
  26536. var currentRenderId = this._actionManager.getScene().getRenderId();
  26537. // We cache the current evaluation for the current frame
  26538. if (condition._evaluationId === currentRenderId) {
  26539. if (!condition._currentResult) {
  26540. return;
  26541. }
  26542. }
  26543. else {
  26544. condition._evaluationId = currentRenderId;
  26545. if (!condition.isValid()) {
  26546. condition._currentResult = false;
  26547. return;
  26548. }
  26549. condition._currentResult = true;
  26550. }
  26551. }
  26552. this._nextActiveAction.execute(evt);
  26553. this.skipToNextActiveAction();
  26554. };
  26555. Action.prototype.execute = function (evt) {
  26556. };
  26557. Action.prototype.skipToNextActiveAction = function () {
  26558. if (this._nextActiveAction._child) {
  26559. if (!this._nextActiveAction._child._actionManager) {
  26560. this._nextActiveAction._child._actionManager = this._actionManager;
  26561. }
  26562. this._nextActiveAction = this._nextActiveAction._child;
  26563. }
  26564. else {
  26565. this._nextActiveAction = this;
  26566. }
  26567. };
  26568. Action.prototype.then = function (action) {
  26569. this._child = action;
  26570. action._actionManager = this._actionManager;
  26571. action._prepare();
  26572. return action;
  26573. };
  26574. Action.prototype._getProperty = function (propertyPath) {
  26575. return this._actionManager._getProperty(propertyPath);
  26576. };
  26577. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26578. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26579. };
  26580. return Action;
  26581. })();
  26582. BABYLON.Action = Action;
  26583. })(BABYLON || (BABYLON = {}));
  26584. var BABYLON;
  26585. (function (BABYLON) {
  26586. /**
  26587. * ActionEvent is the event beint sent when an action is triggered.
  26588. */
  26589. var ActionEvent = (function () {
  26590. /**
  26591. * @constructor
  26592. * @param source The mesh or sprite that triggered the action.
  26593. * @param pointerX The X mouse cursor position at the time of the event
  26594. * @param pointerY The Y mouse cursor position at the time of the event
  26595. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26596. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26597. */
  26598. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  26599. this.source = source;
  26600. this.pointerX = pointerX;
  26601. this.pointerY = pointerY;
  26602. this.meshUnderPointer = meshUnderPointer;
  26603. this.sourceEvent = sourceEvent;
  26604. this.additionalData = additionalData;
  26605. }
  26606. /**
  26607. * Helper function to auto-create an ActionEvent from a source mesh.
  26608. * @param source The source mesh that triggered the event
  26609. * @param evt {Event} The original (browser) event
  26610. */
  26611. ActionEvent.CreateNew = function (source, evt, additionalData) {
  26612. var scene = source.getScene();
  26613. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26614. };
  26615. /**
  26616. * Helper function to auto-create an ActionEvent from a source mesh.
  26617. * @param source The source sprite that triggered the event
  26618. * @param scene Scene associated with the sprite
  26619. * @param evt {Event} The original (browser) event
  26620. */
  26621. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  26622. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26623. };
  26624. /**
  26625. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26626. * @param scene the scene where the event occurred
  26627. * @param evt {Event} The original (browser) event
  26628. */
  26629. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26630. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26631. };
  26632. return ActionEvent;
  26633. })();
  26634. BABYLON.ActionEvent = ActionEvent;
  26635. /**
  26636. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26637. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26638. */
  26639. var ActionManager = (function () {
  26640. function ActionManager(scene) {
  26641. // Members
  26642. this.actions = new Array();
  26643. this._scene = scene;
  26644. scene._actionManagers.push(this);
  26645. }
  26646. Object.defineProperty(ActionManager, "NothingTrigger", {
  26647. get: function () {
  26648. return ActionManager._NothingTrigger;
  26649. },
  26650. enumerable: true,
  26651. configurable: true
  26652. });
  26653. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26654. get: function () {
  26655. return ActionManager._OnPickTrigger;
  26656. },
  26657. enumerable: true,
  26658. configurable: true
  26659. });
  26660. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26661. get: function () {
  26662. return ActionManager._OnLeftPickTrigger;
  26663. },
  26664. enumerable: true,
  26665. configurable: true
  26666. });
  26667. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26668. get: function () {
  26669. return ActionManager._OnRightPickTrigger;
  26670. },
  26671. enumerable: true,
  26672. configurable: true
  26673. });
  26674. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26675. get: function () {
  26676. return ActionManager._OnCenterPickTrigger;
  26677. },
  26678. enumerable: true,
  26679. configurable: true
  26680. });
  26681. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  26682. get: function () {
  26683. return ActionManager._OnPickDownTrigger;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26689. get: function () {
  26690. return ActionManager._OnPickUpTrigger;
  26691. },
  26692. enumerable: true,
  26693. configurable: true
  26694. });
  26695. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  26696. /// This trigger will only be raised if you also declared a OnPickDown
  26697. get: function () {
  26698. return ActionManager._OnPickOutTrigger;
  26699. },
  26700. enumerable: true,
  26701. configurable: true
  26702. });
  26703. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  26704. get: function () {
  26705. return ActionManager._OnLongPressTrigger;
  26706. },
  26707. enumerable: true,
  26708. configurable: true
  26709. });
  26710. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26711. get: function () {
  26712. return ActionManager._OnPointerOverTrigger;
  26713. },
  26714. enumerable: true,
  26715. configurable: true
  26716. });
  26717. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26718. get: function () {
  26719. return ActionManager._OnPointerOutTrigger;
  26720. },
  26721. enumerable: true,
  26722. configurable: true
  26723. });
  26724. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26725. get: function () {
  26726. return ActionManager._OnEveryFrameTrigger;
  26727. },
  26728. enumerable: true,
  26729. configurable: true
  26730. });
  26731. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26732. get: function () {
  26733. return ActionManager._OnIntersectionEnterTrigger;
  26734. },
  26735. enumerable: true,
  26736. configurable: true
  26737. });
  26738. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26739. get: function () {
  26740. return ActionManager._OnIntersectionExitTrigger;
  26741. },
  26742. enumerable: true,
  26743. configurable: true
  26744. });
  26745. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26746. get: function () {
  26747. return ActionManager._OnKeyDownTrigger;
  26748. },
  26749. enumerable: true,
  26750. configurable: true
  26751. });
  26752. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26753. get: function () {
  26754. return ActionManager._OnKeyUpTrigger;
  26755. },
  26756. enumerable: true,
  26757. configurable: true
  26758. });
  26759. // Methods
  26760. ActionManager.prototype.dispose = function () {
  26761. var index = this._scene._actionManagers.indexOf(this);
  26762. if (index > -1) {
  26763. this._scene._actionManagers.splice(index, 1);
  26764. }
  26765. };
  26766. ActionManager.prototype.getScene = function () {
  26767. return this._scene;
  26768. };
  26769. /**
  26770. * Does this action manager handles actions of any of the given triggers
  26771. * @param {number[]} triggers - the triggers to be tested
  26772. * @return {boolean} whether one (or more) of the triggers is handeled
  26773. */
  26774. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26775. for (var index = 0; index < this.actions.length; index++) {
  26776. var action = this.actions[index];
  26777. if (triggers.indexOf(action.trigger) > -1) {
  26778. return true;
  26779. }
  26780. }
  26781. return false;
  26782. };
  26783. /**
  26784. * Does this action manager handles actions of a given trigger
  26785. * @param {number} trigger - the trigger to be tested
  26786. * @return {boolean} whether the trigger is handeled
  26787. */
  26788. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26789. for (var index = 0; index < this.actions.length; index++) {
  26790. var action = this.actions[index];
  26791. if (action.trigger === trigger) {
  26792. return true;
  26793. }
  26794. }
  26795. return false;
  26796. };
  26797. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26798. /**
  26799. * Does this action manager has pointer triggers
  26800. * @return {boolean} whether or not it has pointer triggers
  26801. */
  26802. get: function () {
  26803. for (var index = 0; index < this.actions.length; index++) {
  26804. var action = this.actions[index];
  26805. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26806. return true;
  26807. }
  26808. }
  26809. return false;
  26810. },
  26811. enumerable: true,
  26812. configurable: true
  26813. });
  26814. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26815. /**
  26816. * Does this action manager has pick triggers
  26817. * @return {boolean} whether or not it has pick triggers
  26818. */
  26819. get: function () {
  26820. for (var index = 0; index < this.actions.length; index++) {
  26821. var action = this.actions[index];
  26822. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26823. return true;
  26824. }
  26825. }
  26826. return false;
  26827. },
  26828. enumerable: true,
  26829. configurable: true
  26830. });
  26831. /**
  26832. * Registers an action to this action manager
  26833. * @param {BABYLON.Action} action - the action to be registered
  26834. * @return {BABYLON.Action} the action amended (prepared) after registration
  26835. */
  26836. ActionManager.prototype.registerAction = function (action) {
  26837. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26838. if (this.getScene().actionManager !== this) {
  26839. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26840. return null;
  26841. }
  26842. }
  26843. this.actions.push(action);
  26844. action._actionManager = this;
  26845. action._prepare();
  26846. return action;
  26847. };
  26848. /**
  26849. * Process a specific trigger
  26850. * @param {number} trigger - the trigger to process
  26851. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26852. */
  26853. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26854. for (var index = 0; index < this.actions.length; index++) {
  26855. var action = this.actions[index];
  26856. if (action.trigger === trigger) {
  26857. if (trigger === ActionManager.OnKeyUpTrigger
  26858. || trigger === ActionManager.OnKeyDownTrigger) {
  26859. var parameter = action.getTriggerParameter();
  26860. if (parameter) {
  26861. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26862. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26863. if (actualkey !== parameter.toLowerCase()) {
  26864. continue;
  26865. }
  26866. }
  26867. }
  26868. action._executeCurrent(evt);
  26869. }
  26870. }
  26871. };
  26872. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26873. var properties = propertyPath.split(".");
  26874. for (var index = 0; index < properties.length - 1; index++) {
  26875. target = target[properties[index]];
  26876. }
  26877. return target;
  26878. };
  26879. ActionManager.prototype._getProperty = function (propertyPath) {
  26880. var properties = propertyPath.split(".");
  26881. return properties[properties.length - 1];
  26882. };
  26883. ActionManager.Parse = function (parsedActions, object, scene) {
  26884. var actionManager = new BABYLON.ActionManager(scene);
  26885. if (object === null)
  26886. scene.actionManager = actionManager;
  26887. else
  26888. object.actionManager = actionManager;
  26889. // instanciate a new object
  26890. var instanciate = function (name, params) {
  26891. var newInstance = Object.create(BABYLON[name].prototype);
  26892. newInstance.constructor.apply(newInstance, params);
  26893. return newInstance;
  26894. };
  26895. var parseParameter = function (name, value, target, propertyPath) {
  26896. if (propertyPath === null) {
  26897. // String, boolean or float
  26898. var floatValue = parseFloat(value);
  26899. if (value === "true" || value === "false")
  26900. return value === "true";
  26901. else
  26902. return isNaN(floatValue) ? value : floatValue;
  26903. }
  26904. var effectiveTarget = propertyPath.split(".");
  26905. var values = value.split(",");
  26906. // Get effective Target
  26907. for (var i = 0; i < effectiveTarget.length; i++) {
  26908. target = target[effectiveTarget[i]];
  26909. }
  26910. // Return appropriate value with its type
  26911. if (typeof (target) === "boolean")
  26912. return values[0] === "true";
  26913. if (typeof (target) === "string")
  26914. return values[0];
  26915. // Parameters with multiple values such as Vector3 etc.
  26916. var split = new Array();
  26917. for (var i = 0; i < values.length; i++)
  26918. split.push(parseFloat(values[i]));
  26919. if (target instanceof BABYLON.Vector3)
  26920. return BABYLON.Vector3.FromArray(split);
  26921. if (target instanceof BABYLON.Vector4)
  26922. return BABYLON.Vector4.FromArray(split);
  26923. if (target instanceof BABYLON.Color3)
  26924. return BABYLON.Color3.FromArray(split);
  26925. if (target instanceof BABYLON.Color4)
  26926. return BABYLON.Color4.FromArray(split);
  26927. return parseFloat(values[0]);
  26928. };
  26929. // traverse graph per trigger
  26930. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26931. if (combineArray === void 0) { combineArray = null; }
  26932. if (parsedAction.detached)
  26933. return;
  26934. var parameters = new Array();
  26935. var target = null;
  26936. var propertyPath = null;
  26937. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26938. // Parameters
  26939. if (parsedAction.type === 2)
  26940. parameters.push(actionManager);
  26941. else
  26942. parameters.push(trigger);
  26943. if (combine) {
  26944. var actions = new Array();
  26945. for (var j = 0; j < parsedAction.combine.length; j++) {
  26946. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26947. }
  26948. parameters.push(actions);
  26949. }
  26950. else {
  26951. for (var i = 0; i < parsedAction.properties.length; i++) {
  26952. var value = parsedAction.properties[i].value;
  26953. var name = parsedAction.properties[i].name;
  26954. var targetType = parsedAction.properties[i].targetType;
  26955. if (name === "target")
  26956. if (targetType !== null && targetType === "SceneProperties")
  26957. value = target = scene;
  26958. else
  26959. value = target = scene.getNodeByName(value);
  26960. else if (name === "parent")
  26961. value = scene.getNodeByName(value);
  26962. else if (name === "sound")
  26963. value = scene.getSoundByName(value);
  26964. else if (name !== "propertyPath") {
  26965. if (parsedAction.type === 2 && name === "operator")
  26966. value = BABYLON.ValueCondition[value];
  26967. else
  26968. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26969. }
  26970. else {
  26971. propertyPath = value;
  26972. }
  26973. parameters.push(value);
  26974. }
  26975. }
  26976. if (combineArray === null) {
  26977. parameters.push(condition);
  26978. }
  26979. else {
  26980. parameters.push(null);
  26981. }
  26982. // If interpolate value action
  26983. if (parsedAction.name === "InterpolateValueAction") {
  26984. var param = parameters[parameters.length - 2];
  26985. parameters[parameters.length - 1] = param;
  26986. parameters[parameters.length - 2] = condition;
  26987. }
  26988. // Action or condition(s) and not CombineAction
  26989. var newAction = instanciate(parsedAction.name, parameters);
  26990. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26991. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26992. if (action)
  26993. action.then(nothing);
  26994. else
  26995. actionManager.registerAction(nothing);
  26996. action = nothing;
  26997. }
  26998. if (combineArray === null) {
  26999. if (newAction instanceof BABYLON.Condition) {
  27000. condition = newAction;
  27001. newAction = action;
  27002. }
  27003. else {
  27004. condition = null;
  27005. if (action)
  27006. action.then(newAction);
  27007. else
  27008. actionManager.registerAction(newAction);
  27009. }
  27010. }
  27011. else {
  27012. combineArray.push(newAction);
  27013. }
  27014. for (var i = 0; i < parsedAction.children.length; i++)
  27015. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27016. };
  27017. // triggers
  27018. for (var i = 0; i < parsedActions.children.length; i++) {
  27019. var triggerParams;
  27020. var trigger = parsedActions.children[i];
  27021. if (trigger.properties.length > 0) {
  27022. var param = trigger.properties[0].value;
  27023. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27024. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27025. }
  27026. else
  27027. triggerParams = BABYLON.ActionManager[trigger.name];
  27028. for (var j = 0; j < trigger.children.length; j++) {
  27029. if (!trigger.detached)
  27030. traverse(trigger.children[j], triggerParams, null, null);
  27031. }
  27032. }
  27033. };
  27034. // Statics
  27035. ActionManager._NothingTrigger = 0;
  27036. ActionManager._OnPickTrigger = 1;
  27037. ActionManager._OnLeftPickTrigger = 2;
  27038. ActionManager._OnRightPickTrigger = 3;
  27039. ActionManager._OnCenterPickTrigger = 4;
  27040. ActionManager._OnPickDownTrigger = 5;
  27041. ActionManager._OnPickUpTrigger = 6;
  27042. ActionManager._OnLongPressTrigger = 7;
  27043. ActionManager._OnPointerOverTrigger = 8;
  27044. ActionManager._OnPointerOutTrigger = 9;
  27045. ActionManager._OnEveryFrameTrigger = 10;
  27046. ActionManager._OnIntersectionEnterTrigger = 11;
  27047. ActionManager._OnIntersectionExitTrigger = 12;
  27048. ActionManager._OnKeyDownTrigger = 13;
  27049. ActionManager._OnKeyUpTrigger = 14;
  27050. ActionManager._OnPickOutTrigger = 15;
  27051. ActionManager.DragMovementThreshold = 10; // in pixels
  27052. ActionManager.LongPressDelay = 500; // in milliseconds
  27053. return ActionManager;
  27054. })();
  27055. BABYLON.ActionManager = ActionManager;
  27056. })(BABYLON || (BABYLON = {}));
  27057. var BABYLON;
  27058. (function (BABYLON) {
  27059. var InterpolateValueAction = (function (_super) {
  27060. __extends(InterpolateValueAction, _super);
  27061. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27062. if (duration === void 0) { duration = 1000; }
  27063. _super.call(this, triggerOptions, condition);
  27064. this.propertyPath = propertyPath;
  27065. this.value = value;
  27066. this.duration = duration;
  27067. this.stopOtherAnimations = stopOtherAnimations;
  27068. this.onInterpolationDone = onInterpolationDone;
  27069. this._target = target;
  27070. }
  27071. InterpolateValueAction.prototype._prepare = function () {
  27072. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27073. this._property = this._getProperty(this.propertyPath);
  27074. };
  27075. InterpolateValueAction.prototype.execute = function () {
  27076. var scene = this._actionManager.getScene();
  27077. var keys = [
  27078. {
  27079. frame: 0,
  27080. value: this._target[this._property]
  27081. }, {
  27082. frame: 100,
  27083. value: this.value
  27084. }
  27085. ];
  27086. var dataType;
  27087. if (typeof this.value === "number") {
  27088. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27089. }
  27090. else if (this.value instanceof BABYLON.Color3) {
  27091. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27092. }
  27093. else if (this.value instanceof BABYLON.Vector3) {
  27094. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27095. }
  27096. else if (this.value instanceof BABYLON.Matrix) {
  27097. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27098. }
  27099. else if (this.value instanceof BABYLON.Quaternion) {
  27100. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27101. }
  27102. else {
  27103. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27104. return;
  27105. }
  27106. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27107. animation.setKeys(keys);
  27108. if (this.stopOtherAnimations) {
  27109. scene.stopAnimation(this._target);
  27110. }
  27111. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27112. };
  27113. return InterpolateValueAction;
  27114. })(BABYLON.Action);
  27115. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27116. })(BABYLON || (BABYLON = {}));
  27117. var BABYLON;
  27118. (function (BABYLON) {
  27119. var SwitchBooleanAction = (function (_super) {
  27120. __extends(SwitchBooleanAction, _super);
  27121. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27122. _super.call(this, triggerOptions, condition);
  27123. this.propertyPath = propertyPath;
  27124. this._target = target;
  27125. }
  27126. SwitchBooleanAction.prototype._prepare = function () {
  27127. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27128. this._property = this._getProperty(this.propertyPath);
  27129. };
  27130. SwitchBooleanAction.prototype.execute = function () {
  27131. this._target[this._property] = !this._target[this._property];
  27132. };
  27133. return SwitchBooleanAction;
  27134. })(BABYLON.Action);
  27135. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27136. var SetStateAction = (function (_super) {
  27137. __extends(SetStateAction, _super);
  27138. function SetStateAction(triggerOptions, target, value, condition) {
  27139. _super.call(this, triggerOptions, condition);
  27140. this.value = value;
  27141. this._target = target;
  27142. }
  27143. SetStateAction.prototype.execute = function () {
  27144. this._target.state = this.value;
  27145. };
  27146. return SetStateAction;
  27147. })(BABYLON.Action);
  27148. BABYLON.SetStateAction = SetStateAction;
  27149. var SetValueAction = (function (_super) {
  27150. __extends(SetValueAction, _super);
  27151. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27152. _super.call(this, triggerOptions, condition);
  27153. this.propertyPath = propertyPath;
  27154. this.value = value;
  27155. this._target = target;
  27156. }
  27157. SetValueAction.prototype._prepare = function () {
  27158. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27159. this._property = this._getProperty(this.propertyPath);
  27160. };
  27161. SetValueAction.prototype.execute = function () {
  27162. this._target[this._property] = this.value;
  27163. };
  27164. return SetValueAction;
  27165. })(BABYLON.Action);
  27166. BABYLON.SetValueAction = SetValueAction;
  27167. var IncrementValueAction = (function (_super) {
  27168. __extends(IncrementValueAction, _super);
  27169. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27170. _super.call(this, triggerOptions, condition);
  27171. this.propertyPath = propertyPath;
  27172. this.value = value;
  27173. this._target = target;
  27174. }
  27175. IncrementValueAction.prototype._prepare = function () {
  27176. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27177. this._property = this._getProperty(this.propertyPath);
  27178. if (typeof this._target[this._property] !== "number") {
  27179. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27180. }
  27181. };
  27182. IncrementValueAction.prototype.execute = function () {
  27183. this._target[this._property] += this.value;
  27184. };
  27185. return IncrementValueAction;
  27186. })(BABYLON.Action);
  27187. BABYLON.IncrementValueAction = IncrementValueAction;
  27188. var PlayAnimationAction = (function (_super) {
  27189. __extends(PlayAnimationAction, _super);
  27190. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27191. _super.call(this, triggerOptions, condition);
  27192. this.from = from;
  27193. this.to = to;
  27194. this.loop = loop;
  27195. this._target = target;
  27196. }
  27197. PlayAnimationAction.prototype._prepare = function () {
  27198. };
  27199. PlayAnimationAction.prototype.execute = function () {
  27200. var scene = this._actionManager.getScene();
  27201. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27202. };
  27203. return PlayAnimationAction;
  27204. })(BABYLON.Action);
  27205. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27206. var StopAnimationAction = (function (_super) {
  27207. __extends(StopAnimationAction, _super);
  27208. function StopAnimationAction(triggerOptions, target, condition) {
  27209. _super.call(this, triggerOptions, condition);
  27210. this._target = target;
  27211. }
  27212. StopAnimationAction.prototype._prepare = function () {
  27213. };
  27214. StopAnimationAction.prototype.execute = function () {
  27215. var scene = this._actionManager.getScene();
  27216. scene.stopAnimation(this._target);
  27217. };
  27218. return StopAnimationAction;
  27219. })(BABYLON.Action);
  27220. BABYLON.StopAnimationAction = StopAnimationAction;
  27221. var DoNothingAction = (function (_super) {
  27222. __extends(DoNothingAction, _super);
  27223. function DoNothingAction(triggerOptions, condition) {
  27224. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27225. _super.call(this, triggerOptions, condition);
  27226. }
  27227. DoNothingAction.prototype.execute = function () {
  27228. };
  27229. return DoNothingAction;
  27230. })(BABYLON.Action);
  27231. BABYLON.DoNothingAction = DoNothingAction;
  27232. var CombineAction = (function (_super) {
  27233. __extends(CombineAction, _super);
  27234. function CombineAction(triggerOptions, children, condition) {
  27235. _super.call(this, triggerOptions, condition);
  27236. this.children = children;
  27237. }
  27238. CombineAction.prototype._prepare = function () {
  27239. for (var index = 0; index < this.children.length; index++) {
  27240. this.children[index]._actionManager = this._actionManager;
  27241. this.children[index]._prepare();
  27242. }
  27243. };
  27244. CombineAction.prototype.execute = function (evt) {
  27245. for (var index = 0; index < this.children.length; index++) {
  27246. this.children[index].execute(evt);
  27247. }
  27248. };
  27249. return CombineAction;
  27250. })(BABYLON.Action);
  27251. BABYLON.CombineAction = CombineAction;
  27252. var ExecuteCodeAction = (function (_super) {
  27253. __extends(ExecuteCodeAction, _super);
  27254. function ExecuteCodeAction(triggerOptions, func, condition) {
  27255. _super.call(this, triggerOptions, condition);
  27256. this.func = func;
  27257. }
  27258. ExecuteCodeAction.prototype.execute = function (evt) {
  27259. this.func(evt);
  27260. };
  27261. return ExecuteCodeAction;
  27262. })(BABYLON.Action);
  27263. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27264. var SetParentAction = (function (_super) {
  27265. __extends(SetParentAction, _super);
  27266. function SetParentAction(triggerOptions, target, parent, condition) {
  27267. _super.call(this, triggerOptions, condition);
  27268. this._target = target;
  27269. this._parent = parent;
  27270. }
  27271. SetParentAction.prototype._prepare = function () {
  27272. };
  27273. SetParentAction.prototype.execute = function () {
  27274. if (this._target.parent === this._parent) {
  27275. return;
  27276. }
  27277. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27278. invertParentWorldMatrix.invert();
  27279. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27280. this._target.parent = this._parent;
  27281. };
  27282. return SetParentAction;
  27283. })(BABYLON.Action);
  27284. BABYLON.SetParentAction = SetParentAction;
  27285. var PlaySoundAction = (function (_super) {
  27286. __extends(PlaySoundAction, _super);
  27287. function PlaySoundAction(triggerOptions, sound, condition) {
  27288. _super.call(this, triggerOptions, condition);
  27289. this._sound = sound;
  27290. }
  27291. PlaySoundAction.prototype._prepare = function () {
  27292. };
  27293. PlaySoundAction.prototype.execute = function () {
  27294. if (this._sound !== undefined)
  27295. this._sound.play();
  27296. };
  27297. return PlaySoundAction;
  27298. })(BABYLON.Action);
  27299. BABYLON.PlaySoundAction = PlaySoundAction;
  27300. var StopSoundAction = (function (_super) {
  27301. __extends(StopSoundAction, _super);
  27302. function StopSoundAction(triggerOptions, sound, condition) {
  27303. _super.call(this, triggerOptions, condition);
  27304. this._sound = sound;
  27305. }
  27306. StopSoundAction.prototype._prepare = function () {
  27307. };
  27308. StopSoundAction.prototype.execute = function () {
  27309. if (this._sound !== undefined)
  27310. this._sound.stop();
  27311. };
  27312. return StopSoundAction;
  27313. })(BABYLON.Action);
  27314. BABYLON.StopSoundAction = StopSoundAction;
  27315. })(BABYLON || (BABYLON = {}));
  27316. var BABYLON;
  27317. (function (BABYLON) {
  27318. var Geometry = (function () {
  27319. function Geometry(id, scene, vertexData, updatable, mesh) {
  27320. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27321. this._totalVertices = 0;
  27322. this._isDisposed = false;
  27323. this.id = id;
  27324. this._engine = scene.getEngine();
  27325. this._meshes = [];
  27326. this._scene = scene;
  27327. //Init vertex buffer cache
  27328. this._vertexBuffers = {};
  27329. this._indices = [];
  27330. // vertexData
  27331. if (vertexData) {
  27332. this.setAllVerticesData(vertexData, updatable);
  27333. }
  27334. else {
  27335. this._totalVertices = 0;
  27336. this._indices = [];
  27337. }
  27338. // applyToMesh
  27339. if (mesh) {
  27340. this.applyToMesh(mesh);
  27341. mesh.computeWorldMatrix(true);
  27342. }
  27343. }
  27344. Object.defineProperty(Geometry.prototype, "extend", {
  27345. get: function () {
  27346. return this._extend;
  27347. },
  27348. enumerable: true,
  27349. configurable: true
  27350. });
  27351. Geometry.prototype.getScene = function () {
  27352. return this._scene;
  27353. };
  27354. Geometry.prototype.getEngine = function () {
  27355. return this._engine;
  27356. };
  27357. Geometry.prototype.isReady = function () {
  27358. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27359. };
  27360. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27361. vertexData.applyToGeometry(this, updatable);
  27362. this.notifyUpdate();
  27363. };
  27364. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27365. if (this._vertexBuffers[kind]) {
  27366. this._vertexBuffers[kind].dispose();
  27367. }
  27368. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27369. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27370. stride = this._vertexBuffers[kind].getStrideSize();
  27371. this._totalVertices = data.length / stride;
  27372. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27373. var meshes = this._meshes;
  27374. var numOfMeshes = meshes.length;
  27375. for (var index = 0; index < numOfMeshes; index++) {
  27376. var mesh = meshes[index];
  27377. mesh._resetPointsArrayCache();
  27378. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27379. mesh._createGlobalSubMesh();
  27380. mesh.computeWorldMatrix(true);
  27381. }
  27382. }
  27383. this.notifyUpdate(kind);
  27384. };
  27385. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27386. var vertexBuffer = this.getVertexBuffer(kind);
  27387. if (!vertexBuffer) {
  27388. return;
  27389. }
  27390. vertexBuffer.updateDirectly(data, offset);
  27391. this.notifyUpdate(kind);
  27392. };
  27393. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27394. var vertexBuffer = this.getVertexBuffer(kind);
  27395. if (!vertexBuffer) {
  27396. return;
  27397. }
  27398. vertexBuffer.update(data);
  27399. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27400. var stride = vertexBuffer.getStrideSize();
  27401. this._totalVertices = data.length / stride;
  27402. if (updateExtends) {
  27403. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27404. }
  27405. var meshes = this._meshes;
  27406. var numOfMeshes = meshes.length;
  27407. for (var index = 0; index < numOfMeshes; index++) {
  27408. var mesh = meshes[index];
  27409. mesh._resetPointsArrayCache();
  27410. if (updateExtends) {
  27411. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27412. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27413. var subMesh = mesh.subMeshes[subIndex];
  27414. subMesh.refreshBoundingInfo();
  27415. }
  27416. }
  27417. }
  27418. }
  27419. this.notifyUpdate(kind);
  27420. };
  27421. Geometry.prototype.getTotalVertices = function () {
  27422. if (!this.isReady()) {
  27423. return 0;
  27424. }
  27425. return this._totalVertices;
  27426. };
  27427. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27428. var vertexBuffer = this.getVertexBuffer(kind);
  27429. if (!vertexBuffer) {
  27430. return null;
  27431. }
  27432. var orig = vertexBuffer.getData();
  27433. if (!copyWhenShared || this._meshes.length === 1) {
  27434. return orig;
  27435. }
  27436. else {
  27437. var len = orig.length;
  27438. var copy = [];
  27439. for (var i = 0; i < len; i++) {
  27440. copy.push(orig[i]);
  27441. }
  27442. return copy;
  27443. }
  27444. };
  27445. Geometry.prototype.getVertexBuffer = function (kind) {
  27446. if (!this.isReady()) {
  27447. return null;
  27448. }
  27449. return this._vertexBuffers[kind];
  27450. };
  27451. Geometry.prototype.getVertexBuffers = function () {
  27452. if (!this.isReady()) {
  27453. return null;
  27454. }
  27455. return this._vertexBuffers;
  27456. };
  27457. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27458. if (!this._vertexBuffers) {
  27459. if (this._delayInfo) {
  27460. return this._delayInfo.indexOf(kind) !== -1;
  27461. }
  27462. return false;
  27463. }
  27464. return this._vertexBuffers[kind] !== undefined;
  27465. };
  27466. Geometry.prototype.getVerticesDataKinds = function () {
  27467. var result = [];
  27468. var kind;
  27469. if (!this._vertexBuffers && this._delayInfo) {
  27470. for (kind in this._delayInfo) {
  27471. result.push(kind);
  27472. }
  27473. }
  27474. else {
  27475. for (kind in this._vertexBuffers) {
  27476. result.push(kind);
  27477. }
  27478. }
  27479. return result;
  27480. };
  27481. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27482. if (this._indexBuffer) {
  27483. this._engine._releaseBuffer(this._indexBuffer);
  27484. }
  27485. this._indices = indices;
  27486. if (this._meshes.length !== 0 && this._indices) {
  27487. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27488. }
  27489. if (totalVertices !== undefined) {
  27490. this._totalVertices = totalVertices;
  27491. }
  27492. var meshes = this._meshes;
  27493. var numOfMeshes = meshes.length;
  27494. for (var index = 0; index < numOfMeshes; index++) {
  27495. meshes[index]._createGlobalSubMesh();
  27496. }
  27497. this.notifyUpdate();
  27498. };
  27499. Geometry.prototype.getTotalIndices = function () {
  27500. if (!this.isReady()) {
  27501. return 0;
  27502. }
  27503. return this._indices.length;
  27504. };
  27505. Geometry.prototype.getIndices = function (copyWhenShared) {
  27506. if (!this.isReady()) {
  27507. return null;
  27508. }
  27509. var orig = this._indices;
  27510. if (!copyWhenShared || this._meshes.length === 1) {
  27511. return orig;
  27512. }
  27513. else {
  27514. var len = orig.length;
  27515. var copy = [];
  27516. for (var i = 0; i < len; i++) {
  27517. copy.push(orig[i]);
  27518. }
  27519. return copy;
  27520. }
  27521. };
  27522. Geometry.prototype.getIndexBuffer = function () {
  27523. if (!this.isReady()) {
  27524. return null;
  27525. }
  27526. return this._indexBuffer;
  27527. };
  27528. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27529. var meshes = this._meshes;
  27530. var index = meshes.indexOf(mesh);
  27531. if (index === -1) {
  27532. return;
  27533. }
  27534. for (var kind in this._vertexBuffers) {
  27535. this._vertexBuffers[kind].dispose();
  27536. }
  27537. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27538. this._indexBuffer = null;
  27539. }
  27540. meshes.splice(index, 1);
  27541. mesh._geometry = null;
  27542. if (meshes.length === 0 && shouldDispose) {
  27543. this.dispose();
  27544. }
  27545. };
  27546. Geometry.prototype.applyToMesh = function (mesh) {
  27547. if (mesh._geometry === this) {
  27548. return;
  27549. }
  27550. var previousGeometry = mesh._geometry;
  27551. if (previousGeometry) {
  27552. previousGeometry.releaseForMesh(mesh);
  27553. }
  27554. var meshes = this._meshes;
  27555. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27556. mesh._geometry = this;
  27557. this._scene.pushGeometry(this);
  27558. meshes.push(mesh);
  27559. if (this.isReady()) {
  27560. this._applyToMesh(mesh);
  27561. }
  27562. else {
  27563. mesh._boundingInfo = this._boundingInfo;
  27564. }
  27565. };
  27566. Geometry.prototype._applyToMesh = function (mesh) {
  27567. var numOfMeshes = this._meshes.length;
  27568. // vertexBuffers
  27569. for (var kind in this._vertexBuffers) {
  27570. if (numOfMeshes === 1) {
  27571. this._vertexBuffers[kind].create();
  27572. }
  27573. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27574. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27575. mesh._resetPointsArrayCache();
  27576. if (!this._extend) {
  27577. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27578. }
  27579. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27580. mesh._createGlobalSubMesh();
  27581. //bounding info was just created again, world matrix should be applied again.
  27582. mesh._updateBoundingInfo();
  27583. }
  27584. }
  27585. // indexBuffer
  27586. if (numOfMeshes === 1 && this._indices) {
  27587. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27588. }
  27589. if (this._indexBuffer) {
  27590. this._indexBuffer.references = numOfMeshes;
  27591. }
  27592. };
  27593. Geometry.prototype.notifyUpdate = function (kind) {
  27594. if (this.onGeometryUpdated) {
  27595. this.onGeometryUpdated(this, kind);
  27596. }
  27597. };
  27598. Geometry.prototype.load = function (scene, onLoaded) {
  27599. var _this = this;
  27600. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27601. return;
  27602. }
  27603. if (this.isReady()) {
  27604. if (onLoaded) {
  27605. onLoaded();
  27606. }
  27607. return;
  27608. }
  27609. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27610. scene._addPendingData(this);
  27611. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27612. _this._delayLoadingFunction(JSON.parse(data), _this);
  27613. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27614. _this._delayInfo = [];
  27615. scene._removePendingData(_this);
  27616. var meshes = _this._meshes;
  27617. var numOfMeshes = meshes.length;
  27618. for (var index = 0; index < numOfMeshes; index++) {
  27619. _this._applyToMesh(meshes[index]);
  27620. }
  27621. if (onLoaded) {
  27622. onLoaded();
  27623. }
  27624. }, function () { }, scene.database);
  27625. };
  27626. Geometry.prototype.isDisposed = function () {
  27627. return this._isDisposed;
  27628. };
  27629. Geometry.prototype.dispose = function () {
  27630. var meshes = this._meshes;
  27631. var numOfMeshes = meshes.length;
  27632. var index;
  27633. for (index = 0; index < numOfMeshes; index++) {
  27634. this.releaseForMesh(meshes[index]);
  27635. }
  27636. this._meshes = [];
  27637. for (var kind in this._vertexBuffers) {
  27638. this._vertexBuffers[kind].dispose();
  27639. }
  27640. this._vertexBuffers = [];
  27641. this._totalVertices = 0;
  27642. if (this._indexBuffer) {
  27643. this._engine._releaseBuffer(this._indexBuffer);
  27644. }
  27645. this._indexBuffer = null;
  27646. this._indices = [];
  27647. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27648. this.delayLoadingFile = null;
  27649. this._delayLoadingFunction = null;
  27650. this._delayInfo = [];
  27651. this._boundingInfo = null;
  27652. this._scene.removeGeometry(this);
  27653. this._isDisposed = true;
  27654. };
  27655. Geometry.prototype.copy = function (id) {
  27656. var vertexData = new BABYLON.VertexData();
  27657. vertexData.indices = [];
  27658. var indices = this.getIndices();
  27659. for (var index = 0; index < indices.length; index++) {
  27660. vertexData.indices.push(indices[index]);
  27661. }
  27662. var updatable = false;
  27663. var stopChecking = false;
  27664. var kind;
  27665. for (kind in this._vertexBuffers) {
  27666. // using slice() to make a copy of the array and not just reference it
  27667. var data = this.getVerticesData(kind);
  27668. if (data instanceof Float32Array) {
  27669. vertexData.set(new Float32Array(data), kind);
  27670. }
  27671. else {
  27672. vertexData.set(data.slice(0), kind);
  27673. }
  27674. if (!stopChecking) {
  27675. updatable = this.getVertexBuffer(kind).isUpdatable();
  27676. stopChecking = !updatable;
  27677. }
  27678. }
  27679. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27680. geometry.delayLoadState = this.delayLoadState;
  27681. geometry.delayLoadingFile = this.delayLoadingFile;
  27682. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27683. for (kind in this._delayInfo) {
  27684. geometry._delayInfo = geometry._delayInfo || [];
  27685. geometry._delayInfo.push(kind);
  27686. }
  27687. // Bounding info
  27688. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27689. return geometry;
  27690. };
  27691. Geometry.prototype.serialize = function () {
  27692. var serializationObject = {};
  27693. serializationObject.id = this.id;
  27694. if (BABYLON.Tags.HasTags(this)) {
  27695. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27696. }
  27697. return serializationObject;
  27698. };
  27699. Geometry.prototype.serializeVerticeData = function () {
  27700. var serializationObject = this.serialize();
  27701. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27702. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27703. }
  27704. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27705. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27706. }
  27707. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27708. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27709. }
  27710. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27711. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  27712. }
  27713. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27714. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  27715. }
  27716. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27717. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  27718. }
  27719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27720. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  27721. }
  27722. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27723. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  27724. }
  27725. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27726. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27727. }
  27728. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27729. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27730. serializationObject.matricesIndices._isExpanded = true;
  27731. }
  27732. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27733. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27734. }
  27735. serializationObject.indices = this.getIndices();
  27736. return serializationObject;
  27737. };
  27738. // Statics
  27739. Geometry.ExtractFromMesh = function (mesh, id) {
  27740. var geometry = mesh._geometry;
  27741. if (!geometry) {
  27742. return null;
  27743. }
  27744. return geometry.copy(id);
  27745. };
  27746. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27747. // be aware Math.random() could cause collisions
  27748. Geometry.RandomId = function () {
  27749. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27750. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27751. return v.toString(16);
  27752. });
  27753. };
  27754. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27755. var scene = mesh.getScene();
  27756. // Geometry
  27757. var geometryId = parsedGeometry.geometryId;
  27758. if (geometryId) {
  27759. var geometry = scene.getGeometryByID(geometryId);
  27760. if (geometry) {
  27761. geometry.applyToMesh(mesh);
  27762. }
  27763. }
  27764. else if (parsedGeometry instanceof ArrayBuffer) {
  27765. var binaryInfo = mesh._binaryInfo;
  27766. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27767. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27768. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27769. }
  27770. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27771. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27772. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27773. }
  27774. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27775. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27776. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27777. }
  27778. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27779. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27780. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27781. }
  27782. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27783. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27784. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27785. }
  27786. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27787. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27788. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27789. }
  27790. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27791. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27792. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27793. }
  27794. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27795. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27796. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27797. }
  27798. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27799. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27800. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27801. }
  27802. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27803. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27804. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27805. }
  27806. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27807. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27808. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27809. }
  27810. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27811. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27812. mesh.setIndices(indicesData);
  27813. }
  27814. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27815. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27816. mesh.subMeshes = [];
  27817. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27818. var materialIndex = subMeshesData[(i * 5) + 0];
  27819. var verticesStart = subMeshesData[(i * 5) + 1];
  27820. var verticesCount = subMeshesData[(i * 5) + 2];
  27821. var indexStart = subMeshesData[(i * 5) + 3];
  27822. var indexCount = subMeshesData[(i * 5) + 4];
  27823. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27824. }
  27825. }
  27826. }
  27827. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27828. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27829. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27830. if (parsedGeometry.uvs) {
  27831. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27832. }
  27833. if (parsedGeometry.uvs2) {
  27834. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27835. }
  27836. if (parsedGeometry.uvs3) {
  27837. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27838. }
  27839. if (parsedGeometry.uvs4) {
  27840. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27841. }
  27842. if (parsedGeometry.uvs5) {
  27843. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27844. }
  27845. if (parsedGeometry.uvs6) {
  27846. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27847. }
  27848. if (parsedGeometry.colors) {
  27849. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27850. }
  27851. if (parsedGeometry.matricesIndices) {
  27852. if (!parsedGeometry.matricesIndices._isExpanded) {
  27853. var floatIndices = [];
  27854. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27855. var matricesIndex = parsedGeometry.matricesIndices[i];
  27856. floatIndices.push(matricesIndex & 0x000000FF);
  27857. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27858. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27859. floatIndices.push(matricesIndex >> 24);
  27860. }
  27861. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27862. }
  27863. else {
  27864. delete parsedGeometry.matricesIndices._isExpanded;
  27865. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27866. }
  27867. }
  27868. if (parsedGeometry.matricesIndicesExtra) {
  27869. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27870. var floatIndices = [];
  27871. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27872. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27873. floatIndices.push(matricesIndex & 0x000000FF);
  27874. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27875. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27876. floatIndices.push(matricesIndex >> 24);
  27877. }
  27878. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27879. }
  27880. else {
  27881. delete parsedGeometry.matricesIndices._isExpanded;
  27882. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27883. }
  27884. }
  27885. if (parsedGeometry.matricesWeights) {
  27886. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27887. }
  27888. if (parsedGeometry.matricesWeightsExtra) {
  27889. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27890. }
  27891. mesh.setIndices(parsedGeometry.indices);
  27892. }
  27893. // SubMeshes
  27894. if (parsedGeometry.subMeshes) {
  27895. mesh.subMeshes = [];
  27896. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27897. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27898. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27899. }
  27900. }
  27901. // Flat shading
  27902. if (mesh._shouldGenerateFlatShading) {
  27903. mesh.convertToFlatShadedMesh();
  27904. delete mesh._shouldGenerateFlatShading;
  27905. }
  27906. // Update
  27907. mesh.computeWorldMatrix(true);
  27908. // Octree
  27909. if (scene['_selectionOctree']) {
  27910. scene['_selectionOctree'].addMesh(mesh);
  27911. }
  27912. };
  27913. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27914. if (scene.getGeometryByID(parsedVertexData.id)) {
  27915. return null; // null since geometry could be something else than a box...
  27916. }
  27917. var geometry = new Geometry(parsedVertexData.id, scene);
  27918. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27919. if (parsedVertexData.delayLoadingFile) {
  27920. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27921. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27922. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27923. geometry._delayInfo = [];
  27924. if (parsedVertexData.hasUVs) {
  27925. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27926. }
  27927. if (parsedVertexData.hasUVs2) {
  27928. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27929. }
  27930. if (parsedVertexData.hasUVs3) {
  27931. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27932. }
  27933. if (parsedVertexData.hasUVs4) {
  27934. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27935. }
  27936. if (parsedVertexData.hasUVs5) {
  27937. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27938. }
  27939. if (parsedVertexData.hasUVs6) {
  27940. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27941. }
  27942. if (parsedVertexData.hasColors) {
  27943. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27944. }
  27945. if (parsedVertexData.hasMatricesIndices) {
  27946. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27947. }
  27948. if (parsedVertexData.hasMatricesWeights) {
  27949. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27950. }
  27951. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27952. }
  27953. else {
  27954. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27955. }
  27956. scene.pushGeometry(geometry, true);
  27957. return geometry;
  27958. };
  27959. return Geometry;
  27960. })();
  27961. BABYLON.Geometry = Geometry;
  27962. /////// Primitives //////////////////////////////////////////////
  27963. var Geometry;
  27964. (function (Geometry) {
  27965. var Primitives;
  27966. (function (Primitives) {
  27967. /// Abstract class
  27968. var _Primitive = (function (_super) {
  27969. __extends(_Primitive, _super);
  27970. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27971. this._beingRegenerated = true;
  27972. this._canBeRegenerated = canBeRegenerated;
  27973. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27974. this._beingRegenerated = false;
  27975. }
  27976. _Primitive.prototype.canBeRegenerated = function () {
  27977. return this._canBeRegenerated;
  27978. };
  27979. _Primitive.prototype.regenerate = function () {
  27980. if (!this._canBeRegenerated) {
  27981. return;
  27982. }
  27983. this._beingRegenerated = true;
  27984. this.setAllVerticesData(this._regenerateVertexData(), false);
  27985. this._beingRegenerated = false;
  27986. };
  27987. _Primitive.prototype.asNewGeometry = function (id) {
  27988. return _super.prototype.copy.call(this, id);
  27989. };
  27990. // overrides
  27991. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27992. if (!this._beingRegenerated) {
  27993. return;
  27994. }
  27995. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27996. };
  27997. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27998. if (!this._beingRegenerated) {
  27999. return;
  28000. }
  28001. _super.prototype.setVerticesData.call(this, kind, data, false);
  28002. };
  28003. // to override
  28004. // protected
  28005. _Primitive.prototype._regenerateVertexData = function () {
  28006. throw new Error("Abstract method");
  28007. };
  28008. _Primitive.prototype.copy = function (id) {
  28009. throw new Error("Must be overriden in sub-classes.");
  28010. };
  28011. _Primitive.prototype.serialize = function () {
  28012. var serializationObject = _super.prototype.serialize.call(this);
  28013. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28014. return serializationObject;
  28015. };
  28016. return _Primitive;
  28017. })(Geometry);
  28018. Primitives._Primitive = _Primitive;
  28019. var Ribbon = (function (_super) {
  28020. __extends(Ribbon, _super);
  28021. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28023. this.pathArray = pathArray;
  28024. this.closeArray = closeArray;
  28025. this.closePath = closePath;
  28026. this.offset = offset;
  28027. this.side = side;
  28028. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28029. }
  28030. Ribbon.prototype._regenerateVertexData = function () {
  28031. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28032. };
  28033. Ribbon.prototype.copy = function (id) {
  28034. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28035. };
  28036. return Ribbon;
  28037. })(_Primitive);
  28038. Primitives.Ribbon = Ribbon;
  28039. var Box = (function (_super) {
  28040. __extends(Box, _super);
  28041. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28042. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28043. this.size = size;
  28044. this.side = side;
  28045. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28046. }
  28047. Box.prototype._regenerateVertexData = function () {
  28048. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28049. };
  28050. Box.prototype.copy = function (id) {
  28051. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28052. };
  28053. Box.prototype.serialize = function () {
  28054. var serializationObject = _super.prototype.serialize.call(this);
  28055. serializationObject.size = this.size;
  28056. return serializationObject;
  28057. };
  28058. Box.Parse = function (parsedBox, scene) {
  28059. if (scene.getGeometryByID(parsedBox.id)) {
  28060. return null; // null since geometry could be something else than a box...
  28061. }
  28062. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28063. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28064. scene.pushGeometry(box, true);
  28065. return box;
  28066. };
  28067. return Box;
  28068. })(_Primitive);
  28069. Primitives.Box = Box;
  28070. var Sphere = (function (_super) {
  28071. __extends(Sphere, _super);
  28072. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28074. this.segments = segments;
  28075. this.diameter = diameter;
  28076. this.side = side;
  28077. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28078. }
  28079. Sphere.prototype._regenerateVertexData = function () {
  28080. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28081. };
  28082. Sphere.prototype.copy = function (id) {
  28083. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28084. };
  28085. Sphere.prototype.serialize = function () {
  28086. var serializationObject = _super.prototype.serialize.call(this);
  28087. serializationObject.segments = this.segments;
  28088. serializationObject.diameter = this.diameter;
  28089. return serializationObject;
  28090. };
  28091. Sphere.Parse = function (parsedSphere, scene) {
  28092. if (scene.getGeometryByID(parsedSphere.id)) {
  28093. return null; // null since geometry could be something else than a sphere...
  28094. }
  28095. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28096. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28097. scene.pushGeometry(sphere, true);
  28098. return sphere;
  28099. };
  28100. return Sphere;
  28101. })(_Primitive);
  28102. Primitives.Sphere = Sphere;
  28103. var Disc = (function (_super) {
  28104. __extends(Disc, _super);
  28105. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28106. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28107. this.radius = radius;
  28108. this.tessellation = tessellation;
  28109. this.side = side;
  28110. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28111. }
  28112. Disc.prototype._regenerateVertexData = function () {
  28113. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28114. };
  28115. Disc.prototype.copy = function (id) {
  28116. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28117. };
  28118. return Disc;
  28119. })(_Primitive);
  28120. Primitives.Disc = Disc;
  28121. var Cylinder = (function (_super) {
  28122. __extends(Cylinder, _super);
  28123. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28124. if (subdivisions === void 0) { subdivisions = 1; }
  28125. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28126. this.height = height;
  28127. this.diameterTop = diameterTop;
  28128. this.diameterBottom = diameterBottom;
  28129. this.tessellation = tessellation;
  28130. this.subdivisions = subdivisions;
  28131. this.side = side;
  28132. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28133. }
  28134. Cylinder.prototype._regenerateVertexData = function () {
  28135. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28136. };
  28137. Cylinder.prototype.copy = function (id) {
  28138. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28139. };
  28140. Cylinder.prototype.serialize = function () {
  28141. var serializationObject = _super.prototype.serialize.call(this);
  28142. serializationObject.height = this.height;
  28143. serializationObject.diameterTop = this.diameterTop;
  28144. serializationObject.diameterBottom = this.diameterBottom;
  28145. serializationObject.tessellation = this.tessellation;
  28146. return serializationObject;
  28147. };
  28148. Cylinder.Parse = function (parsedCylinder, scene) {
  28149. if (scene.getGeometryByID(parsedCylinder.id)) {
  28150. return null; // null since geometry could be something else than a cylinder...
  28151. }
  28152. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28153. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28154. scene.pushGeometry(cylinder, true);
  28155. return cylinder;
  28156. };
  28157. return Cylinder;
  28158. })(_Primitive);
  28159. Primitives.Cylinder = Cylinder;
  28160. var Torus = (function (_super) {
  28161. __extends(Torus, _super);
  28162. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28163. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28164. this.diameter = diameter;
  28165. this.thickness = thickness;
  28166. this.tessellation = tessellation;
  28167. this.side = side;
  28168. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28169. }
  28170. Torus.prototype._regenerateVertexData = function () {
  28171. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28172. };
  28173. Torus.prototype.copy = function (id) {
  28174. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28175. };
  28176. Torus.prototype.serialize = function () {
  28177. var serializationObject = _super.prototype.serialize.call(this);
  28178. serializationObject.diameter = this.diameter;
  28179. serializationObject.thickness = this.thickness;
  28180. serializationObject.tessellation = this.tessellation;
  28181. return serializationObject;
  28182. };
  28183. Torus.Parse = function (parsedTorus, scene) {
  28184. if (scene.getGeometryByID(parsedTorus.id)) {
  28185. return null; // null since geometry could be something else than a torus...
  28186. }
  28187. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28188. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28189. scene.pushGeometry(torus, true);
  28190. return torus;
  28191. };
  28192. return Torus;
  28193. })(_Primitive);
  28194. Primitives.Torus = Torus;
  28195. var Ground = (function (_super) {
  28196. __extends(Ground, _super);
  28197. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28198. this.width = width;
  28199. this.height = height;
  28200. this.subdivisions = subdivisions;
  28201. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28202. }
  28203. Ground.prototype._regenerateVertexData = function () {
  28204. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28205. };
  28206. Ground.prototype.copy = function (id) {
  28207. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28208. };
  28209. Ground.prototype.serialize = function () {
  28210. var serializationObject = _super.prototype.serialize.call(this);
  28211. serializationObject.width = this.width;
  28212. serializationObject.height = this.height;
  28213. serializationObject.subdivisions = this.subdivisions;
  28214. return serializationObject;
  28215. };
  28216. Ground.Parse = function (parsedGround, scene) {
  28217. if (scene.getGeometryByID(parsedGround.id)) {
  28218. return null; // null since geometry could be something else than a ground...
  28219. }
  28220. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28221. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28222. scene.pushGeometry(ground, true);
  28223. return ground;
  28224. };
  28225. return Ground;
  28226. })(_Primitive);
  28227. Primitives.Ground = Ground;
  28228. var TiledGround = (function (_super) {
  28229. __extends(TiledGround, _super);
  28230. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28231. this.xmin = xmin;
  28232. this.zmin = zmin;
  28233. this.xmax = xmax;
  28234. this.zmax = zmax;
  28235. this.subdivisions = subdivisions;
  28236. this.precision = precision;
  28237. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28238. }
  28239. TiledGround.prototype._regenerateVertexData = function () {
  28240. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28241. };
  28242. TiledGround.prototype.copy = function (id) {
  28243. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28244. };
  28245. return TiledGround;
  28246. })(_Primitive);
  28247. Primitives.TiledGround = TiledGround;
  28248. var Plane = (function (_super) {
  28249. __extends(Plane, _super);
  28250. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28251. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28252. this.size = size;
  28253. this.side = side;
  28254. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28255. }
  28256. Plane.prototype._regenerateVertexData = function () {
  28257. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28258. };
  28259. Plane.prototype.copy = function (id) {
  28260. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28261. };
  28262. Plane.prototype.serialize = function () {
  28263. var serializationObject = _super.prototype.serialize.call(this);
  28264. serializationObject.size = this.size;
  28265. return serializationObject;
  28266. };
  28267. Plane.Parse = function (parsedPlane, scene) {
  28268. if (scene.getGeometryByID(parsedPlane.id)) {
  28269. return null; // null since geometry could be something else than a ground...
  28270. }
  28271. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28272. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28273. scene.pushGeometry(plane, true);
  28274. return plane;
  28275. };
  28276. return Plane;
  28277. })(_Primitive);
  28278. Primitives.Plane = Plane;
  28279. var TorusKnot = (function (_super) {
  28280. __extends(TorusKnot, _super);
  28281. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28282. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28283. this.radius = radius;
  28284. this.tube = tube;
  28285. this.radialSegments = radialSegments;
  28286. this.tubularSegments = tubularSegments;
  28287. this.p = p;
  28288. this.q = q;
  28289. this.side = side;
  28290. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28291. }
  28292. TorusKnot.prototype._regenerateVertexData = function () {
  28293. 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 });
  28294. };
  28295. TorusKnot.prototype.copy = function (id) {
  28296. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28297. };
  28298. TorusKnot.prototype.serialize = function () {
  28299. var serializationObject = _super.prototype.serialize.call(this);
  28300. serializationObject.radius = this.radius;
  28301. serializationObject.tube = this.tube;
  28302. serializationObject.radialSegments = this.radialSegments;
  28303. serializationObject.tubularSegments = this.tubularSegments;
  28304. serializationObject.p = this.p;
  28305. serializationObject.q = this.q;
  28306. return serializationObject;
  28307. };
  28308. ;
  28309. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28310. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28311. return null; // null since geometry could be something else than a ground...
  28312. }
  28313. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28314. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28315. scene.pushGeometry(torusKnot, true);
  28316. return torusKnot;
  28317. };
  28318. return TorusKnot;
  28319. })(_Primitive);
  28320. Primitives.TorusKnot = TorusKnot;
  28321. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28322. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28323. })(BABYLON || (BABYLON = {}));
  28324. var BABYLON;
  28325. (function (BABYLON) {
  28326. var GroundMesh = (function (_super) {
  28327. __extends(GroundMesh, _super);
  28328. function GroundMesh(name, scene) {
  28329. _super.call(this, name, scene);
  28330. this.generateOctree = false;
  28331. this._worldInverse = new BABYLON.Matrix();
  28332. }
  28333. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28334. get: function () {
  28335. return this._subdivisions;
  28336. },
  28337. enumerable: true,
  28338. configurable: true
  28339. });
  28340. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28341. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28342. this._subdivisions = chunksCount;
  28343. this.subdivide(this._subdivisions);
  28344. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28345. };
  28346. /**
  28347. * Returns a height (y) value in the Worl system :
  28348. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28349. * Returns the ground y position if (x, z) are outside the ground surface.
  28350. * Not pertinent if the ground is rotated.
  28351. */
  28352. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28353. // express x and y in the ground local system
  28354. x -= this.position.x;
  28355. z -= this.position.z;
  28356. x /= this.scaling.x;
  28357. z /= this.scaling.z;
  28358. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28359. return this.position.y;
  28360. }
  28361. if (!this._heightQuads || this._heightQuads.length == 0) {
  28362. this._initHeightQuads();
  28363. this._computeHeightQuads();
  28364. }
  28365. var facet = this._getFacetAt(x, z);
  28366. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28367. // return y in the World system
  28368. return y * this.scaling.y + this.position.y;
  28369. };
  28370. /**
  28371. * Returns a normalized vector (Vector3) orthogonal to the ground
  28372. * at the ground coordinates (x, z) expressed in the World system.
  28373. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28374. * Not pertinent if the ground is rotated.
  28375. */
  28376. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28377. var normal = new BABYLON.Vector3(0, 1, 0);
  28378. this.getNormalAtCoordinatesToRef(x, z, normal);
  28379. return normal;
  28380. };
  28381. /**
  28382. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28383. * at the ground coordinates (x, z) expressed in the World system.
  28384. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28385. * Not pertinent if the ground is rotated.
  28386. */
  28387. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28388. // express x and y in the ground local system
  28389. x -= this.position.x;
  28390. z -= this.position.z;
  28391. x /= this.scaling.x;
  28392. z /= this.scaling.z;
  28393. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28394. return;
  28395. }
  28396. if (!this._heightQuads || this._heightQuads.length == 0) {
  28397. this._initHeightQuads();
  28398. this._computeHeightQuads();
  28399. }
  28400. var facet = this._getFacetAt(x, z);
  28401. ref.x = facet.x;
  28402. ref.y = facet.y;
  28403. ref.z = facet.z;
  28404. };
  28405. /**
  28406. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  28407. * if the ground has been updated.
  28408. * This can be used in the render loop
  28409. */
  28410. GroundMesh.prototype.updateCoordinateHeights = function () {
  28411. if (!this._heightQuads || this._heightQuads.length == 0) {
  28412. this._initHeightQuads();
  28413. }
  28414. this._computeHeightQuads();
  28415. };
  28416. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28417. GroundMesh.prototype._getFacetAt = function (x, z) {
  28418. // retrieve col and row from x, z coordinates in the ground local system
  28419. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28420. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28421. var quad = this._heightQuads[row * this._subdivisions + col];
  28422. var facet;
  28423. if (z < quad.slope.x * x + quad.slope.y) {
  28424. facet = quad.facet1;
  28425. }
  28426. else {
  28427. facet = quad.facet2;
  28428. }
  28429. return facet;
  28430. };
  28431. // Creates and populates the heightMap array with "facet" elements :
  28432. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28433. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28434. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28435. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28436. GroundMesh.prototype._initHeightQuads = function () {
  28437. this._heightQuads = new Array();
  28438. for (var row = 0; row < this._subdivisions; row++) {
  28439. for (var col = 0; col < this._subdivisions; col++) {
  28440. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  28441. this._heightQuads[row * this._subdivisions + col] = quad;
  28442. }
  28443. }
  28444. };
  28445. // Compute each quad element values and update the the heightMap array :
  28446. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28447. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28448. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28449. GroundMesh.prototype._computeHeightQuads = function () {
  28450. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28451. var v1 = BABYLON.Tmp.Vector3[0];
  28452. var v2 = BABYLON.Tmp.Vector3[1];
  28453. var v3 = BABYLON.Tmp.Vector3[2];
  28454. var v4 = BABYLON.Tmp.Vector3[3];
  28455. var v1v2 = BABYLON.Tmp.Vector3[4];
  28456. var v1v3 = BABYLON.Tmp.Vector3[5];
  28457. var v1v4 = BABYLON.Tmp.Vector3[6];
  28458. var norm1 = BABYLON.Tmp.Vector3[7];
  28459. var norm2 = BABYLON.Tmp.Vector3[8];
  28460. var i = 0;
  28461. var j = 0;
  28462. var k = 0;
  28463. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28464. var h = 0;
  28465. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28466. var d2 = 0;
  28467. for (var row = 0; row < this._subdivisions; row++) {
  28468. for (var col = 0; col < this._subdivisions; col++) {
  28469. i = col * 3;
  28470. j = row * (this._subdivisions + 1) * 3;
  28471. k = (row + 1) * (this._subdivisions + 1) * 3;
  28472. v1.x = positions[j + i];
  28473. v1.y = positions[j + i + 1];
  28474. v1.z = positions[j + i + 2];
  28475. v2.x = positions[j + i + 3];
  28476. v2.y = positions[j + i + 4];
  28477. v2.z = positions[j + i + 5];
  28478. v3.x = positions[k + i];
  28479. v3.y = positions[k + i + 1];
  28480. v3.z = positions[k + i + 2];
  28481. v4.x = positions[k + i + 3];
  28482. v4.y = positions[k + i + 4];
  28483. v4.z = positions[k + i + 5];
  28484. // 2D slope V1V4
  28485. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28486. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28487. // facet equations :
  28488. // we compute each facet normal vector
  28489. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28490. // we compute the value d by applying the equation to v1 which belongs to the plane
  28491. // then we store the facet equation in a Vector4
  28492. v2.subtractToRef(v1, v1v2);
  28493. v3.subtractToRef(v1, v1v3);
  28494. v4.subtractToRef(v1, v1v4);
  28495. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28496. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28497. norm1.normalize();
  28498. norm2.normalize();
  28499. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28500. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28501. var quad = this._heightQuads[row * this._subdivisions + col];
  28502. quad.slope.copyFromFloats(cd, h);
  28503. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  28504. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  28505. }
  28506. }
  28507. };
  28508. return GroundMesh;
  28509. })(BABYLON.Mesh);
  28510. BABYLON.GroundMesh = GroundMesh;
  28511. })(BABYLON || (BABYLON = {}));
  28512. var BABYLON;
  28513. (function (BABYLON) {
  28514. var LinesMesh = (function (_super) {
  28515. __extends(LinesMesh, _super);
  28516. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28517. if (parent === void 0) { parent = null; }
  28518. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28519. this.color = new BABYLON.Color3(1, 1, 1);
  28520. this.alpha = 1;
  28521. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28522. attributes: ["position"],
  28523. uniforms: ["worldViewProjection", "color"],
  28524. needAlphaBlending: true
  28525. });
  28526. }
  28527. Object.defineProperty(LinesMesh.prototype, "material", {
  28528. get: function () {
  28529. return this._colorShader;
  28530. },
  28531. enumerable: true,
  28532. configurable: true
  28533. });
  28534. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28535. get: function () {
  28536. return false;
  28537. },
  28538. enumerable: true,
  28539. configurable: true
  28540. });
  28541. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28542. get: function () {
  28543. return false;
  28544. },
  28545. enumerable: true,
  28546. configurable: true
  28547. });
  28548. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28549. var engine = this.getScene().getEngine();
  28550. var indexToBind = this._geometry.getIndexBuffer();
  28551. // VBOs
  28552. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28553. // Color
  28554. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28555. };
  28556. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28557. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28558. return;
  28559. }
  28560. var engine = this.getScene().getEngine();
  28561. // Draw order
  28562. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28563. };
  28564. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28565. return null;
  28566. };
  28567. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28568. this._colorShader.dispose();
  28569. _super.prototype.dispose.call(this, doNotRecurse);
  28570. };
  28571. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28572. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28573. };
  28574. return LinesMesh;
  28575. })(BABYLON.Mesh);
  28576. BABYLON.LinesMesh = LinesMesh;
  28577. })(BABYLON || (BABYLON = {}));
  28578. var BABYLON;
  28579. (function (BABYLON) {
  28580. var DebugLayer = (function () {
  28581. function DebugLayer(scene) {
  28582. var _this = this;
  28583. this._transformationMatrix = BABYLON.Matrix.Identity();
  28584. this._enabled = false;
  28585. this._labelsEnabled = false;
  28586. this._displayStatistics = true;
  28587. this._displayTree = false;
  28588. this._displayLogs = false;
  28589. this._identityMatrix = BABYLON.Matrix.Identity();
  28590. this.axisRatio = 0.02;
  28591. this.accentColor = "orange";
  28592. this._scene = scene;
  28593. this._syncPositions = function () {
  28594. var engine = _this._scene.getEngine();
  28595. var canvasRect = engine.getRenderingCanvasClientRect();
  28596. if (_this._showUI) {
  28597. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28598. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28599. _this._statsDiv.style.width = "400px";
  28600. _this._statsDiv.style.height = "auto";
  28601. _this._statsSubsetDiv.style.maxHeight = "240px";
  28602. _this._optionsDiv.style.left = "0px";
  28603. _this._optionsDiv.style.top = "10px";
  28604. _this._optionsDiv.style.width = "200px";
  28605. _this._optionsDiv.style.height = "auto";
  28606. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28607. _this._logDiv.style.left = "0px";
  28608. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28609. _this._logDiv.style.width = "600px";
  28610. _this._logDiv.style.height = "160px";
  28611. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28612. _this._treeDiv.style.top = "10px";
  28613. _this._treeDiv.style.width = "300px";
  28614. _this._treeDiv.style.height = "auto";
  28615. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28616. }
  28617. _this._globalDiv.style.left = canvasRect.left + "px";
  28618. _this._globalDiv.style.top = canvasRect.top + "px";
  28619. _this._drawingCanvas.style.left = "0px";
  28620. _this._drawingCanvas.style.top = "0px";
  28621. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28622. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28623. var devicePixelRatio = window.devicePixelRatio || 1;
  28624. var context = _this._drawingContext;
  28625. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  28626. context.mozBackingStorePixelRatio ||
  28627. context.msBackingStorePixelRatio ||
  28628. context.oBackingStorePixelRatio ||
  28629. context.backingStorePixelRatio || 1;
  28630. _this._ratio = devicePixelRatio / backingStoreRatio;
  28631. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28632. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28633. };
  28634. this._onCanvasClick = function (evt) {
  28635. _this._clickPosition = {
  28636. x: evt.clientX * _this._ratio,
  28637. y: evt.clientY * _this._ratio
  28638. };
  28639. };
  28640. this._syncUI = function () {
  28641. if (_this._showUI) {
  28642. if (_this._displayStatistics) {
  28643. _this._displayStats();
  28644. _this._statsDiv.style.display = "";
  28645. }
  28646. else {
  28647. _this._statsDiv.style.display = "none";
  28648. }
  28649. if (_this._displayLogs) {
  28650. _this._logDiv.style.display = "";
  28651. }
  28652. else {
  28653. _this._logDiv.style.display = "none";
  28654. }
  28655. if (_this._displayTree) {
  28656. _this._treeDiv.style.display = "";
  28657. if (_this._needToRefreshMeshesTree) {
  28658. _this._needToRefreshMeshesTree = false;
  28659. _this._refreshMeshesTreeContent();
  28660. }
  28661. }
  28662. else {
  28663. _this._treeDiv.style.display = "none";
  28664. }
  28665. }
  28666. };
  28667. this._syncData = function () {
  28668. if (_this._labelsEnabled || !_this._showUI) {
  28669. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28670. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28671. var engine = _this._scene.getEngine();
  28672. var viewport = _this._camera.viewport;
  28673. var globalViewport = viewport.toGlobal(engine);
  28674. // Meshes
  28675. var meshes = _this._camera.getActiveMeshes();
  28676. var index;
  28677. var projectedPosition;
  28678. for (index = 0; index < meshes.length; index++) {
  28679. var mesh = meshes.data[index];
  28680. var position = mesh.getBoundingInfo().boundingSphere.center;
  28681. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28682. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28683. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28684. }
  28685. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28686. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  28687. }
  28688. }
  28689. // Cameras
  28690. var cameras = _this._scene.cameras;
  28691. for (index = 0; index < cameras.length; index++) {
  28692. var camera = cameras[index];
  28693. if (camera === _this._camera) {
  28694. continue;
  28695. }
  28696. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28697. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28698. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28699. _this._camera.detachControl(engine.getRenderingCanvas());
  28700. _this._camera = camera;
  28701. _this._camera.attachControl(engine.getRenderingCanvas());
  28702. }, function () { return "purple"; });
  28703. }
  28704. }
  28705. // Lights
  28706. var lights = _this._scene.lights;
  28707. for (index = 0; index < lights.length; index++) {
  28708. var light = lights[index];
  28709. if (light.position) {
  28710. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28711. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28712. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28713. light.setEnabled(!light.isEnabled());
  28714. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  28715. }
  28716. }
  28717. }
  28718. }
  28719. _this._clickPosition = undefined;
  28720. };
  28721. }
  28722. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28723. while (this._treeSubsetDiv.hasChildNodes()) {
  28724. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28725. }
  28726. // Add meshes
  28727. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28728. sortedArray.sort(function (a, b) {
  28729. if (a.name === b.name) {
  28730. return 0;
  28731. }
  28732. return (a.name > b.name) ? 1 : -1;
  28733. });
  28734. for (var index = 0; index < sortedArray.length; index++) {
  28735. var mesh = sortedArray[index];
  28736. if (!mesh.isEnabled()) {
  28737. continue;
  28738. }
  28739. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28740. m.isVisible = element.checked;
  28741. }, mesh);
  28742. }
  28743. };
  28744. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28745. this._drawingContext.beginPath();
  28746. this._drawingContext.moveTo(zero.x, zero.y);
  28747. this._drawingContext.lineTo(unit.x, unit.y);
  28748. this._drawingContext.strokeStyle = color;
  28749. this._drawingContext.lineWidth = 4;
  28750. this._drawingContext.stroke();
  28751. this._drawingContext.font = "normal 14px Segoe UI";
  28752. this._drawingContext.fillStyle = color;
  28753. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28754. };
  28755. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28756. var position = mesh.getBoundingInfo().boundingSphere.center;
  28757. var worldMatrix = mesh.getWorldMatrix();
  28758. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28759. var unit = (unprojectedVector.subtract(position)).length();
  28760. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28761. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28762. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28763. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28764. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28765. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28766. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28767. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28768. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28769. };
  28770. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28771. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28772. this._drawingContext.font = "normal 12px Segoe UI";
  28773. var textMetrics = this._drawingContext.measureText(text);
  28774. var centerX = projectedPosition.x - textMetrics.width / 2;
  28775. var centerY = projectedPosition.y;
  28776. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28777. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28778. onClick();
  28779. }
  28780. this._drawingContext.beginPath();
  28781. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28782. this._drawingContext.fillStyle = getFillStyle();
  28783. this._drawingContext.globalAlpha = 0.5;
  28784. this._drawingContext.fill();
  28785. this._drawingContext.globalAlpha = 1.0;
  28786. this._drawingContext.strokeStyle = '#FFFFFF';
  28787. this._drawingContext.lineWidth = 1;
  28788. this._drawingContext.stroke();
  28789. this._drawingContext.fillStyle = "#FFFFFF";
  28790. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28791. this._drawingContext.beginPath();
  28792. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28793. this._drawingContext.fill();
  28794. }
  28795. };
  28796. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28797. if (!this._clickPosition) {
  28798. return false;
  28799. }
  28800. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28801. return false;
  28802. }
  28803. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28804. return false;
  28805. }
  28806. return true;
  28807. };
  28808. DebugLayer.prototype.isVisible = function () {
  28809. return this._enabled;
  28810. };
  28811. DebugLayer.prototype.hide = function () {
  28812. if (!this._enabled) {
  28813. return;
  28814. }
  28815. this._enabled = false;
  28816. var engine = this._scene.getEngine();
  28817. this._scene.unregisterBeforeRender(this._syncData);
  28818. this._scene.unregisterAfterRender(this._syncUI);
  28819. this._rootElement.removeChild(this._globalDiv);
  28820. this._scene.forceShowBoundingBoxes = false;
  28821. this._scene.forceWireframe = false;
  28822. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28823. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28824. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28825. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28826. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28827. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28828. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28829. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  28830. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  28831. this._scene.shadowsEnabled = true;
  28832. this._scene.particlesEnabled = true;
  28833. this._scene.postProcessesEnabled = true;
  28834. this._scene.collisionsEnabled = true;
  28835. this._scene.lightsEnabled = true;
  28836. this._scene.texturesEnabled = true;
  28837. this._scene.lensFlaresEnabled = true;
  28838. this._scene.proceduralTexturesEnabled = true;
  28839. this._scene.renderTargetsEnabled = true;
  28840. this._scene.probesEnabled = true;
  28841. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28842. };
  28843. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28844. if (showUI === void 0) { showUI = true; }
  28845. if (camera === void 0) { camera = null; }
  28846. if (rootElement === void 0) { rootElement = null; }
  28847. if (this._enabled) {
  28848. return;
  28849. }
  28850. this._enabled = true;
  28851. if (camera) {
  28852. this._camera = camera;
  28853. }
  28854. else {
  28855. this._camera = this._scene.activeCamera;
  28856. }
  28857. this._showUI = showUI;
  28858. var engine = this._scene.getEngine();
  28859. this._globalDiv = document.createElement("div");
  28860. this._rootElement = rootElement || document.body;
  28861. this._rootElement.appendChild(this._globalDiv);
  28862. this._generateDOMelements();
  28863. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28864. this._syncPositions();
  28865. this._scene.registerBeforeRender(this._syncData);
  28866. this._scene.registerAfterRender(this._syncUI);
  28867. };
  28868. DebugLayer.prototype._clearLabels = function () {
  28869. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28870. for (var index = 0; index < this._scene.meshes.length; index++) {
  28871. var mesh = this._scene.meshes[index];
  28872. mesh.renderOverlay = false;
  28873. }
  28874. };
  28875. DebugLayer.prototype._generateheader = function (root, text) {
  28876. var header = document.createElement("div");
  28877. header.innerHTML = text + "&nbsp;";
  28878. header.style.textAlign = "right";
  28879. header.style.width = "100%";
  28880. header.style.color = "white";
  28881. header.style.backgroundColor = "Black";
  28882. header.style.padding = "5px 5px 4px 0px";
  28883. header.style.marginLeft = "-5px";
  28884. header.style.fontWeight = "bold";
  28885. root.appendChild(header);
  28886. };
  28887. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28888. var label = document.createElement("label");
  28889. label.innerHTML = title;
  28890. label.style.color = color;
  28891. root.appendChild(label);
  28892. root.appendChild(document.createElement("br"));
  28893. };
  28894. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28895. if (tag === void 0) { tag = null; }
  28896. var label = document.createElement("label");
  28897. var boundingBoxesCheckbox = document.createElement("input");
  28898. boundingBoxesCheckbox.type = "checkbox";
  28899. boundingBoxesCheckbox.checked = initialState;
  28900. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28901. task(evt.target, tag);
  28902. });
  28903. label.appendChild(boundingBoxesCheckbox);
  28904. var container = document.createElement("span");
  28905. var leftPart = document.createElement("span");
  28906. var rightPart = document.createElement("span");
  28907. rightPart.style.cssFloat = "right";
  28908. leftPart.innerHTML = leftTitle;
  28909. rightPart.innerHTML = rightTitle;
  28910. rightPart.style.fontSize = "12px";
  28911. rightPart.style.maxWidth = "200px";
  28912. container.appendChild(leftPart);
  28913. container.appendChild(rightPart);
  28914. label.appendChild(container);
  28915. root.appendChild(label);
  28916. root.appendChild(document.createElement("br"));
  28917. };
  28918. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28919. if (tag === void 0) { tag = null; }
  28920. var label = document.createElement("label");
  28921. var checkBox = document.createElement("input");
  28922. checkBox.type = "checkbox";
  28923. checkBox.checked = initialState;
  28924. checkBox.addEventListener("change", function (evt) {
  28925. task(evt.target, tag);
  28926. });
  28927. label.appendChild(checkBox);
  28928. label.appendChild(document.createTextNode(title));
  28929. root.appendChild(label);
  28930. root.appendChild(document.createElement("br"));
  28931. };
  28932. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28933. if (tag === void 0) { tag = null; }
  28934. var button = document.createElement("button");
  28935. button.innerHTML = title;
  28936. button.style.height = "24px";
  28937. button.style.width = "150px";
  28938. button.style.marginBottom = "5px";
  28939. button.style.color = "#444444";
  28940. button.style.border = "1px solid white";
  28941. button.className = "debugLayerButton";
  28942. button.addEventListener("click", function (evt) {
  28943. task(evt.target, tag);
  28944. });
  28945. root.appendChild(button);
  28946. root.appendChild(document.createElement("br"));
  28947. };
  28948. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28949. if (tag === void 0) { tag = null; }
  28950. var label = document.createElement("label");
  28951. var boundingBoxesRadio = document.createElement("input");
  28952. boundingBoxesRadio.type = "radio";
  28953. boundingBoxesRadio.name = name;
  28954. boundingBoxesRadio.checked = initialState;
  28955. boundingBoxesRadio.addEventListener("change", function (evt) {
  28956. task(evt.target, tag);
  28957. });
  28958. label.appendChild(boundingBoxesRadio);
  28959. label.appendChild(document.createTextNode(title));
  28960. root.appendChild(label);
  28961. root.appendChild(document.createElement("br"));
  28962. };
  28963. DebugLayer.prototype._generateDOMelements = function () {
  28964. var _this = this;
  28965. this._globalDiv.id = "DebugLayer";
  28966. this._globalDiv.style.position = "absolute";
  28967. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28968. this._globalDiv.style.fontSize = "14px";
  28969. this._globalDiv.style.color = "white";
  28970. // Drawing canvas
  28971. this._drawingCanvas = document.createElement("canvas");
  28972. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28973. this._drawingCanvas.style.position = "absolute";
  28974. this._drawingCanvas.style.pointerEvents = "none";
  28975. this._drawingCanvas.style.backgroundColor = "transparent";
  28976. this._drawingContext = this._drawingCanvas.getContext("2d");
  28977. this._globalDiv.appendChild(this._drawingCanvas);
  28978. if (this._showUI) {
  28979. var background = "rgba(128, 128, 128, 0.4)";
  28980. var border = "rgb(180, 180, 180) solid 1px";
  28981. // Stats
  28982. this._statsDiv = document.createElement("div");
  28983. this._statsDiv.id = "DebugLayerStats";
  28984. this._statsDiv.style.border = border;
  28985. this._statsDiv.style.position = "absolute";
  28986. this._statsDiv.style.background = background;
  28987. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28988. this._generateheader(this._statsDiv, "STATISTICS");
  28989. this._statsSubsetDiv = document.createElement("div");
  28990. this._statsSubsetDiv.style.paddingTop = "5px";
  28991. this._statsSubsetDiv.style.paddingBottom = "5px";
  28992. this._statsSubsetDiv.style.overflowY = "auto";
  28993. this._statsDiv.appendChild(this._statsSubsetDiv);
  28994. // Tree
  28995. this._treeDiv = document.createElement("div");
  28996. this._treeDiv.id = "DebugLayerTree";
  28997. this._treeDiv.style.border = border;
  28998. this._treeDiv.style.position = "absolute";
  28999. this._treeDiv.style.background = background;
  29000. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29001. this._treeDiv.style.display = "none";
  29002. this._generateheader(this._treeDiv, "MESHES TREE");
  29003. this._treeSubsetDiv = document.createElement("div");
  29004. this._treeSubsetDiv.style.paddingTop = "5px";
  29005. this._treeSubsetDiv.style.paddingRight = "5px";
  29006. this._treeSubsetDiv.style.overflowY = "auto";
  29007. this._treeSubsetDiv.style.maxHeight = "300px";
  29008. this._treeDiv.appendChild(this._treeSubsetDiv);
  29009. this._needToRefreshMeshesTree = true;
  29010. // Logs
  29011. this._logDiv = document.createElement("div");
  29012. this._logDiv.style.border = border;
  29013. this._logDiv.id = "DebugLayerLogs";
  29014. this._logDiv.style.position = "absolute";
  29015. this._logDiv.style.background = background;
  29016. this._logDiv.style.padding = "0px 0px 0px 5px";
  29017. this._logDiv.style.display = "none";
  29018. this._generateheader(this._logDiv, "LOGS");
  29019. this._logSubsetDiv = document.createElement("div");
  29020. this._logSubsetDiv.style.height = "127px";
  29021. this._logSubsetDiv.style.paddingTop = "5px";
  29022. this._logSubsetDiv.style.overflowY = "auto";
  29023. this._logSubsetDiv.style.fontSize = "12px";
  29024. this._logSubsetDiv.style.fontFamily = "consolas";
  29025. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29026. this._logDiv.appendChild(this._logSubsetDiv);
  29027. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29028. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29029. };
  29030. // Options
  29031. this._optionsDiv = document.createElement("div");
  29032. this._optionsDiv.id = "DebugLayerOptions";
  29033. this._optionsDiv.style.border = border;
  29034. this._optionsDiv.style.position = "absolute";
  29035. this._optionsDiv.style.background = background;
  29036. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29037. this._optionsDiv.style.overflowY = "auto";
  29038. this._generateheader(this._optionsDiv, "OPTIONS");
  29039. this._optionsSubsetDiv = document.createElement("div");
  29040. this._optionsSubsetDiv.style.paddingTop = "5px";
  29041. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29042. this._optionsSubsetDiv.style.overflowY = "auto";
  29043. this._optionsSubsetDiv.style.maxHeight = "200px";
  29044. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29045. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29046. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29047. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29048. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29049. _this._displayTree = element.checked;
  29050. _this._needToRefreshMeshesTree = true;
  29051. });
  29052. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29053. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29054. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29055. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29056. _this._labelsEnabled = element.checked;
  29057. if (!_this._labelsEnabled) {
  29058. _this._clearLabels();
  29059. }
  29060. });
  29061. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29062. if (element.checked) {
  29063. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29064. }
  29065. else {
  29066. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29067. }
  29068. });
  29069. ;
  29070. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29071. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29072. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29073. if (element.checked) {
  29074. _this._scene.forceWireframe = false;
  29075. _this._scene.forcePointsCloud = false;
  29076. }
  29077. });
  29078. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29079. if (element.checked) {
  29080. _this._scene.forceWireframe = true;
  29081. _this._scene.forcePointsCloud = false;
  29082. }
  29083. });
  29084. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29085. if (element.checked) {
  29086. _this._scene.forceWireframe = false;
  29087. _this._scene.forcePointsCloud = true;
  29088. }
  29089. });
  29090. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29091. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29092. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29093. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29094. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29095. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29096. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29097. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29098. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29099. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29100. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29101. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29102. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29103. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29104. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29105. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29106. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29107. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29108. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29109. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29110. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29111. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29112. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29113. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29114. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29115. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29116. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29117. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29118. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29119. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29120. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29121. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29122. if (element.checked) {
  29123. _this._scene.headphone = true;
  29124. }
  29125. });
  29126. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29127. if (element.checked) {
  29128. _this._scene.headphone = false;
  29129. }
  29130. });
  29131. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29132. _this._scene.audioEnabled = !element.checked;
  29133. });
  29134. }
  29135. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29136. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29137. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29138. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29139. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29140. if (_this._camera) {
  29141. console.log(_this._camera);
  29142. }
  29143. else {
  29144. console.warn("No camera defined, or debug layer created before camera creation!");
  29145. }
  29146. });
  29147. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29148. this._globalDiv.appendChild(this._statsDiv);
  29149. this._globalDiv.appendChild(this._logDiv);
  29150. this._globalDiv.appendChild(this._optionsDiv);
  29151. this._globalDiv.appendChild(this._treeDiv);
  29152. }
  29153. };
  29154. DebugLayer.prototype._displayStats = function () {
  29155. var scene = this._scene;
  29156. var engine = scene.getEngine();
  29157. var glInfo = engine.getGlInfo();
  29158. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29159. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29160. + "<b>Count</b><br>"
  29161. + "Total meshes: " + scene.meshes.length + "<br>"
  29162. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29163. + "Total materials: " + scene.materials.length + "<br>"
  29164. + "Total textures: " + scene.textures.length + "<br>"
  29165. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29166. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29167. + "Active bones: " + scene.getActiveBones() + "<br>"
  29168. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29169. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29170. + "<b>Duration</b><br>"
  29171. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29172. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29173. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29174. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29175. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29176. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29177. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29178. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29179. + "</div>"
  29180. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29181. + "<b>Extensions</b><br>"
  29182. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29183. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29184. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29185. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29186. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29187. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29188. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29189. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29190. + "</div><br>"
  29191. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29192. + "<b>Caps.</b><br>"
  29193. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29194. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29195. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29196. + "<b>Info</b><br>"
  29197. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29198. + glInfo.version + "<br>"
  29199. + "</div><br>"
  29200. + glInfo.renderer + "<br>";
  29201. if (this.customStatsFunction) {
  29202. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29203. }
  29204. };
  29205. return DebugLayer;
  29206. })();
  29207. BABYLON.DebugLayer = DebugLayer;
  29208. })(BABYLON || (BABYLON = {}));
  29209. var BABYLON;
  29210. (function (BABYLON) {
  29211. var DefaultLoadingScreen = (function () {
  29212. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29213. var _this = this;
  29214. if (_loadingText === void 0) { _loadingText = ""; }
  29215. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29216. this._renderingCanvas = _renderingCanvas;
  29217. this._loadingText = _loadingText;
  29218. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29219. // Resize
  29220. this._resizeLoadingUI = function () {
  29221. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29222. _this._loadingDiv.style.position = "absolute";
  29223. _this._loadingDiv.style.left = canvasRect.left + "px";
  29224. _this._loadingDiv.style.top = canvasRect.top + "px";
  29225. _this._loadingDiv.style.width = canvasRect.width + "px";
  29226. _this._loadingDiv.style.height = canvasRect.height + "px";
  29227. };
  29228. }
  29229. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29230. var _this = this;
  29231. if (this._loadingDiv) {
  29232. // Do not add a loading screen if there is already one
  29233. return;
  29234. }
  29235. this._loadingDiv = document.createElement("div");
  29236. this._loadingDiv.id = "babylonjsLoadingDiv";
  29237. this._loadingDiv.style.opacity = "0";
  29238. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29239. // Loading text
  29240. this._loadingTextDiv = document.createElement("div");
  29241. this._loadingTextDiv.style.position = "absolute";
  29242. this._loadingTextDiv.style.left = "0";
  29243. this._loadingTextDiv.style.top = "50%";
  29244. this._loadingTextDiv.style.marginTop = "80px";
  29245. this._loadingTextDiv.style.width = "100%";
  29246. this._loadingTextDiv.style.height = "20px";
  29247. this._loadingTextDiv.style.fontFamily = "Arial";
  29248. this._loadingTextDiv.style.fontSize = "14px";
  29249. this._loadingTextDiv.style.color = "white";
  29250. this._loadingTextDiv.style.textAlign = "center";
  29251. this._loadingTextDiv.innerHTML = "Loading";
  29252. this._loadingDiv.appendChild(this._loadingTextDiv);
  29253. //set the predefined text
  29254. this._loadingTextDiv.innerHTML = this._loadingText;
  29255. // Loading img
  29256. var imgBack = new Image();
  29257. 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==";
  29258. imgBack.style.position = "absolute";
  29259. imgBack.style.left = "50%";
  29260. imgBack.style.top = "50%";
  29261. imgBack.style.marginLeft = "-50px";
  29262. imgBack.style.marginTop = "-50px";
  29263. imgBack.style.transition = "transform 1.0s ease";
  29264. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29265. var deg = 360;
  29266. var onTransitionEnd = function () {
  29267. deg += 360;
  29268. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29269. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29270. };
  29271. imgBack.addEventListener("transitionend", onTransitionEnd);
  29272. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29273. this._loadingDiv.appendChild(imgBack);
  29274. // front image
  29275. var imgFront = new Image();
  29276. 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=";
  29277. imgFront.style.position = "absolute";
  29278. imgFront.style.left = "50%";
  29279. imgFront.style.top = "50%";
  29280. imgFront.style.marginLeft = "-50px";
  29281. imgFront.style.marginTop = "-50px";
  29282. this._loadingDiv.appendChild(imgFront);
  29283. this._resizeLoadingUI();
  29284. window.addEventListener("resize", this._resizeLoadingUI);
  29285. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29286. document.body.appendChild(this._loadingDiv);
  29287. setTimeout(function () {
  29288. _this._loadingDiv.style.opacity = "1";
  29289. imgBack.style.transform = "rotateZ(360deg)";
  29290. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29291. }, 0);
  29292. };
  29293. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29294. var _this = this;
  29295. if (!this._loadingDiv) {
  29296. return;
  29297. }
  29298. var onTransitionEnd = function () {
  29299. if (!_this._loadingDiv) {
  29300. return;
  29301. }
  29302. document.body.removeChild(_this._loadingDiv);
  29303. window.removeEventListener("resize", _this._resizeLoadingUI);
  29304. _this._loadingDiv = null;
  29305. };
  29306. this._loadingDiv.style.opacity = "0";
  29307. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29308. };
  29309. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29310. set: function (text) {
  29311. this._loadingText = text;
  29312. if (this._loadingTextDiv) {
  29313. this._loadingTextDiv.innerHTML = this._loadingText;
  29314. }
  29315. },
  29316. enumerable: true,
  29317. configurable: true
  29318. });
  29319. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29320. get: function () {
  29321. return this._loadingDivBackgroundColor;
  29322. },
  29323. set: function (color) {
  29324. this._loadingDivBackgroundColor = color;
  29325. if (!this._loadingDiv) {
  29326. return;
  29327. }
  29328. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29329. },
  29330. enumerable: true,
  29331. configurable: true
  29332. });
  29333. return DefaultLoadingScreen;
  29334. })();
  29335. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29336. })(BABYLON || (BABYLON = {}));
  29337. var BABYLON;
  29338. (function (BABYLON) {
  29339. var SIMDVector3 = (function () {
  29340. function SIMDVector3() {
  29341. }
  29342. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29343. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29344. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29345. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29346. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29347. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29348. 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));
  29349. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29350. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29351. };
  29352. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29353. var v0 = SIMD.float32x4.splat(x);
  29354. var v1 = SIMD.float32x4.splat(y);
  29355. var v2 = SIMD.float32x4.splat(z);
  29356. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29357. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29358. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29359. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29360. 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));
  29361. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29362. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29363. };
  29364. return SIMDVector3;
  29365. })();
  29366. BABYLON.SIMDVector3 = SIMDVector3;
  29367. var SIMDMatrix = (function () {
  29368. function SIMDMatrix() {
  29369. }
  29370. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29371. if (offset === void 0) { offset = 0; }
  29372. var tm = this.m;
  29373. var om = other.m;
  29374. var om0 = SIMD.float32x4.load(om, 0);
  29375. var om1 = SIMD.float32x4.load(om, 4);
  29376. var om2 = SIMD.float32x4.load(om, 8);
  29377. var om3 = SIMD.float32x4.load(om, 12);
  29378. var tm0 = SIMD.float32x4.load(tm, 0);
  29379. 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)))));
  29380. var tm1 = SIMD.float32x4.load(tm, 4);
  29381. 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)))));
  29382. var tm2 = SIMD.float32x4.load(tm, 8);
  29383. 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)))));
  29384. var tm3 = SIMD.float32x4.load(tm, 12);
  29385. 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)))));
  29386. };
  29387. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29388. var src = this.m;
  29389. var dest = other.m;
  29390. var row0, row1, row2, row3;
  29391. var tmp1;
  29392. var minor0, minor1, minor2, minor3;
  29393. var det;
  29394. // Load the 4 rows
  29395. var src0 = SIMD.float32x4.load(src, 0);
  29396. var src1 = SIMD.float32x4.load(src, 4);
  29397. var src2 = SIMD.float32x4.load(src, 8);
  29398. var src3 = SIMD.float32x4.load(src, 12);
  29399. // Transpose the source matrix. Sort of. Not a true transpose operation
  29400. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29401. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29402. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29403. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29404. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29405. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29406. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29407. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29408. // This is a true transposition, but it will lead to an incorrect result
  29409. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29410. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29411. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29412. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29413. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29414. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29415. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29416. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29417. // ----
  29418. tmp1 = SIMD.float32x4.mul(row2, row3);
  29419. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29420. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29421. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29422. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29423. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29424. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29425. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29426. // ----
  29427. tmp1 = SIMD.float32x4.mul(row1, row2);
  29428. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29429. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29430. minor3 = SIMD.float32x4.mul(row0, tmp1);
  29431. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29432. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  29433. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  29434. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  29435. // ----
  29436. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  29437. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29438. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  29439. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  29440. minor2 = SIMD.float32x4.mul(row0, tmp1);
  29441. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29442. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  29443. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  29444. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  29445. // ----
  29446. tmp1 = SIMD.float32x4.mul(row0, row1);
  29447. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29448. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29449. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29450. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29451. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29452. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29453. // ----
  29454. tmp1 = SIMD.float32x4.mul(row0, row3);
  29455. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29456. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29457. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29458. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29459. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29460. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29461. // ----
  29462. tmp1 = SIMD.float32x4.mul(row0, row2);
  29463. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29464. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  29465. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  29466. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29467. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  29468. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  29469. // Compute determinant
  29470. det = SIMD.float32x4.mul(row0, minor0);
  29471. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  29472. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  29473. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  29474. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  29475. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  29476. // These shuffles aren't necessary if the faulty transposition is done
  29477. // up at the top of this function.
  29478. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  29479. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  29480. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  29481. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  29482. // Compute final values by multiplying with 1/det
  29483. minor0 = SIMD.float32x4.mul(det, minor0);
  29484. minor1 = SIMD.float32x4.mul(det, minor1);
  29485. minor2 = SIMD.float32x4.mul(det, minor2);
  29486. minor3 = SIMD.float32x4.mul(det, minor3);
  29487. SIMD.float32x4.store(dest, 0, minor0);
  29488. SIMD.float32x4.store(dest, 4, minor1);
  29489. SIMD.float32x4.store(dest, 8, minor2);
  29490. SIMD.float32x4.store(dest, 12, minor3);
  29491. return this;
  29492. };
  29493. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  29494. var out = result.m;
  29495. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  29496. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  29497. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  29498. // cc.kmVec3Subtract(f, pCenter, pEye);
  29499. var f = SIMD.float32x4.sub(center, eye);
  29500. // cc.kmVec3Normalize(f, f);
  29501. var tmp = SIMD.float32x4.mul(f, f);
  29502. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29503. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29504. // cc.kmVec3Assign(up, pUp);
  29505. // cc.kmVec3Normalize(up, up);
  29506. tmp = SIMD.float32x4.mul(up, up);
  29507. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29508. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29509. // cc.kmVec3Cross(s, f, up);
  29510. 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)));
  29511. // cc.kmVec3Normalize(s, s);
  29512. tmp = SIMD.float32x4.mul(s, s);
  29513. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29514. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29515. // cc.kmVec3Cross(u, s, f);
  29516. 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)));
  29517. // cc.kmVec3Normalize(s, s);
  29518. tmp = SIMD.float32x4.mul(s, s);
  29519. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29520. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29521. var zero = SIMD.float32x4.splat(0.0);
  29522. s = SIMD.float32x4.neg(s);
  29523. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  29524. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  29525. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29526. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  29527. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  29528. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  29529. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29530. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  29531. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  29532. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  29533. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  29534. var b3 = SIMD.float32x4.neg(eye);
  29535. b3 = SIMD.float32x4.withW(b3, 1.0);
  29536. 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)))));
  29537. 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)))));
  29538. 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)))));
  29539. 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)))));
  29540. };
  29541. return SIMDMatrix;
  29542. })();
  29543. BABYLON.SIMDMatrix = SIMDMatrix;
  29544. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  29545. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  29546. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  29547. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  29548. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  29549. var SIMDHelper = (function () {
  29550. function SIMDHelper() {
  29551. }
  29552. Object.defineProperty(SIMDHelper, "IsEnabled", {
  29553. get: function () {
  29554. return SIMDHelper._isEnabled;
  29555. },
  29556. enumerable: true,
  29557. configurable: true
  29558. });
  29559. SIMDHelper.DisableSIMD = function () {
  29560. // Replace functions
  29561. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  29562. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  29563. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  29564. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  29565. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  29566. SIMDHelper._isEnabled = false;
  29567. };
  29568. SIMDHelper.EnableSIMD = function () {
  29569. if (window.SIMD === undefined) {
  29570. return;
  29571. }
  29572. // Replace functions
  29573. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  29574. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  29575. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  29576. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  29577. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  29578. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  29579. get: function () { return this._data[0]; },
  29580. set: function (value) {
  29581. if (!this._data) {
  29582. this._data = new Float32Array(3);
  29583. }
  29584. this._data[0] = value;
  29585. }
  29586. });
  29587. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  29588. get: function () { return this._data[1]; },
  29589. set: function (value) {
  29590. this._data[1] = value;
  29591. }
  29592. });
  29593. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  29594. get: function () { return this._data[2]; },
  29595. set: function (value) {
  29596. this._data[2] = value;
  29597. }
  29598. });
  29599. SIMDHelper._isEnabled = true;
  29600. };
  29601. SIMDHelper._isEnabled = false;
  29602. return SIMDHelper;
  29603. })();
  29604. BABYLON.SIMDHelper = SIMDHelper;
  29605. })(BABYLON || (BABYLON = {}));
  29606. var BABYLON;
  29607. (function (BABYLON) {
  29608. var ShaderMaterial = (function (_super) {
  29609. __extends(ShaderMaterial, _super);
  29610. function ShaderMaterial(name, scene, shaderPath, options) {
  29611. _super.call(this, name, scene);
  29612. this._textures = {};
  29613. this._floats = {};
  29614. this._floatsArrays = {};
  29615. this._colors3 = {};
  29616. this._colors4 = {};
  29617. this._vectors2 = {};
  29618. this._vectors3 = {};
  29619. this._vectors4 = {};
  29620. this._matrices = {};
  29621. this._matrices3x3 = {};
  29622. this._matrices2x2 = {};
  29623. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  29624. this._shaderPath = shaderPath;
  29625. options.needAlphaBlending = options.needAlphaBlending || false;
  29626. options.needAlphaTesting = options.needAlphaTesting || false;
  29627. options.attributes = options.attributes || ["position", "normal", "uv"];
  29628. options.uniforms = options.uniforms || ["worldViewProjection"];
  29629. options.samplers = options.samplers || [];
  29630. options.defines = options.defines || [];
  29631. this._options = options;
  29632. }
  29633. ShaderMaterial.prototype.needAlphaBlending = function () {
  29634. return this._options.needAlphaBlending;
  29635. };
  29636. ShaderMaterial.prototype.needAlphaTesting = function () {
  29637. return this._options.needAlphaTesting;
  29638. };
  29639. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  29640. if (this._options.uniforms.indexOf(uniformName) === -1) {
  29641. this._options.uniforms.push(uniformName);
  29642. }
  29643. };
  29644. ShaderMaterial.prototype.setTexture = function (name, texture) {
  29645. if (this._options.samplers.indexOf(name) === -1) {
  29646. this._options.samplers.push(name);
  29647. }
  29648. this._textures[name] = texture;
  29649. return this;
  29650. };
  29651. ShaderMaterial.prototype.setFloat = function (name, value) {
  29652. this._checkUniform(name);
  29653. this._floats[name] = value;
  29654. return this;
  29655. };
  29656. ShaderMaterial.prototype.setFloats = function (name, value) {
  29657. this._checkUniform(name);
  29658. this._floatsArrays[name] = value;
  29659. return this;
  29660. };
  29661. ShaderMaterial.prototype.setColor3 = function (name, value) {
  29662. this._checkUniform(name);
  29663. this._colors3[name] = value;
  29664. return this;
  29665. };
  29666. ShaderMaterial.prototype.setColor4 = function (name, value) {
  29667. this._checkUniform(name);
  29668. this._colors4[name] = value;
  29669. return this;
  29670. };
  29671. ShaderMaterial.prototype.setVector2 = function (name, value) {
  29672. this._checkUniform(name);
  29673. this._vectors2[name] = value;
  29674. return this;
  29675. };
  29676. ShaderMaterial.prototype.setVector3 = function (name, value) {
  29677. this._checkUniform(name);
  29678. this._vectors3[name] = value;
  29679. return this;
  29680. };
  29681. ShaderMaterial.prototype.setVector4 = function (name, value) {
  29682. this._checkUniform(name);
  29683. this._vectors4[name] = value;
  29684. return this;
  29685. };
  29686. ShaderMaterial.prototype.setMatrix = function (name, value) {
  29687. this._checkUniform(name);
  29688. this._matrices[name] = value;
  29689. return this;
  29690. };
  29691. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  29692. this._checkUniform(name);
  29693. this._matrices3x3[name] = value;
  29694. return this;
  29695. };
  29696. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  29697. this._checkUniform(name);
  29698. this._matrices2x2[name] = value;
  29699. return this;
  29700. };
  29701. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  29702. var scene = this.getScene();
  29703. var engine = scene.getEngine();
  29704. if (!this.checkReadyOnEveryCall) {
  29705. if (this._renderId === scene.getRenderId()) {
  29706. return true;
  29707. }
  29708. }
  29709. // Instances
  29710. var defines = [];
  29711. var fallbacks = new BABYLON.EffectFallbacks();
  29712. if (useInstances) {
  29713. defines.push("#define INSTANCES");
  29714. }
  29715. for (var index = 0; index < this._options.defines.length; index++) {
  29716. defines.push(this._options.defines[index]);
  29717. }
  29718. // Bones
  29719. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29720. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  29721. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29722. fallbacks.addCPUSkinningFallback(0, mesh);
  29723. }
  29724. // Alpha test
  29725. if (engine.getAlphaTesting()) {
  29726. defines.push("#define ALPHATEST");
  29727. }
  29728. var previousEffect = this._effect;
  29729. var join = defines.join("\n");
  29730. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  29731. if (!this._effect.isReady()) {
  29732. return false;
  29733. }
  29734. if (previousEffect !== this._effect) {
  29735. scene.resetCachedMaterial();
  29736. }
  29737. this._renderId = scene.getRenderId();
  29738. return true;
  29739. };
  29740. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29741. var scene = this.getScene();
  29742. if (this._options.uniforms.indexOf("world") !== -1) {
  29743. this._effect.setMatrix("world", world);
  29744. }
  29745. if (this._options.uniforms.indexOf("worldView") !== -1) {
  29746. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  29747. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  29748. }
  29749. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  29750. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  29751. }
  29752. };
  29753. ShaderMaterial.prototype.bind = function (world, mesh) {
  29754. // Std values
  29755. this.bindOnlyWorldMatrix(world);
  29756. if (this.getScene().getCachedMaterial() !== this) {
  29757. if (this._options.uniforms.indexOf("view") !== -1) {
  29758. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  29759. }
  29760. if (this._options.uniforms.indexOf("projection") !== -1) {
  29761. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  29762. }
  29763. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  29764. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29765. }
  29766. // Bones
  29767. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29768. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  29769. }
  29770. // Texture
  29771. for (var name in this._textures) {
  29772. this._effect.setTexture(name, this._textures[name]);
  29773. }
  29774. // Float
  29775. for (name in this._floats) {
  29776. this._effect.setFloat(name, this._floats[name]);
  29777. }
  29778. // Float s
  29779. for (name in this._floatsArrays) {
  29780. this._effect.setArray(name, this._floatsArrays[name]);
  29781. }
  29782. // Color3
  29783. for (name in this._colors3) {
  29784. this._effect.setColor3(name, this._colors3[name]);
  29785. }
  29786. // Color4
  29787. for (name in this._colors4) {
  29788. var color = this._colors4[name];
  29789. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  29790. }
  29791. // Vector2
  29792. for (name in this._vectors2) {
  29793. this._effect.setVector2(name, this._vectors2[name]);
  29794. }
  29795. // Vector3
  29796. for (name in this._vectors3) {
  29797. this._effect.setVector3(name, this._vectors3[name]);
  29798. }
  29799. // Vector4
  29800. for (name in this._vectors4) {
  29801. this._effect.setVector4(name, this._vectors4[name]);
  29802. }
  29803. // Matrix
  29804. for (name in this._matrices) {
  29805. this._effect.setMatrix(name, this._matrices[name]);
  29806. }
  29807. // Matrix 3x3
  29808. for (name in this._matrices3x3) {
  29809. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  29810. }
  29811. // Matrix 2x2
  29812. for (name in this._matrices2x2) {
  29813. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  29814. }
  29815. }
  29816. _super.prototype.bind.call(this, world, mesh);
  29817. };
  29818. ShaderMaterial.prototype.clone = function (name) {
  29819. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  29820. return newShaderMaterial;
  29821. };
  29822. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  29823. for (var name in this._textures) {
  29824. this._textures[name].dispose();
  29825. }
  29826. this._textures = {};
  29827. _super.prototype.dispose.call(this, forceDisposeEffect);
  29828. };
  29829. ShaderMaterial.prototype.serialize = function () {
  29830. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29831. serializationObject.customType = "BABYLON.ShaderMaterial";
  29832. serializationObject.options = this._options;
  29833. serializationObject.shaderPath = this._shaderPath;
  29834. // Texture
  29835. serializationObject.textures = {};
  29836. for (var name in this._textures) {
  29837. serializationObject.textures[name] = this._textures[name].serialize();
  29838. }
  29839. // Float
  29840. serializationObject.floats = {};
  29841. for (name in this._floats) {
  29842. serializationObject.floats[name] = this._floats[name];
  29843. }
  29844. // Float s
  29845. serializationObject.floatArrays = {};
  29846. for (name in this._floatsArrays) {
  29847. serializationObject.floatArrays[name] = this._floatsArrays[name];
  29848. }
  29849. // Color3
  29850. serializationObject.colors3 = {};
  29851. for (name in this._colors3) {
  29852. serializationObject.colors3[name] = this._colors3[name].asArray();
  29853. }
  29854. // Color4
  29855. serializationObject.colors4 = {};
  29856. for (name in this._colors4) {
  29857. serializationObject.colors4[name] = this._colors4[name].asArray();
  29858. }
  29859. // Vector2
  29860. serializationObject.vectors2 = {};
  29861. for (name in this._vectors2) {
  29862. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  29863. }
  29864. // Vector3
  29865. serializationObject.vectors3 = {};
  29866. for (name in this._vectors3) {
  29867. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  29868. }
  29869. // Vector4
  29870. serializationObject.vectors4 = {};
  29871. for (name in this._vectors4) {
  29872. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  29873. }
  29874. // Matrix
  29875. serializationObject.matrices = {};
  29876. for (name in this._matrices) {
  29877. serializationObject.matrices[name] = this._matrices[name].asArray();
  29878. }
  29879. // Matrix 3x3
  29880. serializationObject.matrices3x3 = {};
  29881. for (name in this._matrices3x3) {
  29882. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  29883. }
  29884. // Matrix 2x2
  29885. serializationObject.matrices2x2 = {};
  29886. for (name in this._matrices2x2) {
  29887. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  29888. }
  29889. return serializationObject;
  29890. };
  29891. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  29892. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  29893. // Texture
  29894. for (var name in source.textures) {
  29895. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  29896. }
  29897. // Float
  29898. for (name in source.floats) {
  29899. material.setFloat(name, source.floats[name]);
  29900. }
  29901. // Float s
  29902. for (name in source.floatsArrays) {
  29903. material.setFloats(name, source.floatsArrays[name]);
  29904. }
  29905. // Color3
  29906. for (name in source.colors3) {
  29907. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  29908. }
  29909. // Color4
  29910. for (name in source.colors4) {
  29911. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  29912. }
  29913. // Vector2
  29914. for (name in source.vectors2) {
  29915. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  29916. }
  29917. // Vector3
  29918. for (name in source.vectors3) {
  29919. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  29920. }
  29921. // Vector4
  29922. for (name in source.vectors4) {
  29923. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  29924. }
  29925. // Matrix
  29926. for (name in source.matrices) {
  29927. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  29928. }
  29929. // Matrix 3x3
  29930. for (name in source.matrices3x3) {
  29931. material.setMatrix3x3(name, source.matrices3x3[name]);
  29932. }
  29933. // Matrix 2x2
  29934. for (name in source.matrices2x2) {
  29935. material.setMatrix2x2(name, source.matrices2x2[name]);
  29936. }
  29937. return material;
  29938. };
  29939. return ShaderMaterial;
  29940. })(BABYLON.Material);
  29941. BABYLON.ShaderMaterial = ShaderMaterial;
  29942. })(BABYLON || (BABYLON = {}));
  29943. var BABYLON;
  29944. (function (BABYLON) {
  29945. var Internals;
  29946. (function (Internals) {
  29947. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29948. // All values and structures referenced from:
  29949. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29950. var DDS_MAGIC = 0x20534444;
  29951. 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;
  29952. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29953. 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;
  29954. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29955. function FourCCToInt32(value) {
  29956. return value.charCodeAt(0) +
  29957. (value.charCodeAt(1) << 8) +
  29958. (value.charCodeAt(2) << 16) +
  29959. (value.charCodeAt(3) << 24);
  29960. }
  29961. function Int32ToFourCC(value) {
  29962. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29963. }
  29964. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29965. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29966. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29967. var headerLengthInt = 31; // The header length in 32 bit ints
  29968. // Offsets into the header array
  29969. var off_magic = 0;
  29970. var off_size = 1;
  29971. var off_flags = 2;
  29972. var off_height = 3;
  29973. var off_width = 4;
  29974. var off_mipmapCount = 7;
  29975. var off_pfFlags = 20;
  29976. var off_pfFourCC = 21;
  29977. var off_RGBbpp = 22;
  29978. var off_RMask = 23;
  29979. var off_GMask = 24;
  29980. var off_BMask = 25;
  29981. var off_AMask = 26;
  29982. var off_caps1 = 27;
  29983. var off_caps2 = 28;
  29984. ;
  29985. var DDSTools = (function () {
  29986. function DDSTools() {
  29987. }
  29988. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29989. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29990. var mipmapCount = 1;
  29991. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29992. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29993. }
  29994. return {
  29995. width: header[off_width],
  29996. height: header[off_height],
  29997. mipmapCount: mipmapCount,
  29998. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29999. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30000. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30001. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30002. };
  30003. };
  30004. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30005. var byteArray = new Uint8Array(dataLength);
  30006. var srcData = new Uint8Array(arrayBuffer);
  30007. var index = 0;
  30008. for (var y = height - 1; y >= 0; y--) {
  30009. for (var x = 0; x < width; x++) {
  30010. var srcPos = dataOffset + (x + y * width) * 4;
  30011. byteArray[index + 2] = srcData[srcPos];
  30012. byteArray[index + 1] = srcData[srcPos + 1];
  30013. byteArray[index] = srcData[srcPos + 2];
  30014. byteArray[index + 3] = srcData[srcPos + 3];
  30015. index += 4;
  30016. }
  30017. }
  30018. return byteArray;
  30019. };
  30020. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30021. var byteArray = new Uint8Array(dataLength);
  30022. var srcData = new Uint8Array(arrayBuffer);
  30023. var index = 0;
  30024. for (var y = height - 1; y >= 0; y--) {
  30025. for (var x = 0; x < width; x++) {
  30026. var srcPos = dataOffset + (x + y * width) * 3;
  30027. byteArray[index + 2] = srcData[srcPos];
  30028. byteArray[index + 1] = srcData[srcPos + 1];
  30029. byteArray[index] = srcData[srcPos + 2];
  30030. index += 3;
  30031. }
  30032. }
  30033. return byteArray;
  30034. };
  30035. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30036. var byteArray = new Uint8Array(dataLength);
  30037. var srcData = new Uint8Array(arrayBuffer);
  30038. var index = 0;
  30039. for (var y = height - 1; y >= 0; y--) {
  30040. for (var x = 0; x < width; x++) {
  30041. var srcPos = dataOffset + (x + y * width);
  30042. byteArray[index] = srcData[srcPos];
  30043. index++;
  30044. }
  30045. }
  30046. return byteArray;
  30047. };
  30048. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30049. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30050. if (header[off_magic] != DDS_MAGIC) {
  30051. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30052. return;
  30053. }
  30054. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30055. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30056. return;
  30057. }
  30058. if (info.isFourCC) {
  30059. fourCC = header[off_pfFourCC];
  30060. switch (fourCC) {
  30061. case FOURCC_DXT1:
  30062. blockBytes = 8;
  30063. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30064. break;
  30065. case FOURCC_DXT3:
  30066. blockBytes = 16;
  30067. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30068. break;
  30069. case FOURCC_DXT5:
  30070. blockBytes = 16;
  30071. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30072. break;
  30073. default:
  30074. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30075. return;
  30076. }
  30077. }
  30078. mipmapCount = 1;
  30079. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30080. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30081. }
  30082. var bpp = header[off_RGBbpp];
  30083. for (var face = 0; face < faces; face++) {
  30084. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30085. width = header[off_width];
  30086. height = header[off_height];
  30087. dataOffset = header[off_size] + 4;
  30088. for (i = 0; i < mipmapCount; ++i) {
  30089. if (info.isRGB) {
  30090. if (bpp === 24) {
  30091. dataLength = width * height * 3;
  30092. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30093. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30094. }
  30095. else {
  30096. dataLength = width * height * 4;
  30097. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30098. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30099. }
  30100. }
  30101. else if (info.isLuminance) {
  30102. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30103. var unpaddedRowSize = width;
  30104. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30105. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30106. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30107. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30108. }
  30109. else {
  30110. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30111. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30112. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30113. }
  30114. dataOffset += dataLength;
  30115. width *= 0.5;
  30116. height *= 0.5;
  30117. width = Math.max(1.0, width);
  30118. height = Math.max(1.0, height);
  30119. }
  30120. }
  30121. };
  30122. return DDSTools;
  30123. })();
  30124. Internals.DDSTools = DDSTools;
  30125. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30126. })(BABYLON || (BABYLON = {}));
  30127. var BABYLON;
  30128. (function (BABYLON) {
  30129. var CannonJSPlugin = (function () {
  30130. function CannonJSPlugin(_useDeltaForWorldStep) {
  30131. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30132. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30133. this._registeredMeshes = [];
  30134. this._physicsMaterials = [];
  30135. this._fixedTimeStep = 1 / 60;
  30136. //private _maxSubSteps : number = 15;
  30137. this.name = "CannonJS";
  30138. this.updateBodyPosition = function (mesh) {
  30139. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30140. var registeredMesh = this._registeredMeshes[index];
  30141. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30142. var body = registeredMesh.body;
  30143. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30144. body.quaternion.copy(mesh.rotationQuaternion);
  30145. if (registeredMesh.deltaRotation) {
  30146. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30147. body.quaternion = body.quaternion.mult(tmpQ);
  30148. }
  30149. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  30150. //calculate the correct body position:
  30151. var rotationQuaternion = mesh.rotationQuaternion;
  30152. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30153. mesh.computeWorldMatrix(true);
  30154. //get original center with no rotation
  30155. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30156. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30157. //rotation is back
  30158. mesh.rotationQuaternion = rotationQuaternion;
  30159. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30160. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30161. mesh.setPivotMatrix(p);
  30162. mesh.computeWorldMatrix(true);
  30163. //calculate the translation
  30164. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30165. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30166. //add it inverted to the delta
  30167. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30168. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30169. mesh.setPivotMatrix(oldPivot);
  30170. mesh.computeWorldMatrix(true);
  30171. }
  30172. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  30173. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  30174. }
  30175. body.position.set(center.x, center.y, center.z);
  30176. return;
  30177. }
  30178. }
  30179. };
  30180. }
  30181. CannonJSPlugin.prototype.initialize = function (iterations) {
  30182. if (iterations === void 0) { iterations = 10; }
  30183. this._world = new CANNON.World();
  30184. this._world.broadphase = new CANNON.NaiveBroadphase();
  30185. this._world.solver.iterations = iterations;
  30186. };
  30187. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  30188. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30189. };
  30190. CannonJSPlugin.prototype.runOneStep = function (delta) {
  30191. var _this = this;
  30192. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  30193. this._registeredMeshes.forEach(function (registeredMesh) {
  30194. // Body position
  30195. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  30196. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  30197. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  30198. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  30199. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  30200. if (registeredMesh.deltaRotation) {
  30201. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  30202. }
  30203. //is the physics collision callback is set?
  30204. if (registeredMesh.mesh.onPhysicsCollide) {
  30205. if (!registeredMesh.collisionFunction) {
  30206. registeredMesh.collisionFunction = function (e) {
  30207. //find the mesh that collided with the registered mesh
  30208. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  30209. if (_this._registeredMeshes[idx].body == e.body) {
  30210. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  30211. }
  30212. }
  30213. };
  30214. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  30215. }
  30216. }
  30217. else {
  30218. //unregister, in case the function was removed for some reason
  30219. if (registeredMesh.collisionFunction) {
  30220. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  30221. }
  30222. }
  30223. });
  30224. };
  30225. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30226. this._gravity = gravity;
  30227. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  30228. };
  30229. CannonJSPlugin.prototype.getGravity = function () {
  30230. return this._gravity;
  30231. };
  30232. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30233. this.unregisterMesh(mesh);
  30234. if (!mesh.rotationQuaternion) {
  30235. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30236. }
  30237. mesh.computeWorldMatrix(true);
  30238. var shape = this._createShape(mesh, impostor);
  30239. return this._createRigidBodyFromShape(shape, mesh, options);
  30240. };
  30241. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  30242. //get the correct bounding box
  30243. var oldQuaternion = mesh.rotationQuaternion;
  30244. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30245. mesh.computeWorldMatrix(true);
  30246. var returnValue;
  30247. switch (impostor) {
  30248. case BABYLON.PhysicsEngine.SphereImpostor:
  30249. var bbox = mesh.getBoundingInfo().boundingBox;
  30250. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30251. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30252. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30253. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  30254. break;
  30255. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  30256. case BABYLON.PhysicsEngine.CylinderImpostor:
  30257. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  30258. case BABYLON.PhysicsEngine.BoxImpostor:
  30259. bbox = mesh.getBoundingInfo().boundingBox;
  30260. var min = bbox.minimumWorld;
  30261. var max = bbox.maximumWorld;
  30262. var box = max.subtract(min).scale(0.5);
  30263. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  30264. break;
  30265. case BABYLON.PhysicsEngine.PlaneImpostor:
  30266. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  30267. returnValue = new CANNON.Plane();
  30268. break;
  30269. case BABYLON.PhysicsEngine.MeshImpostor:
  30270. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30271. var rawFaces = mesh.getIndices();
  30272. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  30273. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  30274. break;
  30275. case BABYLON.PhysicsEngine.HeightmapImpostor:
  30276. returnValue = this._createHeightmap(mesh);
  30277. break;
  30278. }
  30279. mesh.rotationQuaternion = oldQuaternion;
  30280. return returnValue;
  30281. };
  30282. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  30283. var verts = [], faces = [];
  30284. mesh.computeWorldMatrix(true);
  30285. //reuse this variable
  30286. var transformed = BABYLON.Vector3.Zero();
  30287. // Get vertices
  30288. for (var i = 0; i < rawVerts.length; i += 3) {
  30289. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  30290. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  30291. }
  30292. // Get faces
  30293. for (var j = 0; j < rawFaces.length; j += 3) {
  30294. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  30295. }
  30296. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  30297. return shape;
  30298. };
  30299. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30300. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30301. var matrix = [];
  30302. //For now pointDepth will not be used and will be automatically calculated.
  30303. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30304. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30305. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30306. var elementSize = dim * 2 / arraySize;
  30307. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30308. for (var i = 0; i < pos.length; i = i + 3) {
  30309. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30310. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30311. var y = pos[i + 1] + minY;
  30312. if (!matrix[x]) {
  30313. matrix[x] = [];
  30314. }
  30315. if (!matrix[x][z]) {
  30316. matrix[x][z] = y;
  30317. }
  30318. matrix[x][z] = Math.max(y, matrix[x][z]);
  30319. }
  30320. for (var x = 0; x <= arraySize; ++x) {
  30321. if (!matrix[x]) {
  30322. var loc = 1;
  30323. while (!matrix[(x + loc) % arraySize]) {
  30324. loc++;
  30325. }
  30326. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30327. }
  30328. for (var z = 0; z <= arraySize; ++z) {
  30329. if (!matrix[x][z]) {
  30330. var loc = 1;
  30331. var newValue;
  30332. while (newValue === undefined) {
  30333. newValue = matrix[x][(z + loc++) % arraySize];
  30334. }
  30335. matrix[x][z] = newValue;
  30336. }
  30337. }
  30338. }
  30339. var shape = new CANNON.Heightfield(matrix, {
  30340. elementSize: elementSize
  30341. });
  30342. //For future reference, needed for body transformation
  30343. shape.minY = minY;
  30344. return shape;
  30345. };
  30346. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  30347. var index;
  30348. var mat;
  30349. for (index = 0; index < this._physicsMaterials.length; index++) {
  30350. mat = this._physicsMaterials[index];
  30351. if (mat.friction === friction && mat.restitution === restitution) {
  30352. return mat;
  30353. }
  30354. }
  30355. var currentMat = new CANNON.Material("mat");
  30356. this._physicsMaterials.push(currentMat);
  30357. for (index = 0; index < this._physicsMaterials.length; index++) {
  30358. mat = this._physicsMaterials[index];
  30359. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  30360. this._world.addContactMaterial(contactMaterial);
  30361. }
  30362. return currentMat;
  30363. };
  30364. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  30365. if (!mesh.rotationQuaternion) {
  30366. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30367. }
  30368. // The delta between the mesh position and the mesh bounding box center
  30369. var bbox = mesh.getBoundingInfo().boundingBox;
  30370. var deltaPosition = mesh.position.subtract(bbox.center);
  30371. var deltaRotation;
  30372. var material = this._addMaterial(options.friction, options.restitution);
  30373. var body = new CANNON.Body({
  30374. mass: options.mass,
  30375. material: material,
  30376. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  30377. });
  30378. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  30379. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  30380. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30381. //-90 DEG in X, precalculated
  30382. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30383. body.quaternion = body.quaternion.mult(tmpQ);
  30384. //Invert! (Precalculated, 90 deg in X)
  30385. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30386. }
  30387. //If it is a heightfield, if should be centered.
  30388. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30389. //calculate the correct body position:
  30390. var rotationQuaternion = mesh.rotationQuaternion;
  30391. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30392. mesh.computeWorldMatrix(true);
  30393. //get original center with no rotation
  30394. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30395. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30396. //rotation is back
  30397. mesh.rotationQuaternion = rotationQuaternion;
  30398. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30399. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30400. mesh.setPivotMatrix(p);
  30401. mesh.computeWorldMatrix(true);
  30402. //calculate the translation
  30403. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30404. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30405. //add it inverted to the delta
  30406. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30407. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30408. mesh.setPivotMatrix(oldPivot);
  30409. mesh.computeWorldMatrix(true);
  30410. }
  30411. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  30412. deltaPosition = BABYLON.Vector3.Zero();
  30413. }
  30414. //add the shape
  30415. body.addShape(shape);
  30416. this._world.add(body);
  30417. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  30418. return body;
  30419. };
  30420. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30421. var initialMesh = parts[0].mesh;
  30422. this.unregisterMesh(initialMesh);
  30423. initialMesh.computeWorldMatrix(true);
  30424. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  30425. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  30426. for (var index = 1; index < parts.length; index++) {
  30427. var mesh = parts[index].mesh;
  30428. mesh.computeWorldMatrix(true);
  30429. var shape = this._createShape(mesh, parts[index].impostor);
  30430. var localPosition = mesh.position;
  30431. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30432. }
  30433. return body;
  30434. };
  30435. CannonJSPlugin.prototype._unbindBody = function (body) {
  30436. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30437. var registeredMesh = this._registeredMeshes[index];
  30438. if (registeredMesh.body === body) {
  30439. this._world.remove(registeredMesh.body);
  30440. registeredMesh.body = null;
  30441. registeredMesh.delta = null;
  30442. registeredMesh.deltaRotation = null;
  30443. }
  30444. }
  30445. };
  30446. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  30447. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30448. var registeredMesh = this._registeredMeshes[index];
  30449. if (registeredMesh.mesh === mesh) {
  30450. // Remove body
  30451. if (registeredMesh.body) {
  30452. this._unbindBody(registeredMesh.body);
  30453. }
  30454. this._registeredMeshes.splice(index, 1);
  30455. return;
  30456. }
  30457. }
  30458. };
  30459. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30460. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30461. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30462. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30463. var registeredMesh = this._registeredMeshes[index];
  30464. if (registeredMesh.mesh === mesh) {
  30465. registeredMesh.body.applyImpulse(impulse, worldPoint);
  30466. return;
  30467. }
  30468. }
  30469. };
  30470. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  30471. var body1 = null, body2 = null;
  30472. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30473. var registeredMesh = this._registeredMeshes[index];
  30474. if (registeredMesh.mesh === mesh1) {
  30475. body1 = registeredMesh.body;
  30476. if (body2)
  30477. break;
  30478. }
  30479. else if (registeredMesh.mesh === mesh2) {
  30480. body2 = registeredMesh.body;
  30481. if (body1)
  30482. break;
  30483. }
  30484. }
  30485. if (!body1 || !body2) {
  30486. return false;
  30487. }
  30488. 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));
  30489. this._world.addConstraint(constraint);
  30490. return true;
  30491. };
  30492. CannonJSPlugin.prototype.dispose = function () {
  30493. while (this._registeredMeshes.length) {
  30494. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30495. }
  30496. };
  30497. CannonJSPlugin.prototype.isSupported = function () {
  30498. return window.CANNON !== undefined;
  30499. };
  30500. CannonJSPlugin.prototype.getWorldObject = function () {
  30501. return this._world;
  30502. };
  30503. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30504. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30505. var registeredMesh = this._registeredMeshes[index];
  30506. if (registeredMesh.mesh === mesh) {
  30507. return registeredMesh.body;
  30508. }
  30509. }
  30510. return null;
  30511. };
  30512. return CannonJSPlugin;
  30513. })();
  30514. BABYLON.CannonJSPlugin = CannonJSPlugin;
  30515. })(BABYLON || (BABYLON = {}));
  30516. var BABYLON;
  30517. (function (BABYLON) {
  30518. var OimoJSPlugin = (function () {
  30519. function OimoJSPlugin() {
  30520. this._registeredMeshes = [];
  30521. this.name = "oimo";
  30522. /**
  30523. * Update the body position according to the mesh position
  30524. * @param mesh
  30525. */
  30526. this.updateBodyPosition = function (mesh) {
  30527. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30528. var registeredMesh = this._registeredMeshes[index];
  30529. var body = registeredMesh.body.body;
  30530. var updated = false;
  30531. var newPosition;
  30532. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30533. mesh.computeWorldMatrix(true);
  30534. newPosition = mesh.getBoundingInfo().boundingBox.center;
  30535. updated = true;
  30536. }
  30537. else if (registeredMesh.mesh.parent === mesh) {
  30538. mesh.computeWorldMatrix(true);
  30539. registeredMesh.mesh.computeWorldMatrix(true);
  30540. newPosition = registeredMesh.mesh.getAbsolutePosition();
  30541. updated = true;
  30542. }
  30543. if (updated) {
  30544. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  30545. body.setQuaternion(mesh.rotationQuaternion);
  30546. body.sleeping = false;
  30547. //force Oimo to update the body's position
  30548. body.updatePosition(1);
  30549. }
  30550. }
  30551. };
  30552. }
  30553. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  30554. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30555. };
  30556. OimoJSPlugin.prototype.initialize = function (iterations) {
  30557. this._world = new OIMO.World(null, null, iterations);
  30558. this._world.clear();
  30559. };
  30560. OimoJSPlugin.prototype.setGravity = function (gravity) {
  30561. this._gravity = this._world.gravity = gravity;
  30562. };
  30563. OimoJSPlugin.prototype.getGravity = function () {
  30564. return this._gravity;
  30565. };
  30566. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30567. this.unregisterMesh(mesh);
  30568. if (!mesh.rotationQuaternion) {
  30569. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30570. }
  30571. mesh.computeWorldMatrix(true);
  30572. var bbox = mesh.getBoundingInfo().boundingBox;
  30573. // The delta between the mesh position and the mesh bounding box center
  30574. var deltaPosition = mesh.position.subtract(bbox.center);
  30575. //calculate rotation to fit Oimo's needs (Euler...)
  30576. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30577. //get the correct bounding box
  30578. var oldQuaternion = mesh.rotationQuaternion;
  30579. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30580. mesh.computeWorldMatrix(true);
  30581. var bodyConfig = {
  30582. name: mesh.uniqueId,
  30583. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  30584. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  30585. move: options.mass != 0,
  30586. config: [options.mass, options.friction, options.restitution],
  30587. world: this._world
  30588. };
  30589. // register mesh
  30590. switch (impostor) {
  30591. case BABYLON.PhysicsEngine.SphereImpostor:
  30592. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30593. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30594. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30595. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30596. bodyConfig.type = 'sphere';
  30597. bodyConfig.size = [size];
  30598. break;
  30599. case BABYLON.PhysicsEngine.PlaneImpostor:
  30600. //Oimo "fakes" a cylinder as a box, so why don't we!
  30601. case BABYLON.PhysicsEngine.CylinderImpostor:
  30602. case BABYLON.PhysicsEngine.BoxImpostor:
  30603. var min = bbox.minimumWorld;
  30604. var max = bbox.maximumWorld;
  30605. var box = max.subtract(min);
  30606. var sizeX = this._checkWithEpsilon(box.x);
  30607. var sizeY = this._checkWithEpsilon(box.y);
  30608. var sizeZ = this._checkWithEpsilon(box.z);
  30609. bodyConfig.type = 'box';
  30610. bodyConfig.size = [sizeX, sizeY, sizeZ];
  30611. break;
  30612. }
  30613. var body = new OIMO.Body(bodyConfig);
  30614. //We have to access the rigid body's properties to set the quaternion.
  30615. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  30616. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  30617. //TEST
  30618. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  30619. //update the internal rotation matrix
  30620. //body.body.syncShapes();
  30621. this._registeredMeshes.push({
  30622. mesh: mesh,
  30623. body: body,
  30624. delta: deltaPosition
  30625. });
  30626. //for the sake of consistency.
  30627. mesh.rotationQuaternion = oldQuaternion;
  30628. return body;
  30629. };
  30630. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30631. var types = [], sizes = [], positions = [], rotations = [];
  30632. var initialMesh = parts[0].mesh;
  30633. for (var index = 0; index < parts.length; index++) {
  30634. var part = parts[index];
  30635. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  30636. types.push(bodyParameters.type);
  30637. sizes.push.apply(sizes, bodyParameters.size);
  30638. positions.push.apply(positions, bodyParameters.pos);
  30639. rotations.push.apply(rotations, bodyParameters.rot);
  30640. }
  30641. var body = new OIMO.Body({
  30642. name: initialMesh.uniqueId,
  30643. type: types,
  30644. size: sizes,
  30645. pos: positions,
  30646. rot: rotations,
  30647. move: options.mass != 0,
  30648. config: [options.mass, options.friction, options.restitution],
  30649. world: this._world
  30650. });
  30651. //Reset the body's rotation to be of the initial mesh's.
  30652. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  30653. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  30654. this._registeredMeshes.push({
  30655. mesh: initialMesh,
  30656. body: body
  30657. });
  30658. return body;
  30659. };
  30660. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  30661. var mesh = part.mesh;
  30662. if (!mesh.rotationQuaternion) {
  30663. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30664. }
  30665. // We need the bounding box/sphere info to compute the physics body
  30666. mesh.computeWorldMatrix(true);
  30667. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30668. var bodyParameters = {
  30669. name: mesh.uniqueId,
  30670. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  30671. //A bug in Oimo (Body class) prevents us from using rot directly.
  30672. rot: [0, 0, 0],
  30673. //For future reference, if the bug will ever be fixed.
  30674. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  30675. };
  30676. var oldQuaternion = mesh.rotationQuaternion;
  30677. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30678. mesh.computeWorldMatrix(true);
  30679. switch (part.impostor) {
  30680. case BABYLON.PhysicsEngine.SphereImpostor:
  30681. var bbox = mesh.getBoundingInfo().boundingBox;
  30682. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30683. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30684. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30685. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30686. bodyParameters.type = 'sphere';
  30687. bodyParameters.size = [size, size, size];
  30688. break;
  30689. case BABYLON.PhysicsEngine.PlaneImpostor:
  30690. case BABYLON.PhysicsEngine.CylinderImpostor:
  30691. case BABYLON.PhysicsEngine.BoxImpostor:
  30692. bbox = mesh.getBoundingInfo().boundingBox;
  30693. var min = bbox.minimumWorld;
  30694. var max = bbox.maximumWorld;
  30695. var box = max.subtract(min);
  30696. var sizeX = this._checkWithEpsilon(box.x);
  30697. var sizeY = this._checkWithEpsilon(box.y);
  30698. var sizeZ = this._checkWithEpsilon(box.z);
  30699. bodyParameters.type = 'box';
  30700. bodyParameters.size = [sizeX, sizeY, sizeZ];
  30701. break;
  30702. }
  30703. mesh.rotationQuaternion = oldQuaternion;
  30704. return bodyParameters;
  30705. };
  30706. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  30707. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30708. var registeredMesh = this._registeredMeshes[index];
  30709. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30710. if (registeredMesh.body) {
  30711. this._world.removeRigidBody(registeredMesh.body.body);
  30712. this._unbindBody(registeredMesh.body);
  30713. }
  30714. this._registeredMeshes.splice(index, 1);
  30715. return;
  30716. }
  30717. }
  30718. };
  30719. OimoJSPlugin.prototype._unbindBody = function (body) {
  30720. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30721. var registeredMesh = this._registeredMeshes[index];
  30722. if (registeredMesh.body === body) {
  30723. registeredMesh.body = null;
  30724. }
  30725. }
  30726. };
  30727. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30728. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30729. var registeredMesh = this._registeredMeshes[index];
  30730. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30731. // Get object mass to have a behaviour similar to cannon.js
  30732. var mass = registeredMesh.body.body.massInfo.mass;
  30733. // The force is scaled with the mass of object
  30734. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  30735. return;
  30736. }
  30737. }
  30738. };
  30739. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  30740. var body1 = null, body2 = null;
  30741. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30742. var registeredMesh = this._registeredMeshes[index];
  30743. if (registeredMesh.mesh === mesh1) {
  30744. body1 = registeredMesh.body.body;
  30745. }
  30746. else if (registeredMesh.mesh === mesh2) {
  30747. body2 = registeredMesh.body.body;
  30748. }
  30749. }
  30750. if (!body1 || !body2) {
  30751. return false;
  30752. }
  30753. if (!options) {
  30754. options = {};
  30755. }
  30756. new OIMO.Link({
  30757. type: options.type,
  30758. body1: body1,
  30759. body2: body2,
  30760. min: options.min,
  30761. max: options.max,
  30762. axe1: options.axe1,
  30763. axe2: options.axe2,
  30764. pos1: [pivot1.x, pivot1.y, pivot1.z],
  30765. pos2: [pivot2.x, pivot2.y, pivot2.z],
  30766. collision: options.collision,
  30767. spring: options.spring,
  30768. world: this._world
  30769. });
  30770. return true;
  30771. };
  30772. OimoJSPlugin.prototype.dispose = function () {
  30773. this._world.clear();
  30774. while (this._registeredMeshes.length) {
  30775. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30776. }
  30777. };
  30778. OimoJSPlugin.prototype.isSupported = function () {
  30779. return OIMO !== undefined;
  30780. };
  30781. OimoJSPlugin.prototype.getWorldObject = function () {
  30782. return this._world;
  30783. };
  30784. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30785. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30786. var registeredMesh = this._registeredMeshes[index];
  30787. if (registeredMesh.mesh === mesh) {
  30788. return registeredMesh.body;
  30789. }
  30790. }
  30791. return null;
  30792. };
  30793. OimoJSPlugin.prototype._getLastShape = function (body) {
  30794. var lastShape = body.shapes;
  30795. while (lastShape.next) {
  30796. lastShape = lastShape.next;
  30797. }
  30798. return lastShape;
  30799. };
  30800. OimoJSPlugin.prototype.runOneStep = function (time) {
  30801. this._world.step();
  30802. // Update the position of all registered meshes
  30803. var i = this._registeredMeshes.length;
  30804. var m;
  30805. while (i--) {
  30806. var body = this._registeredMeshes[i].body.body;
  30807. var mesh = this._registeredMeshes[i].mesh;
  30808. if (!this._registeredMeshes[i].delta) {
  30809. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  30810. }
  30811. if (!body.sleeping) {
  30812. //TODO check that
  30813. if (body.shapes.next) {
  30814. var parentShape = this._getLastShape(body);
  30815. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  30816. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  30817. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  30818. }
  30819. else {
  30820. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  30821. }
  30822. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  30823. mesh.computeWorldMatrix();
  30824. }
  30825. //check if the collide callback is set.
  30826. if (mesh.onPhysicsCollide) {
  30827. var meshUniqueName = mesh.uniqueId;
  30828. var contact = this._world.contacts;
  30829. while (contact !== null) {
  30830. //is this body colliding with any other?
  30831. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30832. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  30833. //get the mesh and execute the callback
  30834. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  30835. if (otherMesh)
  30836. mesh.onPhysicsCollide(otherMesh, contact);
  30837. }
  30838. contact = contact.next;
  30839. }
  30840. }
  30841. }
  30842. };
  30843. return OimoJSPlugin;
  30844. })();
  30845. BABYLON.OimoJSPlugin = OimoJSPlugin;
  30846. })(BABYLON || (BABYLON = {}));
  30847. var BABYLON;
  30848. (function (BABYLON) {
  30849. var DisplayPassPostProcess = (function (_super) {
  30850. __extends(DisplayPassPostProcess, _super);
  30851. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30852. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  30853. }
  30854. return DisplayPassPostProcess;
  30855. })(BABYLON.PostProcess);
  30856. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  30857. })(BABYLON || (BABYLON = {}));
  30858. var BABYLON;
  30859. (function (BABYLON) {
  30860. var SimplificationSettings = (function () {
  30861. function SimplificationSettings(quality, distance, optimizeMesh) {
  30862. this.quality = quality;
  30863. this.distance = distance;
  30864. this.optimizeMesh = optimizeMesh;
  30865. }
  30866. return SimplificationSettings;
  30867. })();
  30868. BABYLON.SimplificationSettings = SimplificationSettings;
  30869. var SimplificationQueue = (function () {
  30870. function SimplificationQueue() {
  30871. this.running = false;
  30872. this._simplificationArray = [];
  30873. }
  30874. SimplificationQueue.prototype.addTask = function (task) {
  30875. this._simplificationArray.push(task);
  30876. };
  30877. SimplificationQueue.prototype.executeNext = function () {
  30878. var task = this._simplificationArray.pop();
  30879. if (task) {
  30880. this.running = true;
  30881. this.runSimplification(task);
  30882. }
  30883. else {
  30884. this.running = false;
  30885. }
  30886. };
  30887. SimplificationQueue.prototype.runSimplification = function (task) {
  30888. var _this = this;
  30889. if (task.parallelProcessing) {
  30890. //parallel simplifier
  30891. task.settings.forEach(function (setting) {
  30892. var simplifier = _this.getSimplifier(task);
  30893. simplifier.simplify(setting, function (newMesh) {
  30894. task.mesh.addLODLevel(setting.distance, newMesh);
  30895. newMesh.isVisible = true;
  30896. //check if it is the last
  30897. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30898. //all done, run the success callback.
  30899. task.successCallback();
  30900. }
  30901. _this.executeNext();
  30902. });
  30903. });
  30904. }
  30905. else {
  30906. //single simplifier.
  30907. var simplifier = this.getSimplifier(task);
  30908. var runDecimation = function (setting, callback) {
  30909. simplifier.simplify(setting, function (newMesh) {
  30910. task.mesh.addLODLevel(setting.distance, newMesh);
  30911. newMesh.isVisible = true;
  30912. //run the next quality level
  30913. callback();
  30914. });
  30915. };
  30916. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30917. runDecimation(task.settings[loop.index], function () {
  30918. loop.executeNext();
  30919. });
  30920. }, function () {
  30921. //execution ended, run the success callback.
  30922. if (task.successCallback) {
  30923. task.successCallback();
  30924. }
  30925. _this.executeNext();
  30926. });
  30927. }
  30928. };
  30929. SimplificationQueue.prototype.getSimplifier = function (task) {
  30930. switch (task.simplificationType) {
  30931. case SimplificationType.QUADRATIC:
  30932. default:
  30933. return new QuadraticErrorSimplification(task.mesh);
  30934. }
  30935. };
  30936. return SimplificationQueue;
  30937. })();
  30938. BABYLON.SimplificationQueue = SimplificationQueue;
  30939. /**
  30940. * The implemented types of simplification.
  30941. * At the moment only Quadratic Error Decimation is implemented.
  30942. */
  30943. (function (SimplificationType) {
  30944. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30945. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30946. var SimplificationType = BABYLON.SimplificationType;
  30947. var DecimationTriangle = (function () {
  30948. function DecimationTriangle(vertices) {
  30949. this.vertices = vertices;
  30950. this.error = new Array(4);
  30951. this.deleted = false;
  30952. this.isDirty = false;
  30953. this.deletePending = false;
  30954. this.borderFactor = 0;
  30955. }
  30956. return DecimationTriangle;
  30957. })();
  30958. BABYLON.DecimationTriangle = DecimationTriangle;
  30959. var DecimationVertex = (function () {
  30960. function DecimationVertex(position, id) {
  30961. this.position = position;
  30962. this.id = id;
  30963. this.isBorder = true;
  30964. this.q = new QuadraticMatrix();
  30965. this.triangleCount = 0;
  30966. this.triangleStart = 0;
  30967. this.originalOffsets = [];
  30968. }
  30969. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30970. this.position.copyFrom(newPosition);
  30971. };
  30972. return DecimationVertex;
  30973. })();
  30974. BABYLON.DecimationVertex = DecimationVertex;
  30975. var QuadraticMatrix = (function () {
  30976. function QuadraticMatrix(data) {
  30977. this.data = new Array(10);
  30978. for (var i = 0; i < 10; ++i) {
  30979. if (data && data[i]) {
  30980. this.data[i] = data[i];
  30981. }
  30982. else {
  30983. this.data[i] = 0;
  30984. }
  30985. }
  30986. }
  30987. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30988. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30989. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30990. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30991. return det;
  30992. };
  30993. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30994. for (var i = 0; i < 10; ++i) {
  30995. this.data[i] += matrix.data[i];
  30996. }
  30997. };
  30998. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30999. for (var i = 0; i < 10; ++i) {
  31000. this.data[i] += data[i];
  31001. }
  31002. };
  31003. QuadraticMatrix.prototype.add = function (matrix) {
  31004. var m = new QuadraticMatrix();
  31005. for (var i = 0; i < 10; ++i) {
  31006. m.data[i] = this.data[i] + matrix.data[i];
  31007. }
  31008. return m;
  31009. };
  31010. QuadraticMatrix.FromData = function (a, b, c, d) {
  31011. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31012. };
  31013. //returning an array to avoid garbage collection
  31014. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31015. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31016. };
  31017. return QuadraticMatrix;
  31018. })();
  31019. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31020. var Reference = (function () {
  31021. function Reference(vertexId, triangleId) {
  31022. this.vertexId = vertexId;
  31023. this.triangleId = triangleId;
  31024. }
  31025. return Reference;
  31026. })();
  31027. BABYLON.Reference = Reference;
  31028. /**
  31029. * An implementation of the Quadratic Error simplification algorithm.
  31030. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31031. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31032. * @author RaananW
  31033. */
  31034. var QuadraticErrorSimplification = (function () {
  31035. function QuadraticErrorSimplification(_mesh) {
  31036. this._mesh = _mesh;
  31037. this.initialized = false;
  31038. this.syncIterations = 5000;
  31039. this.aggressiveness = 7;
  31040. this.decimationIterations = 100;
  31041. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31042. }
  31043. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31044. var _this = this;
  31045. this.initDecimatedMesh();
  31046. //iterating through the submeshes array, one after the other.
  31047. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31048. _this.initWithMesh(loop.index, function () {
  31049. _this.runDecimation(settings, loop.index, function () {
  31050. loop.executeNext();
  31051. });
  31052. }, settings.optimizeMesh);
  31053. }, function () {
  31054. setTimeout(function () {
  31055. successCallback(_this._reconstructedMesh);
  31056. }, 0);
  31057. });
  31058. };
  31059. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31060. var _this = this;
  31061. var gCount = 0;
  31062. triangle.vertices.forEach(function (vertex) {
  31063. var count = 0;
  31064. var vPos = vertex.position;
  31065. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31066. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31067. ++count;
  31068. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31069. ++count;
  31070. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31071. ++count;
  31072. if (count > 1) {
  31073. ++gCount;
  31074. }
  31075. ;
  31076. });
  31077. if (gCount > 1) {
  31078. console.log(triangle, gCount);
  31079. }
  31080. return gCount > 1;
  31081. };
  31082. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31083. var _this = this;
  31084. var targetCount = ~~(this.triangles.length * settings.quality);
  31085. var deletedTriangles = 0;
  31086. var triangleCount = this.triangles.length;
  31087. var iterationFunction = function (iteration, callback) {
  31088. setTimeout(function () {
  31089. if (iteration % 5 === 0) {
  31090. _this.updateMesh(iteration === 0);
  31091. }
  31092. for (var i = 0; i < _this.triangles.length; ++i) {
  31093. _this.triangles[i].isDirty = false;
  31094. }
  31095. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31096. var trianglesIterator = function (i) {
  31097. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31098. var t = _this.triangles[tIdx];
  31099. if (!t)
  31100. return;
  31101. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31102. return;
  31103. }
  31104. for (var j = 0; j < 3; ++j) {
  31105. if (t.error[j] < threshold) {
  31106. var deleted0 = [];
  31107. var deleted1 = [];
  31108. var v0 = t.vertices[j];
  31109. var v1 = t.vertices[(j + 1) % 3];
  31110. if (v0.isBorder !== v1.isBorder)
  31111. continue;
  31112. var p = BABYLON.Vector3.Zero();
  31113. var n = BABYLON.Vector3.Zero();
  31114. var uv = BABYLON.Vector2.Zero();
  31115. var color = new BABYLON.Color4(0, 0, 0, 1);
  31116. _this.calculateError(v0, v1, p, n, uv, color);
  31117. var delTr = [];
  31118. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31119. continue;
  31120. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31121. continue;
  31122. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31123. continue;
  31124. var uniqueArray = [];
  31125. delTr.forEach(function (deletedT) {
  31126. if (uniqueArray.indexOf(deletedT) === -1) {
  31127. deletedT.deletePending = true;
  31128. uniqueArray.push(deletedT);
  31129. }
  31130. });
  31131. if (uniqueArray.length % 2 !== 0) {
  31132. continue;
  31133. }
  31134. v0.q = v1.q.add(v0.q);
  31135. v0.updatePosition(p);
  31136. var tStart = _this.references.length;
  31137. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31138. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31139. var tCount = _this.references.length - tStart;
  31140. if (tCount <= v0.triangleCount) {
  31141. if (tCount) {
  31142. for (var c = 0; c < tCount; c++) {
  31143. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31144. }
  31145. }
  31146. }
  31147. else {
  31148. v0.triangleStart = tStart;
  31149. }
  31150. v0.triangleCount = tCount;
  31151. break;
  31152. }
  31153. }
  31154. };
  31155. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31156. }, 0);
  31157. };
  31158. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31159. if (triangleCount - deletedTriangles <= targetCount)
  31160. loop.breakLoop();
  31161. else {
  31162. iterationFunction(loop.index, function () {
  31163. loop.executeNext();
  31164. });
  31165. }
  31166. }, function () {
  31167. setTimeout(function () {
  31168. //reconstruct this part of the mesh
  31169. _this.reconstructMesh(submeshIndex);
  31170. successCallback();
  31171. }, 0);
  31172. });
  31173. };
  31174. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31175. var _this = this;
  31176. this.vertices = [];
  31177. this.triangles = [];
  31178. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31179. var indices = this._mesh.getIndices();
  31180. var submesh = this._mesh.subMeshes[submeshIndex];
  31181. var findInVertices = function (positionToSearch) {
  31182. if (optimizeMesh) {
  31183. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31184. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31185. return _this.vertices[ii];
  31186. }
  31187. }
  31188. }
  31189. return null;
  31190. };
  31191. var vertexReferences = [];
  31192. var vertexInit = function (i) {
  31193. var offset = i + submesh.verticesStart;
  31194. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31195. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31196. vertex.originalOffsets.push(offset);
  31197. if (vertex.id === _this.vertices.length) {
  31198. _this.vertices.push(vertex);
  31199. }
  31200. vertexReferences.push(vertex.id);
  31201. };
  31202. //var totalVertices = mesh.getTotalVertices();
  31203. var totalVertices = submesh.verticesCount;
  31204. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31205. var indicesInit = function (i) {
  31206. var offset = (submesh.indexStart / 3) + i;
  31207. var pos = (offset * 3);
  31208. var i0 = indices[pos + 0];
  31209. var i1 = indices[pos + 1];
  31210. var i2 = indices[pos + 2];
  31211. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31212. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31213. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31214. var triangle = new DecimationTriangle([v0, v1, v2]);
  31215. triangle.originalOffset = pos;
  31216. _this.triangles.push(triangle);
  31217. };
  31218. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31219. _this.init(callback);
  31220. });
  31221. });
  31222. };
  31223. QuadraticErrorSimplification.prototype.init = function (callback) {
  31224. var _this = this;
  31225. var triangleInit1 = function (i) {
  31226. var t = _this.triangles[i];
  31227. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31228. for (var j = 0; j < 3; j++) {
  31229. 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))));
  31230. }
  31231. };
  31232. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31233. var triangleInit2 = function (i) {
  31234. var t = _this.triangles[i];
  31235. for (var j = 0; j < 3; ++j) {
  31236. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31237. }
  31238. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31239. };
  31240. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31241. _this.initialized = true;
  31242. callback();
  31243. });
  31244. });
  31245. };
  31246. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31247. var newTriangles = [];
  31248. var i;
  31249. for (i = 0; i < this.vertices.length; ++i) {
  31250. this.vertices[i].triangleCount = 0;
  31251. }
  31252. var t;
  31253. var j;
  31254. for (i = 0; i < this.triangles.length; ++i) {
  31255. if (!this.triangles[i].deleted) {
  31256. t = this.triangles[i];
  31257. for (j = 0; j < 3; ++j) {
  31258. t.vertices[j].triangleCount = 1;
  31259. }
  31260. newTriangles.push(t);
  31261. }
  31262. }
  31263. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31264. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31265. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31266. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31267. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31268. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31269. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31270. var vertexCount = 0;
  31271. for (i = 0; i < this.vertices.length; ++i) {
  31272. var vertex = this.vertices[i];
  31273. vertex.id = vertexCount;
  31274. if (vertex.triangleCount) {
  31275. vertex.originalOffsets.forEach(function (originalOffset) {
  31276. newPositionData.push(vertex.position.x);
  31277. newPositionData.push(vertex.position.y);
  31278. newPositionData.push(vertex.position.z);
  31279. newNormalData.push(normalData[originalOffset * 3]);
  31280. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31281. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31282. if (uvs && uvs.length) {
  31283. newUVsData.push(uvs[(originalOffset * 2)]);
  31284. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31285. }
  31286. else if (colorsData && colorsData.length) {
  31287. newColorsData.push(colorsData[(originalOffset * 4)]);
  31288. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31289. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31290. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31291. }
  31292. ++vertexCount;
  31293. });
  31294. }
  31295. }
  31296. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31297. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31298. var submeshesArray = this._reconstructedMesh.subMeshes;
  31299. this._reconstructedMesh.subMeshes = [];
  31300. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31301. var originalIndices = this._mesh.getIndices();
  31302. for (i = 0; i < newTriangles.length; ++i) {
  31303. t = newTriangles[i]; //now get the new referencing point for each vertex
  31304. [0, 1, 2].forEach(function (idx) {
  31305. var id = originalIndices[t.originalOffset + idx];
  31306. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31307. if (offset < 0)
  31308. offset = 0;
  31309. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31310. });
  31311. }
  31312. //overwriting the old vertex buffers and indices.
  31313. this._reconstructedMesh.setIndices(newIndicesArray);
  31314. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31315. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31316. if (newUVsData.length > 0)
  31317. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31318. if (newColorsData.length > 0)
  31319. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31320. //create submesh
  31321. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31322. if (submeshIndex > 0) {
  31323. this._reconstructedMesh.subMeshes = [];
  31324. submeshesArray.forEach(function (submesh) {
  31325. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31326. });
  31327. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31328. }
  31329. };
  31330. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31331. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31332. this._reconstructedMesh.material = this._mesh.material;
  31333. this._reconstructedMesh.parent = this._mesh.parent;
  31334. this._reconstructedMesh.isVisible = false;
  31335. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31336. };
  31337. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31338. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31339. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31340. if (t.deleted)
  31341. continue;
  31342. var s = this.references[vertex1.triangleStart + i].vertexId;
  31343. var v1 = t.vertices[(s + 1) % 3];
  31344. var v2 = t.vertices[(s + 2) % 3];
  31345. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31346. deletedArray[i] = true;
  31347. delTr.push(t);
  31348. continue;
  31349. }
  31350. var d1 = v1.position.subtract(point);
  31351. d1 = d1.normalize();
  31352. var d2 = v2.position.subtract(point);
  31353. d2 = d2.normalize();
  31354. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31355. return true;
  31356. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31357. deletedArray[i] = false;
  31358. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31359. return true;
  31360. }
  31361. return false;
  31362. };
  31363. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31364. var newDeleted = deletedTriangles;
  31365. for (var i = 0; i < vertex.triangleCount; ++i) {
  31366. var ref = this.references[vertex.triangleStart + i];
  31367. var t = this.triangles[ref.triangleId];
  31368. if (t.deleted)
  31369. continue;
  31370. if (deletedArray[i] && t.deletePending) {
  31371. t.deleted = true;
  31372. newDeleted++;
  31373. continue;
  31374. }
  31375. t.vertices[ref.vertexId] = origVertex;
  31376. t.isDirty = true;
  31377. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31378. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31379. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31380. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31381. this.references.push(ref);
  31382. }
  31383. return newDeleted;
  31384. };
  31385. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31386. for (var i = 0; i < this.vertices.length; ++i) {
  31387. var vCount = [];
  31388. var vId = [];
  31389. var v = this.vertices[i];
  31390. var j;
  31391. for (j = 0; j < v.triangleCount; ++j) {
  31392. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31393. for (var ii = 0; ii < 3; ii++) {
  31394. var ofs = 0;
  31395. var vv = triangle.vertices[ii];
  31396. while (ofs < vCount.length) {
  31397. if (vId[ofs] === vv.id)
  31398. break;
  31399. ++ofs;
  31400. }
  31401. if (ofs === vCount.length) {
  31402. vCount.push(1);
  31403. vId.push(vv.id);
  31404. }
  31405. else {
  31406. vCount[ofs]++;
  31407. }
  31408. }
  31409. }
  31410. for (j = 0; j < vCount.length; ++j) {
  31411. if (vCount[j] === 1) {
  31412. this.vertices[vId[j]].isBorder = true;
  31413. }
  31414. else {
  31415. this.vertices[vId[j]].isBorder = false;
  31416. }
  31417. }
  31418. }
  31419. };
  31420. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31421. if (identifyBorders === void 0) { identifyBorders = false; }
  31422. var i;
  31423. if (!identifyBorders) {
  31424. var newTrianglesVector = [];
  31425. for (i = 0; i < this.triangles.length; ++i) {
  31426. if (!this.triangles[i].deleted) {
  31427. newTrianglesVector.push(this.triangles[i]);
  31428. }
  31429. }
  31430. this.triangles = newTrianglesVector;
  31431. }
  31432. for (i = 0; i < this.vertices.length; ++i) {
  31433. this.vertices[i].triangleCount = 0;
  31434. this.vertices[i].triangleStart = 0;
  31435. }
  31436. var t;
  31437. var j;
  31438. var v;
  31439. for (i = 0; i < this.triangles.length; ++i) {
  31440. t = this.triangles[i];
  31441. for (j = 0; j < 3; ++j) {
  31442. v = t.vertices[j];
  31443. v.triangleCount++;
  31444. }
  31445. }
  31446. var tStart = 0;
  31447. for (i = 0; i < this.vertices.length; ++i) {
  31448. this.vertices[i].triangleStart = tStart;
  31449. tStart += this.vertices[i].triangleCount;
  31450. this.vertices[i].triangleCount = 0;
  31451. }
  31452. var newReferences = new Array(this.triangles.length * 3);
  31453. for (i = 0; i < this.triangles.length; ++i) {
  31454. t = this.triangles[i];
  31455. for (j = 0; j < 3; ++j) {
  31456. v = t.vertices[j];
  31457. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31458. v.triangleCount++;
  31459. }
  31460. }
  31461. this.references = newReferences;
  31462. if (identifyBorders) {
  31463. this.identifyBorder();
  31464. }
  31465. };
  31466. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31467. var x = point.x;
  31468. var y = point.y;
  31469. var z = point.z;
  31470. 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
  31471. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31472. };
  31473. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31474. var q = vertex1.q.add(vertex2.q);
  31475. var border = vertex1.isBorder && vertex2.isBorder;
  31476. var error = 0;
  31477. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31478. if (qDet !== 0 && !border) {
  31479. if (!pointResult) {
  31480. pointResult = BABYLON.Vector3.Zero();
  31481. }
  31482. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31483. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31484. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31485. error = this.vertexError(q, pointResult);
  31486. }
  31487. else {
  31488. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31489. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31490. var error1 = this.vertexError(q, vertex1.position);
  31491. var error2 = this.vertexError(q, vertex2.position);
  31492. var error3 = this.vertexError(q, p3);
  31493. error = Math.min(error1, error2, error3);
  31494. if (error === error1) {
  31495. if (pointResult) {
  31496. pointResult.copyFrom(vertex1.position);
  31497. }
  31498. }
  31499. else if (error === error2) {
  31500. if (pointResult) {
  31501. pointResult.copyFrom(vertex2.position);
  31502. }
  31503. }
  31504. else {
  31505. if (pointResult) {
  31506. pointResult.copyFrom(p3);
  31507. }
  31508. }
  31509. }
  31510. return error;
  31511. };
  31512. return QuadraticErrorSimplification;
  31513. })();
  31514. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31515. })(BABYLON || (BABYLON = {}));
  31516. var BABYLON;
  31517. (function (BABYLON) {
  31518. var serializedGeometries = [];
  31519. var serializeGeometry = function (geometry, serializationGeometries) {
  31520. if (serializedGeometries[geometry.id]) {
  31521. return;
  31522. }
  31523. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31524. serializationGeometries.boxes.push(geometry.serialize());
  31525. }
  31526. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31527. serializationGeometries.spheres.push(geometry.serialize());
  31528. }
  31529. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31530. serializationGeometries.cylinders.push(geometry.serialize());
  31531. }
  31532. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31533. serializationGeometries.toruses.push(geometry.serialize());
  31534. }
  31535. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31536. serializationGeometries.grounds.push(geometry.serialize());
  31537. }
  31538. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  31539. serializationGeometries.planes.push(geometry.serialize());
  31540. }
  31541. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  31542. serializationGeometries.torusKnots.push(geometry.serialize());
  31543. }
  31544. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  31545. throw new Error("Unknown primitive type");
  31546. }
  31547. else {
  31548. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  31549. }
  31550. serializedGeometries[geometry.id] = true;
  31551. };
  31552. var serializeMesh = function (mesh, serializationScene) {
  31553. var serializationObject = {};
  31554. serializationObject.name = mesh.name;
  31555. serializationObject.id = mesh.id;
  31556. if (BABYLON.Tags.HasTags(mesh)) {
  31557. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  31558. }
  31559. serializationObject.position = mesh.position.asArray();
  31560. if (mesh.rotationQuaternion) {
  31561. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  31562. }
  31563. else if (mesh.rotation) {
  31564. serializationObject.rotation = mesh.rotation.asArray();
  31565. }
  31566. serializationObject.scaling = mesh.scaling.asArray();
  31567. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  31568. serializationObject.isEnabled = mesh.isEnabled();
  31569. serializationObject.isVisible = mesh.isVisible;
  31570. serializationObject.infiniteDistance = mesh.infiniteDistance;
  31571. serializationObject.pickable = mesh.isPickable;
  31572. serializationObject.receiveShadows = mesh.receiveShadows;
  31573. serializationObject.billboardMode = mesh.billboardMode;
  31574. serializationObject.visibility = mesh.visibility;
  31575. serializationObject.checkCollisions = mesh.checkCollisions;
  31576. // Parent
  31577. if (mesh.parent) {
  31578. serializationObject.parentId = mesh.parent.id;
  31579. }
  31580. // Geometry
  31581. var geometry = mesh._geometry;
  31582. if (geometry) {
  31583. var geometryId = geometry.id;
  31584. serializationObject.geometryId = geometryId;
  31585. if (!mesh.getScene().getGeometryByID(geometryId)) {
  31586. // 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
  31587. serializeGeometry(geometry, serializationScene.geometries);
  31588. }
  31589. // SubMeshes
  31590. serializationObject.subMeshes = [];
  31591. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31592. var subMesh = mesh.subMeshes[subIndex];
  31593. serializationObject.subMeshes.push({
  31594. materialIndex: subMesh.materialIndex,
  31595. verticesStart: subMesh.verticesStart,
  31596. verticesCount: subMesh.verticesCount,
  31597. indexStart: subMesh.indexStart,
  31598. indexCount: subMesh.indexCount
  31599. });
  31600. }
  31601. }
  31602. // Material
  31603. if (mesh.material) {
  31604. serializationObject.materialId = mesh.material.id;
  31605. }
  31606. else {
  31607. mesh.material = null;
  31608. }
  31609. // Skeleton
  31610. if (mesh.skeleton) {
  31611. serializationObject.skeletonId = mesh.skeleton.id;
  31612. }
  31613. // Physics
  31614. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  31615. serializationObject.physicsMass = mesh.getPhysicsMass();
  31616. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  31617. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  31618. switch (mesh.getPhysicsImpostor()) {
  31619. case BABYLON.PhysicsEngine.BoxImpostor:
  31620. serializationObject.physicsImpostor = 1;
  31621. break;
  31622. case BABYLON.PhysicsEngine.SphereImpostor:
  31623. serializationObject.physicsImpostor = 2;
  31624. break;
  31625. }
  31626. }
  31627. // Instances
  31628. serializationObject.instances = [];
  31629. for (var index = 0; index < mesh.instances.length; index++) {
  31630. var instance = mesh.instances[index];
  31631. var serializationInstance = {
  31632. name: instance.name,
  31633. position: instance.position.asArray(),
  31634. scaling: instance.scaling.asArray()
  31635. };
  31636. if (instance.rotationQuaternion) {
  31637. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31638. }
  31639. else if (instance.rotation) {
  31640. serializationInstance.rotation = instance.rotation.asArray();
  31641. }
  31642. serializationObject.instances.push(serializationInstance);
  31643. // Animations
  31644. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31645. serializationInstance.ranges = instance.serializeAnimationRanges();
  31646. }
  31647. // Animations
  31648. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  31649. serializationObject.ranges = mesh.serializeAnimationRanges();
  31650. // Layer mask
  31651. serializationObject.layerMask = mesh.layerMask;
  31652. return serializationObject;
  31653. };
  31654. var finalizeSingleMesh = function (mesh, serializationObject) {
  31655. //only works if the mesh is already loaded
  31656. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31657. //serialize material
  31658. if (mesh.material) {
  31659. if (mesh.material instanceof BABYLON.StandardMaterial) {
  31660. serializationObject.materials = serializationObject.materials || [];
  31661. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31662. serializationObject.materials.push(mesh.material.serialize());
  31663. }
  31664. }
  31665. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  31666. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  31667. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31668. serializationObject.multiMaterials.push(mesh.material.serialize());
  31669. }
  31670. }
  31671. }
  31672. //serialize geometry
  31673. var geometry = mesh._geometry;
  31674. if (geometry) {
  31675. if (!serializationObject.geometries) {
  31676. serializationObject.geometries = {};
  31677. serializationObject.geometries.boxes = [];
  31678. serializationObject.geometries.spheres = [];
  31679. serializationObject.geometries.cylinders = [];
  31680. serializationObject.geometries.toruses = [];
  31681. serializationObject.geometries.grounds = [];
  31682. serializationObject.geometries.planes = [];
  31683. serializationObject.geometries.torusKnots = [];
  31684. serializationObject.geometries.vertexData = [];
  31685. }
  31686. serializeGeometry(geometry, serializationObject.geometries);
  31687. }
  31688. // Skeletons
  31689. if (mesh.skeleton) {
  31690. serializationObject.skeletons = serializationObject.skeletons || [];
  31691. serializationObject.skeletons.push(mesh.skeleton.serialize());
  31692. }
  31693. //serialize the actual mesh
  31694. serializationObject.meshes = serializationObject.meshes || [];
  31695. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31696. }
  31697. };
  31698. var SceneSerializer = (function () {
  31699. function SceneSerializer() {
  31700. }
  31701. SceneSerializer.ClearCache = function () {
  31702. serializedGeometries = [];
  31703. };
  31704. SceneSerializer.Serialize = function (scene) {
  31705. var serializationObject = {};
  31706. // Scene
  31707. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  31708. serializationObject.autoClear = scene.autoClear;
  31709. serializationObject.clearColor = scene.clearColor.asArray();
  31710. serializationObject.ambientColor = scene.ambientColor.asArray();
  31711. serializationObject.gravity = scene.gravity.asArray();
  31712. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  31713. serializationObject.workerCollisions = scene.workerCollisions;
  31714. // Fog
  31715. if (scene.fogMode && scene.fogMode !== 0) {
  31716. serializationObject.fogMode = scene.fogMode;
  31717. serializationObject.fogColor = scene.fogColor.asArray();
  31718. serializationObject.fogStart = scene.fogStart;
  31719. serializationObject.fogEnd = scene.fogEnd;
  31720. serializationObject.fogDensity = scene.fogDensity;
  31721. }
  31722. //Physics
  31723. if (scene.isPhysicsEnabled()) {
  31724. serializationObject.physicsEnabled = true;
  31725. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  31726. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  31727. }
  31728. // Lights
  31729. serializationObject.lights = [];
  31730. var index;
  31731. var light;
  31732. for (index = 0; index < scene.lights.length; index++) {
  31733. light = scene.lights[index];
  31734. serializationObject.lights.push(light.serialize());
  31735. }
  31736. // Cameras
  31737. serializationObject.cameras = [];
  31738. for (index = 0; index < scene.cameras.length; index++) {
  31739. var camera = scene.cameras[index];
  31740. serializationObject.cameras.push(camera.serialize());
  31741. }
  31742. if (scene.activeCamera) {
  31743. serializationObject.activeCameraID = scene.activeCamera.id;
  31744. }
  31745. // Animations
  31746. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  31747. // Materials
  31748. serializationObject.materials = [];
  31749. serializationObject.multiMaterials = [];
  31750. var material;
  31751. for (index = 0; index < scene.materials.length; index++) {
  31752. material = scene.materials[index];
  31753. serializationObject.materials.push(material.serialize());
  31754. }
  31755. // MultiMaterials
  31756. serializationObject.multiMaterials = [];
  31757. for (index = 0; index < scene.multiMaterials.length; index++) {
  31758. var multiMaterial = scene.multiMaterials[index];
  31759. serializationObject.multiMaterials.push(multiMaterial.serialize());
  31760. }
  31761. // Skeletons
  31762. serializationObject.skeletons = [];
  31763. for (index = 0; index < scene.skeletons.length; index++) {
  31764. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  31765. }
  31766. // Geometries
  31767. serializationObject.geometries = {};
  31768. serializationObject.geometries.boxes = [];
  31769. serializationObject.geometries.spheres = [];
  31770. serializationObject.geometries.cylinders = [];
  31771. serializationObject.geometries.toruses = [];
  31772. serializationObject.geometries.grounds = [];
  31773. serializationObject.geometries.planes = [];
  31774. serializationObject.geometries.torusKnots = [];
  31775. serializationObject.geometries.vertexData = [];
  31776. serializedGeometries = [];
  31777. var geometries = scene.getGeometries();
  31778. for (index = 0; index < geometries.length; index++) {
  31779. var geometry = geometries[index];
  31780. if (geometry.isReady()) {
  31781. serializeGeometry(geometry, serializationObject.geometries);
  31782. }
  31783. }
  31784. // Meshes
  31785. serializationObject.meshes = [];
  31786. for (index = 0; index < scene.meshes.length; index++) {
  31787. var abstractMesh = scene.meshes[index];
  31788. if (abstractMesh instanceof BABYLON.Mesh) {
  31789. var mesh = abstractMesh;
  31790. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31791. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31792. }
  31793. }
  31794. }
  31795. // Particles Systems
  31796. serializationObject.particleSystems = [];
  31797. for (index = 0; index < scene.particleSystems.length; index++) {
  31798. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  31799. }
  31800. // Lens flares
  31801. serializationObject.lensFlareSystems = [];
  31802. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  31803. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  31804. }
  31805. // Shadows
  31806. serializationObject.shadowGenerators = [];
  31807. for (index = 0; index < scene.lights.length; index++) {
  31808. light = scene.lights[index];
  31809. if (light.getShadowGenerator()) {
  31810. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  31811. }
  31812. }
  31813. return serializationObject;
  31814. };
  31815. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  31816. if (withParents === void 0) { withParents = false; }
  31817. if (withChildren === void 0) { withChildren = false; }
  31818. var serializationObject = {};
  31819. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  31820. if (withParents || withChildren) {
  31821. //deliberate for loop! not for each, appended should be processed as well.
  31822. for (var i = 0; i < toSerialize.length; ++i) {
  31823. if (withChildren) {
  31824. toSerialize[i].getDescendants().forEach(function (node) {
  31825. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  31826. toSerialize.push(node);
  31827. }
  31828. });
  31829. }
  31830. //make sure the array doesn't contain the object already
  31831. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  31832. toSerialize.push(toSerialize[i].parent);
  31833. }
  31834. }
  31835. }
  31836. toSerialize.forEach(function (mesh) {
  31837. finalizeSingleMesh(mesh, serializationObject);
  31838. });
  31839. return serializationObject;
  31840. };
  31841. return SceneSerializer;
  31842. })();
  31843. BABYLON.SceneSerializer = SceneSerializer;
  31844. })(BABYLON || (BABYLON = {}));
  31845. var BABYLON;
  31846. (function (BABYLON) {
  31847. // Unique ID when we import meshes from Babylon to CSG
  31848. var currentCSGMeshId = 0;
  31849. // # class Vertex
  31850. // Represents a vertex of a polygon. Use your own vertex class instead of this
  31851. // one to provide additional features like texture coordinates and vertex
  31852. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  31853. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  31854. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  31855. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  31856. // is not used anywhere else.
  31857. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  31858. var Vertex = (function () {
  31859. function Vertex(pos, normal, uv) {
  31860. this.pos = pos;
  31861. this.normal = normal;
  31862. this.uv = uv;
  31863. }
  31864. Vertex.prototype.clone = function () {
  31865. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  31866. };
  31867. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  31868. // orientation of a polygon is flipped.
  31869. Vertex.prototype.flip = function () {
  31870. this.normal = this.normal.scale(-1);
  31871. };
  31872. // Create a new vertex between this vertex and `other` by linearly
  31873. // interpolating all properties using a parameter of `t`. Subclasses should
  31874. // override this to interpolate additional properties.
  31875. Vertex.prototype.interpolate = function (other, t) {
  31876. 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));
  31877. };
  31878. return Vertex;
  31879. })();
  31880. // # class Plane
  31881. // Represents a plane in 3D space.
  31882. var Plane = (function () {
  31883. function Plane(normal, w) {
  31884. this.normal = normal;
  31885. this.w = w;
  31886. }
  31887. Plane.FromPoints = function (a, b, c) {
  31888. var v0 = c.subtract(a);
  31889. var v1 = b.subtract(a);
  31890. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  31891. return null;
  31892. }
  31893. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  31894. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  31895. };
  31896. Plane.prototype.clone = function () {
  31897. return new Plane(this.normal.clone(), this.w);
  31898. };
  31899. Plane.prototype.flip = function () {
  31900. this.normal.scaleInPlace(-1);
  31901. this.w = -this.w;
  31902. };
  31903. // Split `polygon` by this plane if needed, then put the polygon or polygon
  31904. // fragments in the appropriate lists. Coplanar polygons go into either
  31905. // `coplanarFront` or `coplanarBack` depending on their orientation with
  31906. // respect to this plane. Polygons in front or in back of this plane go into
  31907. // either `front` or `back`.
  31908. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  31909. var COPLANAR = 0;
  31910. var FRONT = 1;
  31911. var BACK = 2;
  31912. var SPANNING = 3;
  31913. // Classify each point as well as the entire polygon into one of the above
  31914. // four classes.
  31915. var polygonType = 0;
  31916. var types = [];
  31917. var i;
  31918. var t;
  31919. for (i = 0; i < polygon.vertices.length; i++) {
  31920. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  31921. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  31922. polygonType |= type;
  31923. types.push(type);
  31924. }
  31925. // Put the polygon in the correct list, splitting it when necessary.
  31926. switch (polygonType) {
  31927. case COPLANAR:
  31928. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  31929. break;
  31930. case FRONT:
  31931. front.push(polygon);
  31932. break;
  31933. case BACK:
  31934. back.push(polygon);
  31935. break;
  31936. case SPANNING:
  31937. var f = [], b = [];
  31938. for (i = 0; i < polygon.vertices.length; i++) {
  31939. var j = (i + 1) % polygon.vertices.length;
  31940. var ti = types[i], tj = types[j];
  31941. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  31942. if (ti !== BACK)
  31943. f.push(vi);
  31944. if (ti !== FRONT)
  31945. b.push(ti !== BACK ? vi.clone() : vi);
  31946. if ((ti | tj) === SPANNING) {
  31947. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31948. var v = vi.interpolate(vj, t);
  31949. f.push(v);
  31950. b.push(v.clone());
  31951. }
  31952. }
  31953. var poly;
  31954. if (f.length >= 3) {
  31955. poly = new Polygon(f, polygon.shared);
  31956. if (poly.plane)
  31957. front.push(poly);
  31958. }
  31959. if (b.length >= 3) {
  31960. poly = new Polygon(b, polygon.shared);
  31961. if (poly.plane)
  31962. back.push(poly);
  31963. }
  31964. break;
  31965. }
  31966. };
  31967. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31968. // point is on the plane.
  31969. Plane.EPSILON = 1e-5;
  31970. return Plane;
  31971. })();
  31972. // # class Polygon
  31973. // Represents a convex polygon. The vertices used to initialize a polygon must
  31974. // be coplanar and form a convex loop.
  31975. //
  31976. // Each convex polygon has a `shared` property, which is shared between all
  31977. // polygons that are clones of each other or were split from the same polygon.
  31978. // This can be used to define per-polygon properties (such as surface color).
  31979. var Polygon = (function () {
  31980. function Polygon(vertices, shared) {
  31981. this.vertices = vertices;
  31982. this.shared = shared;
  31983. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31984. }
  31985. Polygon.prototype.clone = function () {
  31986. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31987. return new Polygon(vertices, this.shared);
  31988. };
  31989. Polygon.prototype.flip = function () {
  31990. this.vertices.reverse().map(function (v) { v.flip(); });
  31991. this.plane.flip();
  31992. };
  31993. return Polygon;
  31994. })();
  31995. // # class Node
  31996. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31997. // by picking a polygon to split along. That polygon (and all other coplanar
  31998. // polygons) are added directly to that node and the other polygons are added to
  31999. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32000. // no distinction between internal and leaf nodes.
  32001. var Node = (function () {
  32002. function Node(polygons) {
  32003. this.plane = null;
  32004. this.front = null;
  32005. this.back = null;
  32006. this.polygons = [];
  32007. if (polygons) {
  32008. this.build(polygons);
  32009. }
  32010. }
  32011. Node.prototype.clone = function () {
  32012. var node = new Node();
  32013. node.plane = this.plane && this.plane.clone();
  32014. node.front = this.front && this.front.clone();
  32015. node.back = this.back && this.back.clone();
  32016. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32017. return node;
  32018. };
  32019. // Convert solid space to empty space and empty space to solid space.
  32020. Node.prototype.invert = function () {
  32021. for (var i = 0; i < this.polygons.length; i++) {
  32022. this.polygons[i].flip();
  32023. }
  32024. if (this.plane) {
  32025. this.plane.flip();
  32026. }
  32027. if (this.front) {
  32028. this.front.invert();
  32029. }
  32030. if (this.back) {
  32031. this.back.invert();
  32032. }
  32033. var temp = this.front;
  32034. this.front = this.back;
  32035. this.back = temp;
  32036. };
  32037. // Recursively remove all polygons in `polygons` that are inside this BSP
  32038. // tree.
  32039. Node.prototype.clipPolygons = function (polygons) {
  32040. if (!this.plane)
  32041. return polygons.slice();
  32042. var front = [], back = [];
  32043. for (var i = 0; i < polygons.length; i++) {
  32044. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32045. }
  32046. if (this.front) {
  32047. front = this.front.clipPolygons(front);
  32048. }
  32049. if (this.back) {
  32050. back = this.back.clipPolygons(back);
  32051. }
  32052. else {
  32053. back = [];
  32054. }
  32055. return front.concat(back);
  32056. };
  32057. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32058. // `bsp`.
  32059. Node.prototype.clipTo = function (bsp) {
  32060. this.polygons = bsp.clipPolygons(this.polygons);
  32061. if (this.front)
  32062. this.front.clipTo(bsp);
  32063. if (this.back)
  32064. this.back.clipTo(bsp);
  32065. };
  32066. // Return a list of all polygons in this BSP tree.
  32067. Node.prototype.allPolygons = function () {
  32068. var polygons = this.polygons.slice();
  32069. if (this.front)
  32070. polygons = polygons.concat(this.front.allPolygons());
  32071. if (this.back)
  32072. polygons = polygons.concat(this.back.allPolygons());
  32073. return polygons;
  32074. };
  32075. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32076. // new polygons are filtered down to the bottom of the tree and become new
  32077. // nodes there. Each set of polygons is partitioned using the first polygon
  32078. // (no heuristic is used to pick a good split).
  32079. Node.prototype.build = function (polygons) {
  32080. if (!polygons.length)
  32081. return;
  32082. if (!this.plane)
  32083. this.plane = polygons[0].plane.clone();
  32084. var front = [], back = [];
  32085. for (var i = 0; i < polygons.length; i++) {
  32086. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32087. }
  32088. if (front.length) {
  32089. if (!this.front)
  32090. this.front = new Node();
  32091. this.front.build(front);
  32092. }
  32093. if (back.length) {
  32094. if (!this.back)
  32095. this.back = new Node();
  32096. this.back.build(back);
  32097. }
  32098. };
  32099. return Node;
  32100. })();
  32101. var CSG = (function () {
  32102. function CSG() {
  32103. this.polygons = new Array();
  32104. }
  32105. // Convert BABYLON.Mesh to BABYLON.CSG
  32106. CSG.FromMesh = function (mesh) {
  32107. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32108. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32109. if (mesh instanceof BABYLON.Mesh) {
  32110. mesh.computeWorldMatrix(true);
  32111. matrix = mesh.getWorldMatrix();
  32112. meshPosition = mesh.position.clone();
  32113. meshRotation = mesh.rotation.clone();
  32114. if (mesh.rotationQuaternion) {
  32115. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32116. }
  32117. meshScaling = mesh.scaling.clone();
  32118. }
  32119. else {
  32120. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32121. }
  32122. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32123. var subMeshes = mesh.subMeshes;
  32124. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32125. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32126. vertices = [];
  32127. for (var j = 0; j < 3; j++) {
  32128. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32129. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32130. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32131. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32132. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32133. vertex = new Vertex(position, normal, uv);
  32134. vertices.push(vertex);
  32135. }
  32136. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32137. // To handle the case of degenerated triangle
  32138. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32139. if (polygon.plane)
  32140. polygons.push(polygon);
  32141. }
  32142. }
  32143. var csg = CSG.FromPolygons(polygons);
  32144. csg.matrix = matrix;
  32145. csg.position = meshPosition;
  32146. csg.rotation = meshRotation;
  32147. csg.scaling = meshScaling;
  32148. csg.rotationQuaternion = meshRotationQuaternion;
  32149. currentCSGMeshId++;
  32150. return csg;
  32151. };
  32152. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32153. CSG.FromPolygons = function (polygons) {
  32154. var csg = new CSG();
  32155. csg.polygons = polygons;
  32156. return csg;
  32157. };
  32158. CSG.prototype.clone = function () {
  32159. var csg = new CSG();
  32160. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32161. csg.copyTransformAttributes(this);
  32162. return csg;
  32163. };
  32164. CSG.prototype.toPolygons = function () {
  32165. return this.polygons;
  32166. };
  32167. CSG.prototype.union = function (csg) {
  32168. var a = new Node(this.clone().polygons);
  32169. var b = new Node(csg.clone().polygons);
  32170. a.clipTo(b);
  32171. b.clipTo(a);
  32172. b.invert();
  32173. b.clipTo(a);
  32174. b.invert();
  32175. a.build(b.allPolygons());
  32176. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32177. };
  32178. CSG.prototype.unionInPlace = function (csg) {
  32179. var a = new Node(this.polygons);
  32180. var b = new Node(csg.polygons);
  32181. a.clipTo(b);
  32182. b.clipTo(a);
  32183. b.invert();
  32184. b.clipTo(a);
  32185. b.invert();
  32186. a.build(b.allPolygons());
  32187. this.polygons = a.allPolygons();
  32188. };
  32189. CSG.prototype.subtract = function (csg) {
  32190. var a = new Node(this.clone().polygons);
  32191. var b = new Node(csg.clone().polygons);
  32192. a.invert();
  32193. a.clipTo(b);
  32194. b.clipTo(a);
  32195. b.invert();
  32196. b.clipTo(a);
  32197. b.invert();
  32198. a.build(b.allPolygons());
  32199. a.invert();
  32200. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32201. };
  32202. CSG.prototype.subtractInPlace = function (csg) {
  32203. var a = new Node(this.polygons);
  32204. var b = new Node(csg.polygons);
  32205. a.invert();
  32206. a.clipTo(b);
  32207. b.clipTo(a);
  32208. b.invert();
  32209. b.clipTo(a);
  32210. b.invert();
  32211. a.build(b.allPolygons());
  32212. a.invert();
  32213. this.polygons = a.allPolygons();
  32214. };
  32215. CSG.prototype.intersect = function (csg) {
  32216. var a = new Node(this.clone().polygons);
  32217. var b = new Node(csg.clone().polygons);
  32218. a.invert();
  32219. b.clipTo(a);
  32220. b.invert();
  32221. a.clipTo(b);
  32222. b.clipTo(a);
  32223. a.build(b.allPolygons());
  32224. a.invert();
  32225. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32226. };
  32227. CSG.prototype.intersectInPlace = function (csg) {
  32228. var a = new Node(this.polygons);
  32229. var b = new Node(csg.polygons);
  32230. a.invert();
  32231. b.clipTo(a);
  32232. b.invert();
  32233. a.clipTo(b);
  32234. b.clipTo(a);
  32235. a.build(b.allPolygons());
  32236. a.invert();
  32237. this.polygons = a.allPolygons();
  32238. };
  32239. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32240. // not modified.
  32241. CSG.prototype.inverse = function () {
  32242. var csg = this.clone();
  32243. csg.inverseInPlace();
  32244. return csg;
  32245. };
  32246. CSG.prototype.inverseInPlace = function () {
  32247. this.polygons.map(function (p) { p.flip(); });
  32248. };
  32249. // This is used to keep meshes transformations so they can be restored
  32250. // when we build back a Babylon Mesh
  32251. // NB : All CSG operations are performed in world coordinates
  32252. CSG.prototype.copyTransformAttributes = function (csg) {
  32253. this.matrix = csg.matrix;
  32254. this.position = csg.position;
  32255. this.rotation = csg.rotation;
  32256. this.scaling = csg.scaling;
  32257. this.rotationQuaternion = csg.rotationQuaternion;
  32258. return this;
  32259. };
  32260. // Build Raw mesh from CSG
  32261. // Coordinates here are in world space
  32262. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32263. var matrix = this.matrix.clone();
  32264. matrix.invert();
  32265. 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;
  32266. if (keepSubMeshes) {
  32267. // Sort Polygons, since subMeshes are indices range
  32268. polygons.sort(function (a, b) {
  32269. if (a.shared.meshId === b.shared.meshId) {
  32270. return a.shared.subMeshId - b.shared.subMeshId;
  32271. }
  32272. else {
  32273. return a.shared.meshId - b.shared.meshId;
  32274. }
  32275. });
  32276. }
  32277. for (var i = 0, il = polygons.length; i < il; i++) {
  32278. polygon = polygons[i];
  32279. // Building SubMeshes
  32280. if (!subMesh_dict[polygon.shared.meshId]) {
  32281. subMesh_dict[polygon.shared.meshId] = {};
  32282. }
  32283. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32284. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32285. indexStart: +Infinity,
  32286. indexEnd: -Infinity,
  32287. materialIndex: polygon.shared.materialIndex
  32288. };
  32289. }
  32290. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32291. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32292. polygonIndices[0] = 0;
  32293. polygonIndices[1] = j - 1;
  32294. polygonIndices[2] = j;
  32295. for (var k = 0; k < 3; k++) {
  32296. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32297. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32298. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32299. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32300. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32301. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32302. // Check if 2 points can be merged
  32303. if (!(typeof vertex_idx !== 'undefined' &&
  32304. normals[vertex_idx * 3] === localNormal.x &&
  32305. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32306. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32307. uvs[vertex_idx * 2] === uv.x &&
  32308. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32309. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32310. uvs.push(uv.x, uv.y);
  32311. normals.push(normal.x, normal.y, normal.z);
  32312. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32313. }
  32314. indices.push(vertex_idx);
  32315. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32316. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32317. currentIndex++;
  32318. }
  32319. }
  32320. }
  32321. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32322. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32323. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32324. mesh.setIndices(indices);
  32325. if (keepSubMeshes) {
  32326. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32327. var materialIndexOffset = 0, materialMaxIndex;
  32328. mesh.subMeshes = new Array();
  32329. for (var m in subMesh_dict) {
  32330. materialMaxIndex = -1;
  32331. for (var sm in subMesh_dict[m]) {
  32332. subMesh_obj = subMesh_dict[m][sm];
  32333. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32334. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32335. }
  32336. materialIndexOffset += ++materialMaxIndex;
  32337. }
  32338. }
  32339. return mesh;
  32340. };
  32341. // Build Mesh from CSG taking material and transforms into account
  32342. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32343. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32344. mesh.material = material;
  32345. mesh.position.copyFrom(this.position);
  32346. mesh.rotation.copyFrom(this.rotation);
  32347. if (this.rotationQuaternion) {
  32348. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32349. }
  32350. mesh.scaling.copyFrom(this.scaling);
  32351. mesh.computeWorldMatrix(true);
  32352. return mesh;
  32353. };
  32354. return CSG;
  32355. })();
  32356. BABYLON.CSG = CSG;
  32357. })(BABYLON || (BABYLON = {}));
  32358. var BABYLON;
  32359. (function (BABYLON) {
  32360. var VRDistortionCorrectionPostProcess = (function (_super) {
  32361. __extends(VRDistortionCorrectionPostProcess, _super);
  32362. //ANY
  32363. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32364. var _this = this;
  32365. _super.call(this, name, "vrDistortionCorrection", [
  32366. 'LensCenter',
  32367. 'Scale',
  32368. 'ScaleIn',
  32369. 'HmdWarpParam'
  32370. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32371. this._isRightEye = isRightEye;
  32372. this._distortionFactors = vrMetrics.distortionK;
  32373. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32374. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32375. this.onSizeChanged = function () {
  32376. _this.aspectRatio = _this.width * .5 / _this.height;
  32377. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32378. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32379. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32380. };
  32381. this.onApply = function (effect) {
  32382. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32383. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32384. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32385. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32386. };
  32387. }
  32388. return VRDistortionCorrectionPostProcess;
  32389. })(BABYLON.PostProcess);
  32390. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32391. })(BABYLON || (BABYLON = {}));
  32392. // Mainly based on these 2 articles :
  32393. // 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
  32394. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32395. var BABYLON;
  32396. (function (BABYLON) {
  32397. (function (JoystickAxis) {
  32398. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32399. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32400. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32401. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32402. var JoystickAxis = BABYLON.JoystickAxis;
  32403. var VirtualJoystick = (function () {
  32404. function VirtualJoystick(leftJoystick) {
  32405. var _this = this;
  32406. if (leftJoystick) {
  32407. this._leftJoystick = true;
  32408. }
  32409. else {
  32410. this._leftJoystick = false;
  32411. }
  32412. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32413. VirtualJoystick._globalJoystickIndex++;
  32414. // By default left & right arrow keys are moving the X
  32415. // and up & down keys are moving the Y
  32416. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32417. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32418. this.reverseLeftRight = false;
  32419. this.reverseUpDown = false;
  32420. // collections of pointers
  32421. this._touches = new BABYLON.SmartCollection();
  32422. this.deltaPosition = BABYLON.Vector3.Zero();
  32423. this._joystickSensibility = 25;
  32424. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32425. this._rotationSpeed = 25;
  32426. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32427. this._rotateOnAxisRelativeToMesh = false;
  32428. this._onResize = function (evt) {
  32429. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32430. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32431. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32432. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32433. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32434. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32435. };
  32436. // injecting a canvas element on top of the canvas 3D game
  32437. if (!VirtualJoystick.vjCanvas) {
  32438. window.addEventListener("resize", this._onResize, false);
  32439. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32440. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32441. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32442. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32443. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32444. VirtualJoystick.vjCanvas.style.width = "100%";
  32445. VirtualJoystick.vjCanvas.style.height = "100%";
  32446. VirtualJoystick.vjCanvas.style.position = "absolute";
  32447. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32448. VirtualJoystick.vjCanvas.style.top = "0px";
  32449. VirtualJoystick.vjCanvas.style.left = "0px";
  32450. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32451. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32452. // Support for jQuery PEP polyfill
  32453. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32454. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32455. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32456. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32457. document.body.appendChild(VirtualJoystick.vjCanvas);
  32458. }
  32459. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32460. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32461. this.pressed = false;
  32462. // default joystick color
  32463. this._joystickColor = "cyan";
  32464. this._joystickPointerID = -1;
  32465. // current joystick position
  32466. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32467. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32468. // origin joystick position
  32469. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32470. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32471. this._onPointerDownHandlerRef = function (evt) {
  32472. _this._onPointerDown(evt);
  32473. };
  32474. this._onPointerMoveHandlerRef = function (evt) {
  32475. _this._onPointerMove(evt);
  32476. };
  32477. this._onPointerOutHandlerRef = function (evt) {
  32478. _this._onPointerUp(evt);
  32479. };
  32480. this._onPointerUpHandlerRef = function (evt) {
  32481. _this._onPointerUp(evt);
  32482. };
  32483. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32484. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32485. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32486. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32487. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32488. evt.preventDefault(); // Disables system menu
  32489. }, false);
  32490. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32491. }
  32492. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32493. this._joystickSensibility = newJoystickSensibility;
  32494. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32495. };
  32496. VirtualJoystick.prototype._onPointerDown = function (e) {
  32497. var positionOnScreenCondition;
  32498. e.preventDefault();
  32499. if (this._leftJoystick === true) {
  32500. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32501. }
  32502. else {
  32503. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32504. }
  32505. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32506. // First contact will be dedicated to the virtual joystick
  32507. this._joystickPointerID = e.pointerId;
  32508. this._joystickPointerStartPos.x = e.clientX;
  32509. this._joystickPointerStartPos.y = e.clientY;
  32510. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32511. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32512. this._deltaJoystickVector.x = 0;
  32513. this._deltaJoystickVector.y = 0;
  32514. this.pressed = true;
  32515. this._touches.add(e.pointerId.toString(), e);
  32516. }
  32517. else {
  32518. // You can only trigger the action buttons with a joystick declared
  32519. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32520. this._action();
  32521. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32522. }
  32523. }
  32524. };
  32525. VirtualJoystick.prototype._onPointerMove = function (e) {
  32526. // If the current pointer is the one associated to the joystick (first touch contact)
  32527. if (this._joystickPointerID == e.pointerId) {
  32528. this._joystickPointerPos.x = e.clientX;
  32529. this._joystickPointerPos.y = e.clientY;
  32530. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32531. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32532. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32533. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32534. switch (this._axisTargetedByLeftAndRight) {
  32535. case JoystickAxis.X:
  32536. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32537. break;
  32538. case JoystickAxis.Y:
  32539. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  32540. break;
  32541. case JoystickAxis.Z:
  32542. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  32543. break;
  32544. }
  32545. var directionUpDown = this.reverseUpDown ? 1 : -1;
  32546. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  32547. switch (this._axisTargetedByUpAndDown) {
  32548. case JoystickAxis.X:
  32549. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  32550. break;
  32551. case JoystickAxis.Y:
  32552. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  32553. break;
  32554. case JoystickAxis.Z:
  32555. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  32556. break;
  32557. }
  32558. }
  32559. else {
  32560. if (this._touches.item(e.pointerId.toString())) {
  32561. this._touches.item(e.pointerId.toString()).x = e.clientX;
  32562. this._touches.item(e.pointerId.toString()).y = e.clientY;
  32563. }
  32564. }
  32565. };
  32566. VirtualJoystick.prototype._onPointerUp = function (e) {
  32567. if (this._joystickPointerID == e.pointerId) {
  32568. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  32569. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  32570. this._joystickPointerID = -1;
  32571. this.pressed = false;
  32572. }
  32573. else {
  32574. var touch = this._touches.item(e.pointerId.toString());
  32575. if (touch) {
  32576. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32577. }
  32578. }
  32579. this._deltaJoystickVector.x = 0;
  32580. this._deltaJoystickVector.y = 0;
  32581. this._touches.remove(e.pointerId.toString());
  32582. };
  32583. /**
  32584. * Change the color of the virtual joystick
  32585. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  32586. */
  32587. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  32588. this._joystickColor = newColor;
  32589. };
  32590. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  32591. this._action = action;
  32592. };
  32593. // Define which axis you'd like to control for left & right
  32594. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  32595. switch (axis) {
  32596. case JoystickAxis.X:
  32597. case JoystickAxis.Y:
  32598. case JoystickAxis.Z:
  32599. this._axisTargetedByLeftAndRight = axis;
  32600. break;
  32601. default:
  32602. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32603. break;
  32604. }
  32605. };
  32606. // Define which axis you'd like to control for up & down
  32607. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  32608. switch (axis) {
  32609. case JoystickAxis.X:
  32610. case JoystickAxis.Y:
  32611. case JoystickAxis.Z:
  32612. this._axisTargetedByUpAndDown = axis;
  32613. break;
  32614. default:
  32615. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32616. break;
  32617. }
  32618. };
  32619. VirtualJoystick.prototype._clearCanvas = function () {
  32620. if (this._leftJoystick) {
  32621. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  32622. }
  32623. else {
  32624. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  32625. }
  32626. };
  32627. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  32628. var _this = this;
  32629. if (this.pressed) {
  32630. this._touches.forEach(function (touch) {
  32631. if (touch.pointerId === _this._joystickPointerID) {
  32632. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  32633. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  32634. VirtualJoystick.vjCanvasContext.beginPath();
  32635. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32636. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32637. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  32638. VirtualJoystick.vjCanvasContext.stroke();
  32639. VirtualJoystick.vjCanvasContext.closePath();
  32640. VirtualJoystick.vjCanvasContext.beginPath();
  32641. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32642. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32643. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  32644. VirtualJoystick.vjCanvasContext.stroke();
  32645. VirtualJoystick.vjCanvasContext.closePath();
  32646. VirtualJoystick.vjCanvasContext.beginPath();
  32647. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32648. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  32649. VirtualJoystick.vjCanvasContext.stroke();
  32650. VirtualJoystick.vjCanvasContext.closePath();
  32651. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  32652. }
  32653. else {
  32654. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32655. VirtualJoystick.vjCanvasContext.beginPath();
  32656. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  32657. VirtualJoystick.vjCanvasContext.beginPath();
  32658. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  32659. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32660. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  32661. VirtualJoystick.vjCanvasContext.stroke();
  32662. VirtualJoystick.vjCanvasContext.closePath();
  32663. touch.prevX = touch.x;
  32664. touch.prevY = touch.y;
  32665. }
  32666. ;
  32667. });
  32668. }
  32669. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32670. };
  32671. VirtualJoystick.prototype.releaseCanvas = function () {
  32672. if (VirtualJoystick.vjCanvas) {
  32673. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  32674. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  32675. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  32676. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  32677. window.removeEventListener("resize", this._onResize);
  32678. document.body.removeChild(VirtualJoystick.vjCanvas);
  32679. VirtualJoystick.vjCanvas = null;
  32680. }
  32681. };
  32682. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  32683. VirtualJoystick._globalJoystickIndex = 0;
  32684. return VirtualJoystick;
  32685. })();
  32686. BABYLON.VirtualJoystick = VirtualJoystick;
  32687. })(BABYLON || (BABYLON = {}));
  32688. var BABYLON;
  32689. (function (BABYLON) {
  32690. // We're mainly based on the logic defined into the FreeCamera code
  32691. var VirtualJoysticksCamera = (function (_super) {
  32692. __extends(VirtualJoysticksCamera, _super);
  32693. function VirtualJoysticksCamera(name, position, scene) {
  32694. _super.call(this, name, position, scene);
  32695. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  32696. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  32697. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  32698. this._leftjoystick.setJoystickSensibility(0.15);
  32699. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  32700. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  32701. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  32702. this._rightjoystick.reverseUpDown = true;
  32703. this._rightjoystick.setJoystickSensibility(0.05);
  32704. this._rightjoystick.setJoystickColor("yellow");
  32705. }
  32706. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  32707. return this._leftjoystick;
  32708. };
  32709. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  32710. return this._rightjoystick;
  32711. };
  32712. VirtualJoysticksCamera.prototype._checkInputs = function () {
  32713. var speed = this._computeLocalCameraSpeed() * 50;
  32714. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32715. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  32716. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32717. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  32718. if (!this._leftjoystick.pressed) {
  32719. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  32720. }
  32721. if (!this._rightjoystick.pressed) {
  32722. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  32723. }
  32724. _super.prototype._checkInputs.call(this);
  32725. };
  32726. VirtualJoysticksCamera.prototype.dispose = function () {
  32727. this._leftjoystick.releaseCanvas();
  32728. _super.prototype.dispose.call(this);
  32729. };
  32730. VirtualJoysticksCamera.prototype.getTypeName = function () {
  32731. return "VirtualJoysticksCamera";
  32732. };
  32733. return VirtualJoysticksCamera;
  32734. })(BABYLON.FreeCamera);
  32735. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  32736. })(BABYLON || (BABYLON = {}));
  32737. var BABYLON;
  32738. (function (BABYLON) {
  32739. var AnaglyphPostProcess = (function (_super) {
  32740. __extends(AnaglyphPostProcess, _super);
  32741. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32742. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  32743. }
  32744. return AnaglyphPostProcess;
  32745. })(BABYLON.PostProcess);
  32746. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  32747. })(BABYLON || (BABYLON = {}));
  32748. var BABYLON;
  32749. (function (BABYLON) {
  32750. var OutlineRenderer = (function () {
  32751. function OutlineRenderer(scene) {
  32752. this._scene = scene;
  32753. }
  32754. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  32755. var _this = this;
  32756. if (useOverlay === void 0) { useOverlay = false; }
  32757. var scene = this._scene;
  32758. var engine = this._scene.getEngine();
  32759. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32760. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  32761. return;
  32762. }
  32763. var mesh = subMesh.getRenderingMesh();
  32764. var material = subMesh.getMaterial();
  32765. engine.enableEffect(this._effect);
  32766. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  32767. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  32768. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32769. // Bones
  32770. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32771. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32772. }
  32773. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  32774. // Alpha test
  32775. if (material && material.needAlphaTesting()) {
  32776. var alphaTexture = material.getAlphaTestTexture();
  32777. this._effect.setTexture("diffuseSampler", alphaTexture);
  32778. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32779. }
  32780. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  32781. };
  32782. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  32783. var defines = [];
  32784. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  32785. var mesh = subMesh.getMesh();
  32786. var material = subMesh.getMaterial();
  32787. // Alpha test
  32788. if (material && material.needAlphaTesting()) {
  32789. defines.push("#define ALPHATEST");
  32790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32791. attribs.push(BABYLON.VertexBuffer.UVKind);
  32792. defines.push("#define UV1");
  32793. }
  32794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32795. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32796. defines.push("#define UV2");
  32797. }
  32798. }
  32799. // Bones
  32800. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32801. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32802. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32803. if (mesh.numBoneInfluencers > 4) {
  32804. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32805. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32806. }
  32807. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32808. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32809. }
  32810. else {
  32811. defines.push("#define NUM_BONE_INFLUENCERS 0");
  32812. }
  32813. // Instances
  32814. if (useInstances) {
  32815. defines.push("#define INSTANCES");
  32816. attribs.push("world0");
  32817. attribs.push("world1");
  32818. attribs.push("world2");
  32819. attribs.push("world3");
  32820. }
  32821. // Get correct effect
  32822. var join = defines.join("\n");
  32823. if (this._cachedDefines !== join) {
  32824. this._cachedDefines = join;
  32825. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  32826. }
  32827. return this._effect.isReady();
  32828. };
  32829. return OutlineRenderer;
  32830. })();
  32831. BABYLON.OutlineRenderer = OutlineRenderer;
  32832. })(BABYLON || (BABYLON = {}));
  32833. var BABYLON;
  32834. (function (BABYLON) {
  32835. var MeshAssetTask = (function () {
  32836. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  32837. this.name = name;
  32838. this.meshesNames = meshesNames;
  32839. this.rootUrl = rootUrl;
  32840. this.sceneFilename = sceneFilename;
  32841. this.isCompleted = false;
  32842. }
  32843. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32844. var _this = this;
  32845. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  32846. _this.loadedMeshes = meshes;
  32847. _this.loadedParticleSystems = particleSystems;
  32848. _this.loadedSkeletons = skeletons;
  32849. _this.isCompleted = true;
  32850. if (_this.onSuccess) {
  32851. _this.onSuccess(_this);
  32852. }
  32853. onSuccess();
  32854. }, null, function () {
  32855. if (_this.onError) {
  32856. _this.onError(_this);
  32857. }
  32858. onError();
  32859. });
  32860. };
  32861. return MeshAssetTask;
  32862. })();
  32863. BABYLON.MeshAssetTask = MeshAssetTask;
  32864. var TextFileAssetTask = (function () {
  32865. function TextFileAssetTask(name, url) {
  32866. this.name = name;
  32867. this.url = url;
  32868. this.isCompleted = false;
  32869. }
  32870. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32871. var _this = this;
  32872. BABYLON.Tools.LoadFile(this.url, function (data) {
  32873. _this.text = data;
  32874. _this.isCompleted = true;
  32875. if (_this.onSuccess) {
  32876. _this.onSuccess(_this);
  32877. }
  32878. onSuccess();
  32879. }, null, scene.database, false, function () {
  32880. if (_this.onError) {
  32881. _this.onError(_this);
  32882. }
  32883. onError();
  32884. });
  32885. };
  32886. return TextFileAssetTask;
  32887. })();
  32888. BABYLON.TextFileAssetTask = TextFileAssetTask;
  32889. var BinaryFileAssetTask = (function () {
  32890. function BinaryFileAssetTask(name, url) {
  32891. this.name = name;
  32892. this.url = url;
  32893. this.isCompleted = false;
  32894. }
  32895. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32896. var _this = this;
  32897. BABYLON.Tools.LoadFile(this.url, function (data) {
  32898. _this.data = data;
  32899. _this.isCompleted = true;
  32900. if (_this.onSuccess) {
  32901. _this.onSuccess(_this);
  32902. }
  32903. onSuccess();
  32904. }, null, scene.database, true, function () {
  32905. if (_this.onError) {
  32906. _this.onError(_this);
  32907. }
  32908. onError();
  32909. });
  32910. };
  32911. return BinaryFileAssetTask;
  32912. })();
  32913. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  32914. var ImageAssetTask = (function () {
  32915. function ImageAssetTask(name, url) {
  32916. this.name = name;
  32917. this.url = url;
  32918. this.isCompleted = false;
  32919. }
  32920. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32921. var _this = this;
  32922. var img = new Image();
  32923. img.onload = function () {
  32924. _this.image = img;
  32925. _this.isCompleted = true;
  32926. if (_this.onSuccess) {
  32927. _this.onSuccess(_this);
  32928. }
  32929. onSuccess();
  32930. };
  32931. img.onerror = function () {
  32932. if (_this.onError) {
  32933. _this.onError(_this);
  32934. }
  32935. onError();
  32936. };
  32937. img.src = this.url;
  32938. };
  32939. return ImageAssetTask;
  32940. })();
  32941. BABYLON.ImageAssetTask = ImageAssetTask;
  32942. var TextureAssetTask = (function () {
  32943. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  32944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32945. this.name = name;
  32946. this.url = url;
  32947. this.noMipmap = noMipmap;
  32948. this.invertY = invertY;
  32949. this.samplingMode = samplingMode;
  32950. this.isCompleted = false;
  32951. }
  32952. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32953. var _this = this;
  32954. var onload = function () {
  32955. _this.isCompleted = true;
  32956. if (_this.onSuccess) {
  32957. _this.onSuccess(_this);
  32958. }
  32959. onSuccess();
  32960. };
  32961. var onerror = function () {
  32962. if (_this.onError) {
  32963. _this.onError(_this);
  32964. }
  32965. onError();
  32966. };
  32967. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  32968. };
  32969. return TextureAssetTask;
  32970. })();
  32971. BABYLON.TextureAssetTask = TextureAssetTask;
  32972. var AssetsManager = (function () {
  32973. function AssetsManager(scene) {
  32974. this._tasks = new Array();
  32975. this._waitingTasksCount = 0;
  32976. this.useDefaultLoadingScreen = true;
  32977. this._scene = scene;
  32978. }
  32979. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32980. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32981. this._tasks.push(task);
  32982. return task;
  32983. };
  32984. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32985. var task = new TextFileAssetTask(taskName, url);
  32986. this._tasks.push(task);
  32987. return task;
  32988. };
  32989. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32990. var task = new BinaryFileAssetTask(taskName, url);
  32991. this._tasks.push(task);
  32992. return task;
  32993. };
  32994. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32995. var task = new ImageAssetTask(taskName, url);
  32996. this._tasks.push(task);
  32997. return task;
  32998. };
  32999. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33001. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33002. this._tasks.push(task);
  33003. return task;
  33004. };
  33005. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33006. this._waitingTasksCount--;
  33007. if (this._waitingTasksCount === 0) {
  33008. if (this.onFinish) {
  33009. this.onFinish(this._tasks);
  33010. }
  33011. this._scene.getEngine().hideLoadingUI();
  33012. }
  33013. };
  33014. AssetsManager.prototype._runTask = function (task) {
  33015. var _this = this;
  33016. task.run(this._scene, function () {
  33017. if (_this.onTaskSuccess) {
  33018. _this.onTaskSuccess(task);
  33019. }
  33020. _this._decreaseWaitingTasksCount();
  33021. }, function () {
  33022. if (_this.onTaskError) {
  33023. _this.onTaskError(task);
  33024. }
  33025. _this._decreaseWaitingTasksCount();
  33026. });
  33027. };
  33028. AssetsManager.prototype.reset = function () {
  33029. this._tasks = new Array();
  33030. return this;
  33031. };
  33032. AssetsManager.prototype.load = function () {
  33033. this._waitingTasksCount = this._tasks.length;
  33034. if (this._waitingTasksCount === 0) {
  33035. if (this.onFinish) {
  33036. this.onFinish(this._tasks);
  33037. }
  33038. return this;
  33039. }
  33040. if (this.useDefaultLoadingScreen) {
  33041. this._scene.getEngine().displayLoadingUI();
  33042. }
  33043. for (var index = 0; index < this._tasks.length; index++) {
  33044. var task = this._tasks[index];
  33045. this._runTask(task);
  33046. }
  33047. return this;
  33048. };
  33049. return AssetsManager;
  33050. })();
  33051. BABYLON.AssetsManager = AssetsManager;
  33052. })(BABYLON || (BABYLON = {}));
  33053. var BABYLON;
  33054. (function (BABYLON) {
  33055. var VRCameraMetrics = (function () {
  33056. function VRCameraMetrics() {
  33057. this.compensateDistortion = true;
  33058. }
  33059. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33060. get: function () {
  33061. return this.hResolution / (2 * this.vResolution);
  33062. },
  33063. enumerable: true,
  33064. configurable: true
  33065. });
  33066. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33067. get: function () {
  33068. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33069. },
  33070. enumerable: true,
  33071. configurable: true
  33072. });
  33073. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33074. get: function () {
  33075. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33076. var h = (4 * meters) / this.hScreenSize;
  33077. return BABYLON.Matrix.Translation(h, 0, 0);
  33078. },
  33079. enumerable: true,
  33080. configurable: true
  33081. });
  33082. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33083. get: function () {
  33084. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33085. var h = (4 * meters) / this.hScreenSize;
  33086. return BABYLON.Matrix.Translation(-h, 0, 0);
  33087. },
  33088. enumerable: true,
  33089. configurable: true
  33090. });
  33091. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33092. get: function () {
  33093. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33094. },
  33095. enumerable: true,
  33096. configurable: true
  33097. });
  33098. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33099. get: function () {
  33100. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33101. },
  33102. enumerable: true,
  33103. configurable: true
  33104. });
  33105. VRCameraMetrics.GetDefault = function () {
  33106. var result = new VRCameraMetrics();
  33107. result.hResolution = 1280;
  33108. result.vResolution = 800;
  33109. result.hScreenSize = 0.149759993;
  33110. result.vScreenSize = 0.0935999975;
  33111. result.vScreenCenter = 0.0467999987,
  33112. result.eyeToScreenDistance = 0.0410000011;
  33113. result.lensSeparationDistance = 0.0635000020;
  33114. result.interpupillaryDistance = 0.0640000030;
  33115. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33116. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33117. result.postProcessScaleFactor = 1.714605507808412;
  33118. result.lensCenterOffset = 0.151976421;
  33119. return result;
  33120. };
  33121. return VRCameraMetrics;
  33122. })();
  33123. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33124. })(BABYLON || (BABYLON = {}));
  33125. var BABYLON;
  33126. (function (BABYLON) {
  33127. var VRDeviceOrientationFreeCamera = (function (_super) {
  33128. __extends(VRDeviceOrientationFreeCamera, _super);
  33129. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33130. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33131. _super.call(this, name, position, scene);
  33132. this._alpha = 0;
  33133. this._beta = 0;
  33134. this._gamma = 0;
  33135. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33136. metrics.compensateDistortion = compensateDistortion;
  33137. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33138. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33139. }
  33140. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33141. this._alpha = +evt.alpha | 0;
  33142. this._beta = +evt.beta | 0;
  33143. this._gamma = +evt.gamma | 0;
  33144. if (this._gamma < 0) {
  33145. this._gamma = 90 + this._gamma;
  33146. }
  33147. else {
  33148. // Incline it in the correct angle.
  33149. this._gamma = 270 - this._gamma;
  33150. }
  33151. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33152. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33153. this.rotation.z = this._beta / 180.0 * Math.PI;
  33154. };
  33155. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33156. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33157. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33158. };
  33159. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33160. _super.prototype.detachControl.call(this, element);
  33161. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33162. };
  33163. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33164. return "VRDeviceOrientationFreeCamera";
  33165. };
  33166. return VRDeviceOrientationFreeCamera;
  33167. })(BABYLON.FreeCamera);
  33168. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33169. })(BABYLON || (BABYLON = {}));
  33170. var BABYLON;
  33171. (function (BABYLON) {
  33172. var WebVRFreeCamera = (function (_super) {
  33173. __extends(WebVRFreeCamera, _super);
  33174. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33175. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33176. _super.call(this, name, position, scene);
  33177. this._hmdDevice = null;
  33178. this._sensorDevice = null;
  33179. this._cacheState = null;
  33180. this._cacheQuaternion = new BABYLON.Quaternion();
  33181. this._cacheRotation = BABYLON.Vector3.Zero();
  33182. this._vrEnabled = false;
  33183. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33184. metrics.compensateDistortion = compensateDistortion;
  33185. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33186. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33187. }
  33188. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33189. var size = devices.length;
  33190. var i = 0;
  33191. // Reset devices.
  33192. this._sensorDevice = null;
  33193. this._hmdDevice = null;
  33194. // Search for a HmdDevice.
  33195. while (i < size && this._hmdDevice === null) {
  33196. if (devices[i] instanceof HMDVRDevice) {
  33197. this._hmdDevice = devices[i];
  33198. }
  33199. i++;
  33200. }
  33201. i = 0;
  33202. while (i < size && this._sensorDevice === null) {
  33203. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33204. this._sensorDevice = devices[i];
  33205. }
  33206. i++;
  33207. }
  33208. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33209. };
  33210. WebVRFreeCamera.prototype._checkInputs = function () {
  33211. if (this._vrEnabled) {
  33212. this._cacheState = this._sensorDevice.getState();
  33213. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33214. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33215. this.rotation.x = -this._cacheRotation.z;
  33216. this.rotation.y = -this._cacheRotation.y;
  33217. this.rotation.z = this._cacheRotation.x;
  33218. }
  33219. _super.prototype._checkInputs.call(this);
  33220. };
  33221. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33222. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33223. if (navigator.getVRDevices) {
  33224. navigator.getVRDevices().then(this._getWebVRDevices);
  33225. }
  33226. else if (navigator.mozGetVRDevices) {
  33227. navigator.mozGetVRDevices(this._getWebVRDevices);
  33228. }
  33229. };
  33230. WebVRFreeCamera.prototype.detachControl = function (element) {
  33231. _super.prototype.detachControl.call(this, element);
  33232. this._vrEnabled = false;
  33233. };
  33234. WebVRFreeCamera.prototype.getTypeName = function () {
  33235. return "WebVRFreeCamera";
  33236. };
  33237. return WebVRFreeCamera;
  33238. })(BABYLON.FreeCamera);
  33239. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33240. })(BABYLON || (BABYLON = {}));
  33241. var BABYLON;
  33242. (function (BABYLON) {
  33243. // Standard optimizations
  33244. var SceneOptimization = (function () {
  33245. function SceneOptimization(priority) {
  33246. if (priority === void 0) { priority = 0; }
  33247. this.priority = priority;
  33248. this.apply = function (scene) {
  33249. return true; // Return true if everything that can be done was applied
  33250. };
  33251. }
  33252. return SceneOptimization;
  33253. })();
  33254. BABYLON.SceneOptimization = SceneOptimization;
  33255. var TextureOptimization = (function (_super) {
  33256. __extends(TextureOptimization, _super);
  33257. function TextureOptimization(priority, maximumSize) {
  33258. var _this = this;
  33259. if (priority === void 0) { priority = 0; }
  33260. if (maximumSize === void 0) { maximumSize = 1024; }
  33261. _super.call(this, priority);
  33262. this.priority = priority;
  33263. this.maximumSize = maximumSize;
  33264. this.apply = function (scene) {
  33265. var allDone = true;
  33266. for (var index = 0; index < scene.textures.length; index++) {
  33267. var texture = scene.textures[index];
  33268. if (!texture.canRescale) {
  33269. continue;
  33270. }
  33271. var currentSize = texture.getSize();
  33272. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33273. if (maxDimension > _this.maximumSize) {
  33274. texture.scale(0.5);
  33275. allDone = false;
  33276. }
  33277. }
  33278. return allDone;
  33279. };
  33280. }
  33281. return TextureOptimization;
  33282. })(SceneOptimization);
  33283. BABYLON.TextureOptimization = TextureOptimization;
  33284. var HardwareScalingOptimization = (function (_super) {
  33285. __extends(HardwareScalingOptimization, _super);
  33286. function HardwareScalingOptimization(priority, maximumScale) {
  33287. var _this = this;
  33288. if (priority === void 0) { priority = 0; }
  33289. if (maximumScale === void 0) { maximumScale = 2; }
  33290. _super.call(this, priority);
  33291. this.priority = priority;
  33292. this.maximumScale = maximumScale;
  33293. this._currentScale = 1;
  33294. this.apply = function (scene) {
  33295. _this._currentScale++;
  33296. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33297. return _this._currentScale >= _this.maximumScale;
  33298. };
  33299. }
  33300. return HardwareScalingOptimization;
  33301. })(SceneOptimization);
  33302. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33303. var ShadowsOptimization = (function (_super) {
  33304. __extends(ShadowsOptimization, _super);
  33305. function ShadowsOptimization() {
  33306. _super.apply(this, arguments);
  33307. this.apply = function (scene) {
  33308. scene.shadowsEnabled = false;
  33309. return true;
  33310. };
  33311. }
  33312. return ShadowsOptimization;
  33313. })(SceneOptimization);
  33314. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33315. var PostProcessesOptimization = (function (_super) {
  33316. __extends(PostProcessesOptimization, _super);
  33317. function PostProcessesOptimization() {
  33318. _super.apply(this, arguments);
  33319. this.apply = function (scene) {
  33320. scene.postProcessesEnabled = false;
  33321. return true;
  33322. };
  33323. }
  33324. return PostProcessesOptimization;
  33325. })(SceneOptimization);
  33326. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33327. var LensFlaresOptimization = (function (_super) {
  33328. __extends(LensFlaresOptimization, _super);
  33329. function LensFlaresOptimization() {
  33330. _super.apply(this, arguments);
  33331. this.apply = function (scene) {
  33332. scene.lensFlaresEnabled = false;
  33333. return true;
  33334. };
  33335. }
  33336. return LensFlaresOptimization;
  33337. })(SceneOptimization);
  33338. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33339. var ParticlesOptimization = (function (_super) {
  33340. __extends(ParticlesOptimization, _super);
  33341. function ParticlesOptimization() {
  33342. _super.apply(this, arguments);
  33343. this.apply = function (scene) {
  33344. scene.particlesEnabled = false;
  33345. return true;
  33346. };
  33347. }
  33348. return ParticlesOptimization;
  33349. })(SceneOptimization);
  33350. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33351. var RenderTargetsOptimization = (function (_super) {
  33352. __extends(RenderTargetsOptimization, _super);
  33353. function RenderTargetsOptimization() {
  33354. _super.apply(this, arguments);
  33355. this.apply = function (scene) {
  33356. scene.renderTargetsEnabled = false;
  33357. return true;
  33358. };
  33359. }
  33360. return RenderTargetsOptimization;
  33361. })(SceneOptimization);
  33362. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  33363. var MergeMeshesOptimization = (function (_super) {
  33364. __extends(MergeMeshesOptimization, _super);
  33365. function MergeMeshesOptimization() {
  33366. var _this = this;
  33367. _super.apply(this, arguments);
  33368. this._canBeMerged = function (abstractMesh) {
  33369. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33370. return false;
  33371. }
  33372. var mesh = abstractMesh;
  33373. if (!mesh.isVisible || !mesh.isEnabled()) {
  33374. return false;
  33375. }
  33376. if (mesh.instances.length > 0) {
  33377. return false;
  33378. }
  33379. if (mesh.skeleton || mesh.hasLODLevels) {
  33380. return false;
  33381. }
  33382. if (mesh.parent) {
  33383. return false;
  33384. }
  33385. return true;
  33386. };
  33387. this.apply = function (scene, updateSelectionTree) {
  33388. var globalPool = scene.meshes.slice(0);
  33389. var globalLength = globalPool.length;
  33390. for (var index = 0; index < globalLength; index++) {
  33391. var currentPool = new Array();
  33392. var current = globalPool[index];
  33393. // Checks
  33394. if (!_this._canBeMerged(current)) {
  33395. continue;
  33396. }
  33397. currentPool.push(current);
  33398. // Find compatible meshes
  33399. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33400. var otherMesh = globalPool[subIndex];
  33401. if (!_this._canBeMerged(otherMesh)) {
  33402. continue;
  33403. }
  33404. if (otherMesh.material !== current.material) {
  33405. continue;
  33406. }
  33407. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33408. continue;
  33409. }
  33410. currentPool.push(otherMesh);
  33411. globalLength--;
  33412. globalPool.splice(subIndex, 1);
  33413. subIndex--;
  33414. }
  33415. if (currentPool.length < 2) {
  33416. continue;
  33417. }
  33418. // Merge meshes
  33419. BABYLON.Mesh.MergeMeshes(currentPool);
  33420. }
  33421. if (updateSelectionTree != undefined) {
  33422. if (updateSelectionTree) {
  33423. scene.createOrUpdateSelectionOctree();
  33424. }
  33425. }
  33426. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33427. scene.createOrUpdateSelectionOctree();
  33428. }
  33429. return true;
  33430. };
  33431. }
  33432. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33433. get: function () {
  33434. return MergeMeshesOptimization._UpdateSelectionTree;
  33435. },
  33436. set: function (value) {
  33437. MergeMeshesOptimization._UpdateSelectionTree = value;
  33438. },
  33439. enumerable: true,
  33440. configurable: true
  33441. });
  33442. MergeMeshesOptimization._UpdateSelectionTree = false;
  33443. return MergeMeshesOptimization;
  33444. })(SceneOptimization);
  33445. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33446. // Options
  33447. var SceneOptimizerOptions = (function () {
  33448. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33449. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33450. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33451. this.targetFrameRate = targetFrameRate;
  33452. this.trackerDuration = trackerDuration;
  33453. this.optimizations = new Array();
  33454. }
  33455. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33456. var result = new SceneOptimizerOptions(targetFrameRate);
  33457. var priority = 0;
  33458. result.optimizations.push(new MergeMeshesOptimization(priority));
  33459. result.optimizations.push(new ShadowsOptimization(priority));
  33460. result.optimizations.push(new LensFlaresOptimization(priority));
  33461. // Next priority
  33462. priority++;
  33463. result.optimizations.push(new PostProcessesOptimization(priority));
  33464. result.optimizations.push(new ParticlesOptimization(priority));
  33465. // Next priority
  33466. priority++;
  33467. result.optimizations.push(new TextureOptimization(priority, 1024));
  33468. return result;
  33469. };
  33470. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33471. var result = new SceneOptimizerOptions(targetFrameRate);
  33472. var priority = 0;
  33473. result.optimizations.push(new MergeMeshesOptimization(priority));
  33474. result.optimizations.push(new ShadowsOptimization(priority));
  33475. result.optimizations.push(new LensFlaresOptimization(priority));
  33476. // Next priority
  33477. priority++;
  33478. result.optimizations.push(new PostProcessesOptimization(priority));
  33479. result.optimizations.push(new ParticlesOptimization(priority));
  33480. // Next priority
  33481. priority++;
  33482. result.optimizations.push(new TextureOptimization(priority, 512));
  33483. // Next priority
  33484. priority++;
  33485. result.optimizations.push(new RenderTargetsOptimization(priority));
  33486. // Next priority
  33487. priority++;
  33488. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33489. return result;
  33490. };
  33491. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33492. var result = new SceneOptimizerOptions(targetFrameRate);
  33493. var priority = 0;
  33494. result.optimizations.push(new MergeMeshesOptimization(priority));
  33495. result.optimizations.push(new ShadowsOptimization(priority));
  33496. result.optimizations.push(new LensFlaresOptimization(priority));
  33497. // Next priority
  33498. priority++;
  33499. result.optimizations.push(new PostProcessesOptimization(priority));
  33500. result.optimizations.push(new ParticlesOptimization(priority));
  33501. // Next priority
  33502. priority++;
  33503. result.optimizations.push(new TextureOptimization(priority, 256));
  33504. // Next priority
  33505. priority++;
  33506. result.optimizations.push(new RenderTargetsOptimization(priority));
  33507. // Next priority
  33508. priority++;
  33509. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  33510. return result;
  33511. };
  33512. return SceneOptimizerOptions;
  33513. })();
  33514. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  33515. // Scene optimizer tool
  33516. var SceneOptimizer = (function () {
  33517. function SceneOptimizer() {
  33518. }
  33519. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  33520. // TODO: add an epsilon
  33521. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  33522. if (onSuccess) {
  33523. onSuccess();
  33524. }
  33525. return;
  33526. }
  33527. // Apply current level of optimizations
  33528. var allDone = true;
  33529. var noOptimizationApplied = true;
  33530. for (var index = 0; index < options.optimizations.length; index++) {
  33531. var optimization = options.optimizations[index];
  33532. if (optimization.priority === currentPriorityLevel) {
  33533. noOptimizationApplied = false;
  33534. allDone = allDone && optimization.apply(scene);
  33535. }
  33536. }
  33537. // If no optimization was applied, this is a failure :(
  33538. if (noOptimizationApplied) {
  33539. if (onFailure) {
  33540. onFailure();
  33541. }
  33542. return;
  33543. }
  33544. // If all optimizations were done, move to next level
  33545. if (allDone) {
  33546. currentPriorityLevel++;
  33547. }
  33548. // Let's the system running for a specific amount of time before checking FPS
  33549. scene.executeWhenReady(function () {
  33550. setTimeout(function () {
  33551. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  33552. }, options.trackerDuration);
  33553. });
  33554. };
  33555. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  33556. if (!options) {
  33557. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  33558. }
  33559. // Let's the system running for a specific amount of time before checking FPS
  33560. scene.executeWhenReady(function () {
  33561. setTimeout(function () {
  33562. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  33563. }, options.trackerDuration);
  33564. });
  33565. };
  33566. return SceneOptimizer;
  33567. })();
  33568. BABYLON.SceneOptimizer = SceneOptimizer;
  33569. })(BABYLON || (BABYLON = {}));
  33570. var BABYLON;
  33571. (function (BABYLON) {
  33572. var Internals;
  33573. (function (Internals) {
  33574. var MeshLODLevel = (function () {
  33575. function MeshLODLevel(distance, mesh) {
  33576. this.distance = distance;
  33577. this.mesh = mesh;
  33578. }
  33579. return MeshLODLevel;
  33580. })();
  33581. Internals.MeshLODLevel = MeshLODLevel;
  33582. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33583. })(BABYLON || (BABYLON = {}));
  33584. var BABYLON;
  33585. (function (BABYLON) {
  33586. var RawTexture = (function (_super) {
  33587. __extends(RawTexture, _super);
  33588. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33589. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33590. if (invertY === void 0) { invertY = false; }
  33591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33592. _super.call(this, null, scene, !generateMipMaps, invertY);
  33593. this.format = format;
  33594. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33595. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33596. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33597. }
  33598. RawTexture.prototype.update = function (data) {
  33599. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33600. };
  33601. // Statics
  33602. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33603. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33604. if (invertY === void 0) { invertY = false; }
  33605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33606. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33607. };
  33608. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33609. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33610. if (invertY === void 0) { invertY = false; }
  33611. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33612. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33613. };
  33614. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33615. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33616. if (invertY === void 0) { invertY = false; }
  33617. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33618. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33619. };
  33620. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33621. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33622. if (invertY === void 0) { invertY = false; }
  33623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33624. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33625. };
  33626. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33627. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33628. if (invertY === void 0) { invertY = false; }
  33629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33630. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33631. };
  33632. return RawTexture;
  33633. })(BABYLON.Texture);
  33634. BABYLON.RawTexture = RawTexture;
  33635. })(BABYLON || (BABYLON = {}));
  33636. var BABYLON;
  33637. (function (BABYLON) {
  33638. var IndexedVector2 = (function (_super) {
  33639. __extends(IndexedVector2, _super);
  33640. function IndexedVector2(original, index) {
  33641. _super.call(this, original.x, original.y);
  33642. this.index = index;
  33643. }
  33644. return IndexedVector2;
  33645. })(BABYLON.Vector2);
  33646. var PolygonPoints = (function () {
  33647. function PolygonPoints() {
  33648. this.elements = new Array();
  33649. }
  33650. PolygonPoints.prototype.add = function (originalPoints) {
  33651. var _this = this;
  33652. var result = new Array();
  33653. originalPoints.forEach(function (point) {
  33654. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  33655. var newPoint = new IndexedVector2(point, _this.elements.length);
  33656. result.push(newPoint);
  33657. _this.elements.push(newPoint);
  33658. }
  33659. });
  33660. return result;
  33661. };
  33662. PolygonPoints.prototype.computeBounds = function () {
  33663. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33664. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33665. this.elements.forEach(function (point) {
  33666. // x
  33667. if (point.x < lmin.x) {
  33668. lmin.x = point.x;
  33669. }
  33670. else if (point.x > lmax.x) {
  33671. lmax.x = point.x;
  33672. }
  33673. // y
  33674. if (point.y < lmin.y) {
  33675. lmin.y = point.y;
  33676. }
  33677. else if (point.y > lmax.y) {
  33678. lmax.y = point.y;
  33679. }
  33680. });
  33681. return {
  33682. min: lmin,
  33683. max: lmax,
  33684. width: lmax.x - lmin.x,
  33685. height: lmax.y - lmin.y
  33686. };
  33687. };
  33688. return PolygonPoints;
  33689. })();
  33690. var Polygon = (function () {
  33691. function Polygon() {
  33692. }
  33693. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  33694. return [
  33695. new BABYLON.Vector2(xmin, ymin),
  33696. new BABYLON.Vector2(xmax, ymin),
  33697. new BABYLON.Vector2(xmax, ymax),
  33698. new BABYLON.Vector2(xmin, ymax)
  33699. ];
  33700. };
  33701. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  33702. if (cx === void 0) { cx = 0; }
  33703. if (cy === void 0) { cy = 0; }
  33704. if (numberOfSides === void 0) { numberOfSides = 32; }
  33705. var result = new Array();
  33706. var angle = 0;
  33707. var increment = (Math.PI * 2) / numberOfSides;
  33708. for (var i = 0; i < numberOfSides; i++) {
  33709. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  33710. angle -= increment;
  33711. }
  33712. return result;
  33713. };
  33714. Polygon.Parse = function (input) {
  33715. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  33716. var i, result = [];
  33717. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  33718. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  33719. }
  33720. return result;
  33721. };
  33722. Polygon.StartingAt = function (x, y) {
  33723. return BABYLON.Path2.StartingAt(x, y);
  33724. };
  33725. return Polygon;
  33726. })();
  33727. BABYLON.Polygon = Polygon;
  33728. var PolygonMeshBuilder = (function () {
  33729. function PolygonMeshBuilder(name, contours, scene) {
  33730. this._points = new PolygonPoints();
  33731. this._outlinepoints = new PolygonPoints();
  33732. this._holes = [];
  33733. if (!("poly2tri" in window)) {
  33734. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  33735. }
  33736. this._name = name;
  33737. this._scene = scene;
  33738. var points;
  33739. if (contours instanceof BABYLON.Path2) {
  33740. points = contours.getPoints();
  33741. }
  33742. else {
  33743. points = contours;
  33744. }
  33745. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  33746. this._outlinepoints.add(points);
  33747. }
  33748. PolygonMeshBuilder.prototype.addHole = function (hole) {
  33749. this._swctx.addHole(this._points.add(hole));
  33750. var holepoints = new PolygonPoints();
  33751. holepoints.add(hole);
  33752. this._holes.push(holepoints);
  33753. return this;
  33754. };
  33755. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  33756. var _this = this;
  33757. if (updatable === void 0) { updatable = false; }
  33758. var result = new BABYLON.Mesh(this._name, this._scene);
  33759. var normals = [];
  33760. var positions = [];
  33761. var uvs = [];
  33762. var bounds = this._points.computeBounds();
  33763. this._points.elements.forEach(function (p) {
  33764. normals.push(0, 1.0, 0);
  33765. positions.push(p.x, 0, p.y);
  33766. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  33767. });
  33768. var indices = [];
  33769. this._swctx.triangulate();
  33770. this._swctx.getTriangles().forEach(function (triangle) {
  33771. triangle.getPoints().forEach(function (point) {
  33772. indices.push(point.index);
  33773. });
  33774. });
  33775. if (depth > 0) {
  33776. var positionscount = (positions.length / 3); //get the current pointcount
  33777. this._points.elements.forEach(function (p) {
  33778. normals.push(0, -1.0, 0);
  33779. positions.push(p.x, -depth, p.y);
  33780. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  33781. });
  33782. var p1; //we need to change order of point so the triangles are made in the rigth way.
  33783. var p2;
  33784. var poscounter = 0;
  33785. this._swctx.getTriangles().forEach(function (triangle) {
  33786. triangle.getPoints().forEach(function (point) {
  33787. switch (poscounter) {
  33788. case 0:
  33789. p1 = point;
  33790. break;
  33791. case 1:
  33792. p2 = point;
  33793. break;
  33794. case 2:
  33795. indices.push(point.index + positionscount);
  33796. indices.push(p2.index + positionscount);
  33797. indices.push(p1.index + positionscount);
  33798. poscounter = -1;
  33799. break;
  33800. }
  33801. poscounter++;
  33802. //indices.push((<IndexedVector2>point).index + positionscount);
  33803. });
  33804. });
  33805. //Add the sides
  33806. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  33807. this._holes.forEach(function (hole) {
  33808. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  33809. });
  33810. }
  33811. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  33812. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  33813. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  33814. result.setIndices(indices);
  33815. return result;
  33816. };
  33817. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  33818. var StartIndex = positions.length / 3;
  33819. var ulength = 0;
  33820. for (var i = 0; i < points.elements.length; i++) {
  33821. var p = points.elements[i];
  33822. var p1;
  33823. if ((i + 1) > points.elements.length - 1) {
  33824. p1 = points.elements[0];
  33825. }
  33826. else {
  33827. p1 = points.elements[i + 1];
  33828. }
  33829. positions.push(p.x, 0, p.y);
  33830. positions.push(p.x, -depth, p.y);
  33831. positions.push(p1.x, 0, p1.y);
  33832. positions.push(p1.x, -depth, p1.y);
  33833. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  33834. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  33835. var v3 = v2.subtract(v1);
  33836. var v4 = new BABYLON.Vector3(0, 1, 0);
  33837. var vn = BABYLON.Vector3.Cross(v3, v4);
  33838. vn = vn.normalize();
  33839. uvs.push(ulength / bounds.width, 0);
  33840. uvs.push(ulength / bounds.width, 1);
  33841. ulength += v3.length();
  33842. uvs.push((ulength / bounds.width), 0);
  33843. uvs.push((ulength / bounds.width), 1);
  33844. if (!flip) {
  33845. normals.push(-vn.x, -vn.y, -vn.z);
  33846. normals.push(-vn.x, -vn.y, -vn.z);
  33847. normals.push(-vn.x, -vn.y, -vn.z);
  33848. normals.push(-vn.x, -vn.y, -vn.z);
  33849. indices.push(StartIndex);
  33850. indices.push(StartIndex + 1);
  33851. indices.push(StartIndex + 2);
  33852. indices.push(StartIndex + 1);
  33853. indices.push(StartIndex + 3);
  33854. indices.push(StartIndex + 2);
  33855. }
  33856. else {
  33857. normals.push(vn.x, vn.y, vn.z);
  33858. normals.push(vn.x, vn.y, vn.z);
  33859. normals.push(vn.x, vn.y, vn.z);
  33860. normals.push(vn.x, vn.y, vn.z);
  33861. indices.push(StartIndex);
  33862. indices.push(StartIndex + 2);
  33863. indices.push(StartIndex + 1);
  33864. indices.push(StartIndex + 1);
  33865. indices.push(StartIndex + 2);
  33866. indices.push(StartIndex + 3);
  33867. }
  33868. StartIndex += 4;
  33869. }
  33870. ;
  33871. };
  33872. return PolygonMeshBuilder;
  33873. })();
  33874. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  33875. })(BABYLON || (BABYLON = {}));
  33876. var BABYLON;
  33877. (function (BABYLON) {
  33878. var Octree = (function () {
  33879. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  33880. if (maxDepth === void 0) { maxDepth = 2; }
  33881. this.maxDepth = maxDepth;
  33882. this.dynamicContent = new Array();
  33883. this._maxBlockCapacity = maxBlockCapacity || 64;
  33884. this._selectionContent = new BABYLON.SmartArray(1024);
  33885. this._creationFunc = creationFunc;
  33886. }
  33887. // Methods
  33888. Octree.prototype.update = function (worldMin, worldMax, entries) {
  33889. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  33890. };
  33891. Octree.prototype.addMesh = function (entry) {
  33892. for (var index = 0; index < this.blocks.length; index++) {
  33893. var block = this.blocks[index];
  33894. block.addEntry(entry);
  33895. }
  33896. };
  33897. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  33898. this._selectionContent.reset();
  33899. for (var index = 0; index < this.blocks.length; index++) {
  33900. var block = this.blocks[index];
  33901. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  33902. }
  33903. if (allowDuplicate) {
  33904. this._selectionContent.concat(this.dynamicContent);
  33905. }
  33906. else {
  33907. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33908. }
  33909. return this._selectionContent;
  33910. };
  33911. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  33912. this._selectionContent.reset();
  33913. for (var index = 0; index < this.blocks.length; index++) {
  33914. var block = this.blocks[index];
  33915. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  33916. }
  33917. if (allowDuplicate) {
  33918. this._selectionContent.concat(this.dynamicContent);
  33919. }
  33920. else {
  33921. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33922. }
  33923. return this._selectionContent;
  33924. };
  33925. Octree.prototype.intersectsRay = function (ray) {
  33926. this._selectionContent.reset();
  33927. for (var index = 0; index < this.blocks.length; index++) {
  33928. var block = this.blocks[index];
  33929. block.intersectsRay(ray, this._selectionContent);
  33930. }
  33931. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33932. return this._selectionContent;
  33933. };
  33934. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  33935. target.blocks = new Array();
  33936. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  33937. // Segmenting space
  33938. for (var x = 0; x < 2; x++) {
  33939. for (var y = 0; y < 2; y++) {
  33940. for (var z = 0; z < 2; z++) {
  33941. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  33942. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  33943. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  33944. block.addEntries(entries);
  33945. target.blocks.push(block);
  33946. }
  33947. }
  33948. }
  33949. };
  33950. Octree.CreationFuncForMeshes = function (entry, block) {
  33951. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33952. block.entries.push(entry);
  33953. }
  33954. };
  33955. Octree.CreationFuncForSubMeshes = function (entry, block) {
  33956. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33957. block.entries.push(entry);
  33958. }
  33959. };
  33960. return Octree;
  33961. })();
  33962. BABYLON.Octree = Octree;
  33963. })(BABYLON || (BABYLON = {}));
  33964. var BABYLON;
  33965. (function (BABYLON) {
  33966. var OctreeBlock = (function () {
  33967. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  33968. this.entries = new Array();
  33969. this._boundingVectors = new Array();
  33970. this._capacity = capacity;
  33971. this._depth = depth;
  33972. this._maxDepth = maxDepth;
  33973. this._creationFunc = creationFunc;
  33974. this._minPoint = minPoint;
  33975. this._maxPoint = maxPoint;
  33976. this._boundingVectors.push(minPoint.clone());
  33977. this._boundingVectors.push(maxPoint.clone());
  33978. this._boundingVectors.push(minPoint.clone());
  33979. this._boundingVectors[2].x = maxPoint.x;
  33980. this._boundingVectors.push(minPoint.clone());
  33981. this._boundingVectors[3].y = maxPoint.y;
  33982. this._boundingVectors.push(minPoint.clone());
  33983. this._boundingVectors[4].z = maxPoint.z;
  33984. this._boundingVectors.push(maxPoint.clone());
  33985. this._boundingVectors[5].z = minPoint.z;
  33986. this._boundingVectors.push(maxPoint.clone());
  33987. this._boundingVectors[6].x = minPoint.x;
  33988. this._boundingVectors.push(maxPoint.clone());
  33989. this._boundingVectors[7].y = minPoint.y;
  33990. }
  33991. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  33992. // Property
  33993. get: function () {
  33994. return this._capacity;
  33995. },
  33996. enumerable: true,
  33997. configurable: true
  33998. });
  33999. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34000. get: function () {
  34001. return this._minPoint;
  34002. },
  34003. enumerable: true,
  34004. configurable: true
  34005. });
  34006. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34007. get: function () {
  34008. return this._maxPoint;
  34009. },
  34010. enumerable: true,
  34011. configurable: true
  34012. });
  34013. // Methods
  34014. OctreeBlock.prototype.addEntry = function (entry) {
  34015. if (this.blocks) {
  34016. for (var index = 0; index < this.blocks.length; index++) {
  34017. var block = this.blocks[index];
  34018. block.addEntry(entry);
  34019. }
  34020. return;
  34021. }
  34022. this._creationFunc(entry, this);
  34023. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34024. this.createInnerBlocks();
  34025. }
  34026. };
  34027. OctreeBlock.prototype.addEntries = function (entries) {
  34028. for (var index = 0; index < entries.length; index++) {
  34029. var mesh = entries[index];
  34030. this.addEntry(mesh);
  34031. }
  34032. };
  34033. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34034. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34035. if (this.blocks) {
  34036. for (var index = 0; index < this.blocks.length; index++) {
  34037. var block = this.blocks[index];
  34038. block.select(frustumPlanes, selection, allowDuplicate);
  34039. }
  34040. return;
  34041. }
  34042. if (allowDuplicate) {
  34043. selection.concat(this.entries);
  34044. }
  34045. else {
  34046. selection.concatWithNoDuplicate(this.entries);
  34047. }
  34048. }
  34049. };
  34050. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34051. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34052. if (this.blocks) {
  34053. for (var index = 0; index < this.blocks.length; index++) {
  34054. var block = this.blocks[index];
  34055. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34056. }
  34057. return;
  34058. }
  34059. if (allowDuplicate) {
  34060. selection.concat(this.entries);
  34061. }
  34062. else {
  34063. selection.concatWithNoDuplicate(this.entries);
  34064. }
  34065. }
  34066. };
  34067. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34068. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34069. if (this.blocks) {
  34070. for (var index = 0; index < this.blocks.length; index++) {
  34071. var block = this.blocks[index];
  34072. block.intersectsRay(ray, selection);
  34073. }
  34074. return;
  34075. }
  34076. selection.concatWithNoDuplicate(this.entries);
  34077. }
  34078. };
  34079. OctreeBlock.prototype.createInnerBlocks = function () {
  34080. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34081. };
  34082. return OctreeBlock;
  34083. })();
  34084. BABYLON.OctreeBlock = OctreeBlock;
  34085. })(BABYLON || (BABYLON = {}));
  34086. var BABYLON;
  34087. (function (BABYLON) {
  34088. var BlurPostProcess = (function (_super) {
  34089. __extends(BlurPostProcess, _super);
  34090. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34091. var _this = this;
  34092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34093. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34094. this.direction = direction;
  34095. this.blurWidth = blurWidth;
  34096. this.onApply = function (effect) {
  34097. effect.setFloat2("screenSize", _this.width, _this.height);
  34098. effect.setVector2("direction", _this.direction);
  34099. effect.setFloat("blurWidth", _this.blurWidth);
  34100. };
  34101. }
  34102. return BlurPostProcess;
  34103. })(BABYLON.PostProcess);
  34104. BABYLON.BlurPostProcess = BlurPostProcess;
  34105. })(BABYLON || (BABYLON = {}));
  34106. var BABYLON;
  34107. (function (BABYLON) {
  34108. var RefractionPostProcess = (function (_super) {
  34109. __extends(RefractionPostProcess, _super);
  34110. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34111. var _this = this;
  34112. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34113. this.color = color;
  34114. this.depth = depth;
  34115. this.colorLevel = colorLevel;
  34116. this.onActivate = function (cam) {
  34117. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34118. };
  34119. this.onApply = function (effect) {
  34120. effect.setColor3("baseColor", _this.color);
  34121. effect.setFloat("depth", _this.depth);
  34122. effect.setFloat("colorLevel", _this.colorLevel);
  34123. effect.setTexture("refractionSampler", _this._refRexture);
  34124. };
  34125. }
  34126. // Methods
  34127. RefractionPostProcess.prototype.dispose = function (camera) {
  34128. if (this._refRexture) {
  34129. this._refRexture.dispose();
  34130. }
  34131. _super.prototype.dispose.call(this, camera);
  34132. };
  34133. return RefractionPostProcess;
  34134. })(BABYLON.PostProcess);
  34135. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34136. })(BABYLON || (BABYLON = {}));
  34137. var BABYLON;
  34138. (function (BABYLON) {
  34139. var BlackAndWhitePostProcess = (function (_super) {
  34140. __extends(BlackAndWhitePostProcess, _super);
  34141. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34142. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34143. }
  34144. return BlackAndWhitePostProcess;
  34145. })(BABYLON.PostProcess);
  34146. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34147. })(BABYLON || (BABYLON = {}));
  34148. var BABYLON;
  34149. (function (BABYLON) {
  34150. var ConvolutionPostProcess = (function (_super) {
  34151. __extends(ConvolutionPostProcess, _super);
  34152. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34153. var _this = this;
  34154. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34155. this.kernel = kernel;
  34156. this.onApply = function (effect) {
  34157. effect.setFloat2("screenSize", _this.width, _this.height);
  34158. effect.setArray("kernel", _this.kernel);
  34159. };
  34160. }
  34161. // Statics
  34162. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34163. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34164. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34165. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34166. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34167. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34168. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34169. return ConvolutionPostProcess;
  34170. })(BABYLON.PostProcess);
  34171. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34172. })(BABYLON || (BABYLON = {}));
  34173. var BABYLON;
  34174. (function (BABYLON) {
  34175. var FilterPostProcess = (function (_super) {
  34176. __extends(FilterPostProcess, _super);
  34177. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34178. var _this = this;
  34179. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34180. this.kernelMatrix = kernelMatrix;
  34181. this.onApply = function (effect) {
  34182. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34183. };
  34184. }
  34185. return FilterPostProcess;
  34186. })(BABYLON.PostProcess);
  34187. BABYLON.FilterPostProcess = FilterPostProcess;
  34188. })(BABYLON || (BABYLON = {}));
  34189. var BABYLON;
  34190. (function (BABYLON) {
  34191. var FxaaPostProcess = (function (_super) {
  34192. __extends(FxaaPostProcess, _super);
  34193. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34194. var _this = this;
  34195. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34196. this.onSizeChanged = function () {
  34197. _this.texelWidth = 1.0 / _this.width;
  34198. _this.texelHeight = 1.0 / _this.height;
  34199. };
  34200. this.onApply = function (effect) {
  34201. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34202. };
  34203. }
  34204. return FxaaPostProcess;
  34205. })(BABYLON.PostProcess);
  34206. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34207. })(BABYLON || (BABYLON = {}));
  34208. var BABYLON;
  34209. (function (BABYLON) {
  34210. var StereoscopicInterlacePostProcess = (function (_super) {
  34211. __extends(StereoscopicInterlacePostProcess, _super);
  34212. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34213. var _this = this;
  34214. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34215. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34216. this.onSizeChanged = function () {
  34217. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34218. };
  34219. this.onApply = function (effect) {
  34220. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34221. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34222. };
  34223. }
  34224. return StereoscopicInterlacePostProcess;
  34225. })(BABYLON.PostProcess);
  34226. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34227. })(BABYLON || (BABYLON = {}));
  34228. var BABYLON;
  34229. (function (BABYLON) {
  34230. var LensFlare = (function () {
  34231. function LensFlare(size, position, color, imgUrl, system) {
  34232. this.size = size;
  34233. this.position = position;
  34234. this.dispose = function () {
  34235. if (this.texture) {
  34236. this.texture.dispose();
  34237. }
  34238. // Remove from scene
  34239. var index = this._system.lensFlares.indexOf(this);
  34240. this._system.lensFlares.splice(index, 1);
  34241. };
  34242. this.color = color || new BABYLON.Color3(1, 1, 1);
  34243. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34244. this._system = system;
  34245. system.lensFlares.push(this);
  34246. }
  34247. return LensFlare;
  34248. })();
  34249. BABYLON.LensFlare = LensFlare;
  34250. })(BABYLON || (BABYLON = {}));
  34251. var BABYLON;
  34252. (function (BABYLON) {
  34253. var LensFlareSystem = (function () {
  34254. function LensFlareSystem(name, emitter, scene) {
  34255. this.name = name;
  34256. this.lensFlares = new Array();
  34257. this.borderLimit = 300;
  34258. this.layerMask = 0x0FFFFFFF;
  34259. this._vertexDeclaration = [2];
  34260. this._vertexStrideSize = 2 * 4;
  34261. this._isEnabled = true;
  34262. this._scene = scene;
  34263. this._emitter = emitter;
  34264. scene.lensFlareSystems.push(this);
  34265. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34266. // VBO
  34267. var vertices = [];
  34268. vertices.push(1, 1);
  34269. vertices.push(-1, 1);
  34270. vertices.push(-1, -1);
  34271. vertices.push(1, -1);
  34272. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34273. // Indices
  34274. var indices = [];
  34275. indices.push(0);
  34276. indices.push(1);
  34277. indices.push(2);
  34278. indices.push(0);
  34279. indices.push(2);
  34280. indices.push(3);
  34281. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34282. // Effects
  34283. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34284. }
  34285. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34286. get: function () {
  34287. return this._isEnabled;
  34288. },
  34289. set: function (value) {
  34290. this._isEnabled = value;
  34291. },
  34292. enumerable: true,
  34293. configurable: true
  34294. });
  34295. LensFlareSystem.prototype.getScene = function () {
  34296. return this._scene;
  34297. };
  34298. LensFlareSystem.prototype.getEmitter = function () {
  34299. return this._emitter;
  34300. };
  34301. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34302. this._emitter = newEmitter;
  34303. };
  34304. LensFlareSystem.prototype.getEmitterPosition = function () {
  34305. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34306. };
  34307. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34308. var position = this.getEmitterPosition();
  34309. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34310. this._positionX = position.x;
  34311. this._positionY = position.y;
  34312. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34313. if (position.z > 0) {
  34314. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34315. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34316. return true;
  34317. }
  34318. }
  34319. return false;
  34320. };
  34321. LensFlareSystem.prototype._isVisible = function () {
  34322. if (!this._isEnabled) {
  34323. return false;
  34324. }
  34325. var emitterPosition = this.getEmitterPosition();
  34326. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34327. var distance = direction.length();
  34328. direction.normalize();
  34329. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34330. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34331. return !pickInfo.hit || pickInfo.distance > distance;
  34332. };
  34333. LensFlareSystem.prototype.render = function () {
  34334. if (!this._effect.isReady())
  34335. return false;
  34336. var engine = this._scene.getEngine();
  34337. var viewport = this._scene.activeCamera.viewport;
  34338. var globalViewport = viewport.toScreenGlobal(engine);
  34339. // Position
  34340. if (!this.computeEffectivePosition(globalViewport)) {
  34341. return false;
  34342. }
  34343. // Visibility
  34344. if (!this._isVisible()) {
  34345. return false;
  34346. }
  34347. // Intensity
  34348. var awayX;
  34349. var awayY;
  34350. if (this._positionX < this.borderLimit + globalViewport.x) {
  34351. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34352. }
  34353. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34354. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34355. }
  34356. else {
  34357. awayX = 0;
  34358. }
  34359. if (this._positionY < this.borderLimit + globalViewport.y) {
  34360. awayY = this.borderLimit + globalViewport.y - this._positionY;
  34361. }
  34362. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  34363. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  34364. }
  34365. else {
  34366. awayY = 0;
  34367. }
  34368. var away = (awayX > awayY) ? awayX : awayY;
  34369. if (away > this.borderLimit) {
  34370. away = this.borderLimit;
  34371. }
  34372. var intensity = 1.0 - (away / this.borderLimit);
  34373. if (intensity < 0) {
  34374. return false;
  34375. }
  34376. if (intensity > 1.0) {
  34377. intensity = 1.0;
  34378. }
  34379. // Position
  34380. var centerX = globalViewport.x + globalViewport.width / 2;
  34381. var centerY = globalViewport.y + globalViewport.height / 2;
  34382. var distX = centerX - this._positionX;
  34383. var distY = centerY - this._positionY;
  34384. // Effects
  34385. engine.enableEffect(this._effect);
  34386. engine.setState(false);
  34387. engine.setDepthBuffer(false);
  34388. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34389. // VBOs
  34390. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34391. // Flares
  34392. for (var index = 0; index < this.lensFlares.length; index++) {
  34393. var flare = this.lensFlares[index];
  34394. var x = centerX - (distX * flare.position);
  34395. var y = centerY - (distY * flare.position);
  34396. var cw = flare.size;
  34397. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34398. var cx = 2 * (x / globalViewport.width) - 1.0;
  34399. var cy = 1.0 - 2 * (y / globalViewport.height);
  34400. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34401. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34402. // Texture
  34403. this._effect.setTexture("textureSampler", flare.texture);
  34404. // Color
  34405. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34406. // Draw order
  34407. engine.draw(true, 0, 6);
  34408. }
  34409. engine.setDepthBuffer(true);
  34410. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34411. return true;
  34412. };
  34413. LensFlareSystem.prototype.dispose = function () {
  34414. if (this._vertexBuffer) {
  34415. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34416. this._vertexBuffer = null;
  34417. }
  34418. if (this._indexBuffer) {
  34419. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34420. this._indexBuffer = null;
  34421. }
  34422. while (this.lensFlares.length) {
  34423. this.lensFlares[0].dispose();
  34424. }
  34425. // Remove from scene
  34426. var index = this._scene.lensFlareSystems.indexOf(this);
  34427. this._scene.lensFlareSystems.splice(index, 1);
  34428. };
  34429. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34430. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34431. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34432. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34433. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34434. var parsedFlare = parsedLensFlareSystem.flares[index];
  34435. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34436. }
  34437. return lensFlareSystem;
  34438. };
  34439. LensFlareSystem.prototype.serialize = function () {
  34440. var serializationObject = {};
  34441. serializationObject.emitterId = this.getEmitter().id;
  34442. serializationObject.borderLimit = this.borderLimit;
  34443. serializationObject.flares = [];
  34444. for (var index = 0; index < this.lensFlares.length; index++) {
  34445. var flare = this.lensFlares[index];
  34446. serializationObject.flares.push({
  34447. size: flare.size,
  34448. position: flare.position,
  34449. color: flare.color.asArray(),
  34450. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34451. });
  34452. }
  34453. return serializationObject;
  34454. };
  34455. return LensFlareSystem;
  34456. })();
  34457. BABYLON.LensFlareSystem = LensFlareSystem;
  34458. })(BABYLON || (BABYLON = {}));
  34459. var BABYLON;
  34460. (function (BABYLON) {
  34461. // We're mainly based on the logic defined into the FreeCamera code
  34462. var DeviceOrientationCamera = (function (_super) {
  34463. __extends(DeviceOrientationCamera, _super);
  34464. function DeviceOrientationCamera(name, position, scene) {
  34465. var _this = this;
  34466. _super.call(this, name, position, scene);
  34467. this._offsetX = null;
  34468. this._offsetY = null;
  34469. this._orientationGamma = 0;
  34470. this._orientationBeta = 0;
  34471. this._initialOrientationGamma = 0;
  34472. this._initialOrientationBeta = 0;
  34473. this.angularSensibility = 10000.0;
  34474. this.moveSensibility = 50.0;
  34475. window.addEventListener("resize", function () {
  34476. _this._initialOrientationGamma = null;
  34477. }, false);
  34478. }
  34479. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34480. var _this = this;
  34481. if (this._attachedCanvas) {
  34482. return;
  34483. }
  34484. this._attachedCanvas = canvas;
  34485. if (!this._orientationChanged) {
  34486. this._orientationChanged = function (evt) {
  34487. if (!_this._initialOrientationGamma) {
  34488. _this._initialOrientationGamma = evt.gamma;
  34489. _this._initialOrientationBeta = evt.beta;
  34490. }
  34491. _this._orientationGamma = evt.gamma;
  34492. _this._orientationBeta = evt.beta;
  34493. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34494. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34495. };
  34496. }
  34497. window.addEventListener("deviceorientation", this._orientationChanged);
  34498. };
  34499. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34500. if (this._attachedCanvas !== canvas) {
  34501. return;
  34502. }
  34503. window.removeEventListener("deviceorientation", this._orientationChanged);
  34504. this._attachedCanvas = null;
  34505. this._orientationGamma = 0;
  34506. this._orientationBeta = 0;
  34507. this._initialOrientationGamma = 0;
  34508. this._initialOrientationBeta = 0;
  34509. };
  34510. DeviceOrientationCamera.prototype._checkInputs = function () {
  34511. if (!this._offsetX) {
  34512. return;
  34513. }
  34514. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  34515. var speed = this._computeLocalCameraSpeed();
  34516. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  34517. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  34518. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  34519. _super.prototype._checkInputs.call(this);
  34520. };
  34521. DeviceOrientationCamera.prototype.getTypeName = function () {
  34522. return "DeviceOrientationCamera";
  34523. };
  34524. __decorate([
  34525. BABYLON.serialize()
  34526. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  34527. __decorate([
  34528. BABYLON.serialize()
  34529. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  34530. return DeviceOrientationCamera;
  34531. })(BABYLON.FreeCamera);
  34532. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  34533. })(BABYLON || (BABYLON = {}));
  34534. var BABYLON;
  34535. (function (BABYLON) {
  34536. var Analyser = (function () {
  34537. function Analyser(scene) {
  34538. this.SMOOTHING = 0.75;
  34539. this.FFT_SIZE = 512;
  34540. this.BARGRAPHAMPLITUDE = 256;
  34541. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34542. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34543. this._scene = scene;
  34544. this._audioEngine = BABYLON.Engine.audioEngine;
  34545. if (this._audioEngine.canUseWebAudio) {
  34546. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34547. this._webAudioAnalyser.minDecibels = -140;
  34548. this._webAudioAnalyser.maxDecibels = 0;
  34549. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34550. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34551. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34552. }
  34553. }
  34554. Analyser.prototype.getFrequencyBinCount = function () {
  34555. if (this._audioEngine.canUseWebAudio) {
  34556. return this._webAudioAnalyser.frequencyBinCount;
  34557. }
  34558. else {
  34559. return 0;
  34560. }
  34561. };
  34562. Analyser.prototype.getByteFrequencyData = function () {
  34563. if (this._audioEngine.canUseWebAudio) {
  34564. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34565. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34566. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34567. }
  34568. return this._byteFreqs;
  34569. };
  34570. Analyser.prototype.getByteTimeDomainData = function () {
  34571. if (this._audioEngine.canUseWebAudio) {
  34572. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34573. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34574. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34575. }
  34576. return this._byteTime;
  34577. };
  34578. Analyser.prototype.getFloatFrequencyData = function () {
  34579. if (this._audioEngine.canUseWebAudio) {
  34580. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34581. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34582. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34583. }
  34584. return this._floatFreqs;
  34585. };
  34586. Analyser.prototype.drawDebugCanvas = function () {
  34587. var _this = this;
  34588. if (this._audioEngine.canUseWebAudio) {
  34589. if (!this._debugCanvas) {
  34590. this._debugCanvas = document.createElement("canvas");
  34591. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34592. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34593. this._debugCanvas.style.position = "absolute";
  34594. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34595. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34596. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34597. document.body.appendChild(this._debugCanvas);
  34598. this._registerFunc = function () {
  34599. _this.drawDebugCanvas();
  34600. };
  34601. this._scene.registerBeforeRender(this._registerFunc);
  34602. }
  34603. if (this._registerFunc) {
  34604. var workingArray = this.getByteFrequencyData();
  34605. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34606. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34607. // Draw the frequency domain chart.
  34608. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34609. var value = workingArray[i];
  34610. var percent = value / this.BARGRAPHAMPLITUDE;
  34611. var height = this.DEBUGCANVASSIZE.height * percent;
  34612. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34613. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34614. var hue = i / this.getFrequencyBinCount() * 360;
  34615. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34616. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34617. }
  34618. }
  34619. }
  34620. };
  34621. Analyser.prototype.stopDebugCanvas = function () {
  34622. if (this._debugCanvas) {
  34623. this._scene.unregisterBeforeRender(this._registerFunc);
  34624. this._registerFunc = null;
  34625. document.body.removeChild(this._debugCanvas);
  34626. this._debugCanvas = null;
  34627. this._debugCanvasContext = null;
  34628. }
  34629. };
  34630. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34631. if (this._audioEngine.canUseWebAudio) {
  34632. inputAudioNode.connect(this._webAudioAnalyser);
  34633. this._webAudioAnalyser.connect(outputAudioNode);
  34634. }
  34635. };
  34636. Analyser.prototype.dispose = function () {
  34637. if (this._audioEngine.canUseWebAudio) {
  34638. this._webAudioAnalyser.disconnect();
  34639. }
  34640. };
  34641. return Analyser;
  34642. })();
  34643. BABYLON.Analyser = Analyser;
  34644. })(BABYLON || (BABYLON = {}));
  34645. var BABYLON;
  34646. (function (BABYLON) {
  34647. var AudioEngine = (function () {
  34648. function AudioEngine() {
  34649. this._audioContext = null;
  34650. this._audioContextInitialized = false;
  34651. this.canUseWebAudio = false;
  34652. this.WarnedWebAudioUnsupported = false;
  34653. this.unlocked = false;
  34654. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34655. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34656. this.canUseWebAudio = true;
  34657. }
  34658. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34659. this._unlockiOSaudio();
  34660. }
  34661. else {
  34662. this.unlocked = true;
  34663. }
  34664. }
  34665. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34666. get: function () {
  34667. if (!this._audioContextInitialized) {
  34668. this._initializeAudioContext();
  34669. }
  34670. return this._audioContext;
  34671. },
  34672. enumerable: true,
  34673. configurable: true
  34674. });
  34675. AudioEngine.prototype._unlockiOSaudio = function () {
  34676. var _this = this;
  34677. var unlockaudio = function () {
  34678. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34679. var source = _this.audioContext.createBufferSource();
  34680. source.buffer = buffer;
  34681. source.connect(_this.audioContext.destination);
  34682. source.start(0);
  34683. setTimeout(function () {
  34684. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34685. _this.unlocked = true;
  34686. window.removeEventListener('touchend', unlockaudio, false);
  34687. if (_this.onAudioUnlocked) {
  34688. _this.onAudioUnlocked();
  34689. }
  34690. }
  34691. }, 0);
  34692. };
  34693. window.addEventListener('touchend', unlockaudio, false);
  34694. };
  34695. AudioEngine.prototype._initializeAudioContext = function () {
  34696. try {
  34697. if (this.canUseWebAudio) {
  34698. this._audioContext = new AudioContext();
  34699. // create a global volume gain node
  34700. this.masterGain = this._audioContext.createGain();
  34701. this.masterGain.gain.value = 1;
  34702. this.masterGain.connect(this._audioContext.destination);
  34703. this._audioContextInitialized = true;
  34704. }
  34705. }
  34706. catch (e) {
  34707. this.canUseWebAudio = false;
  34708. BABYLON.Tools.Error("Web Audio: " + e.message);
  34709. }
  34710. };
  34711. AudioEngine.prototype.dispose = function () {
  34712. if (this.canUseWebAudio && this._audioContextInitialized) {
  34713. if (this._connectedAnalyser) {
  34714. this._connectedAnalyser.stopDebugCanvas();
  34715. this._connectedAnalyser.dispose();
  34716. this.masterGain.disconnect();
  34717. this.masterGain.connect(this._audioContext.destination);
  34718. this._connectedAnalyser = null;
  34719. }
  34720. this.masterGain.gain.value = 1;
  34721. }
  34722. this.WarnedWebAudioUnsupported = false;
  34723. };
  34724. AudioEngine.prototype.getGlobalVolume = function () {
  34725. if (this.canUseWebAudio && this._audioContextInitialized) {
  34726. return this.masterGain.gain.value;
  34727. }
  34728. else {
  34729. return -1;
  34730. }
  34731. };
  34732. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34733. if (this.canUseWebAudio && this._audioContextInitialized) {
  34734. this.masterGain.gain.value = newVolume;
  34735. }
  34736. };
  34737. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34738. if (this._connectedAnalyser) {
  34739. this._connectedAnalyser.stopDebugCanvas();
  34740. }
  34741. if (this.canUseWebAudio && this._audioContextInitialized) {
  34742. this._connectedAnalyser = analyser;
  34743. this.masterGain.disconnect();
  34744. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34745. }
  34746. };
  34747. return AudioEngine;
  34748. })();
  34749. BABYLON.AudioEngine = AudioEngine;
  34750. })(BABYLON || (BABYLON = {}));
  34751. var BABYLON;
  34752. (function (BABYLON) {
  34753. var Sound = (function () {
  34754. /**
  34755. * Create a sound and attach it to a scene
  34756. * @param name Name of your sound
  34757. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34758. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34759. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34760. */
  34761. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34762. var _this = this;
  34763. this.autoplay = false;
  34764. this.loop = false;
  34765. this.useCustomAttenuation = false;
  34766. this.spatialSound = false;
  34767. this.refDistance = 1;
  34768. this.rolloffFactor = 1;
  34769. this.maxDistance = 100;
  34770. this.distanceModel = "linear";
  34771. this._panningModel = "equalpower";
  34772. this._playbackRate = 1;
  34773. this._streaming = false;
  34774. this._startTime = 0;
  34775. this._startOffset = 0;
  34776. this._position = BABYLON.Vector3.Zero();
  34777. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34778. this._volume = 1;
  34779. this._isLoaded = false;
  34780. this._isReadyToPlay = false;
  34781. this.isPlaying = false;
  34782. this.isPaused = false;
  34783. this._isDirectional = false;
  34784. // Used if you'd like to create a directional sound.
  34785. // If not set, the sound will be omnidirectional
  34786. this._coneInnerAngle = 360;
  34787. this._coneOuterAngle = 360;
  34788. this._coneOuterGain = 0;
  34789. this._isOutputConnected = false;
  34790. this.name = name;
  34791. this._scene = scene;
  34792. this._readyToPlayCallback = readyToPlayCallback;
  34793. // Default custom attenuation function is a linear attenuation
  34794. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34795. if (currentDistance < maxDistance) {
  34796. return currentVolume * (1 - currentDistance / maxDistance);
  34797. }
  34798. else {
  34799. return 0;
  34800. }
  34801. };
  34802. if (options) {
  34803. this.autoplay = options.autoplay || false;
  34804. this.loop = options.loop || false;
  34805. // if volume === 0, we need another way to check this option
  34806. if (options.volume !== undefined) {
  34807. this._volume = options.volume;
  34808. }
  34809. this.spatialSound = options.spatialSound || false;
  34810. this.maxDistance = options.maxDistance || 100;
  34811. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34812. this.rolloffFactor = options.rolloffFactor || 1;
  34813. this.refDistance = options.refDistance || 1;
  34814. this.distanceModel = options.distanceModel || "linear";
  34815. this._playbackRate = options.playbackRate || 1;
  34816. this._streaming = options.streaming || false;
  34817. }
  34818. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34819. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34820. this._soundGain.gain.value = this._volume;
  34821. this._inputAudioNode = this._soundGain;
  34822. this._ouputAudioNode = this._soundGain;
  34823. if (this.spatialSound) {
  34824. this._createSpatialParameters();
  34825. }
  34826. this._scene.mainSoundTrack.AddSound(this);
  34827. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34828. if (urlOrArrayBuffer) {
  34829. // If it's an URL
  34830. if (typeof (urlOrArrayBuffer) === "string") {
  34831. // Loading sound using XHR2
  34832. if (!this._streaming) {
  34833. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34834. }
  34835. else {
  34836. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34837. this._htmlAudioElement.controls = false;
  34838. this._htmlAudioElement.loop = this.loop;
  34839. this._htmlAudioElement.crossOrigin = "anonymous";
  34840. this._htmlAudioElement.preload = "auto";
  34841. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34842. _this._isReadyToPlay = true;
  34843. if (_this.autoplay) {
  34844. _this.play();
  34845. }
  34846. if (_this._readyToPlayCallback) {
  34847. _this._readyToPlayCallback();
  34848. }
  34849. });
  34850. document.body.appendChild(this._htmlAudioElement);
  34851. }
  34852. }
  34853. else {
  34854. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34855. if (urlOrArrayBuffer.byteLength > 0) {
  34856. this._soundLoaded(urlOrArrayBuffer);
  34857. }
  34858. }
  34859. else {
  34860. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34861. }
  34862. }
  34863. }
  34864. }
  34865. else {
  34866. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34867. this._scene.mainSoundTrack.AddSound(this);
  34868. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34869. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34870. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34871. }
  34872. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34873. if (this._readyToPlayCallback) {
  34874. window.setTimeout(function () {
  34875. _this._readyToPlayCallback();
  34876. }, 1000);
  34877. }
  34878. }
  34879. }
  34880. Sound.prototype.dispose = function () {
  34881. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34882. if (this.isPlaying) {
  34883. this.stop();
  34884. }
  34885. this._isReadyToPlay = false;
  34886. if (this.soundTrackId === -1) {
  34887. this._scene.mainSoundTrack.RemoveSound(this);
  34888. }
  34889. else {
  34890. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34891. }
  34892. if (this._soundGain) {
  34893. this._soundGain.disconnect();
  34894. this._soundGain = null;
  34895. }
  34896. if (this._soundPanner) {
  34897. this._soundPanner.disconnect();
  34898. this._soundPanner = null;
  34899. }
  34900. if (this._soundSource) {
  34901. this._soundSource.disconnect();
  34902. this._soundSource = null;
  34903. }
  34904. this._audioBuffer = null;
  34905. if (this._htmlAudioElement) {
  34906. this._htmlAudioElement.pause();
  34907. this._htmlAudioElement.src = "";
  34908. document.body.removeChild(this._htmlAudioElement);
  34909. }
  34910. if (this._connectedMesh) {
  34911. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34912. this._connectedMesh = null;
  34913. }
  34914. }
  34915. };
  34916. Sound.prototype._soundLoaded = function (audioData) {
  34917. var _this = this;
  34918. this._isLoaded = true;
  34919. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34920. _this._audioBuffer = buffer;
  34921. _this._isReadyToPlay = true;
  34922. if (_this.autoplay) {
  34923. _this.play();
  34924. }
  34925. if (_this._readyToPlayCallback) {
  34926. _this._readyToPlayCallback();
  34927. }
  34928. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34929. };
  34930. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34931. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34932. this._audioBuffer = audioBuffer;
  34933. this._isReadyToPlay = true;
  34934. }
  34935. };
  34936. Sound.prototype.updateOptions = function (options) {
  34937. if (options) {
  34938. this.loop = options.loop || this.loop;
  34939. this.maxDistance = options.maxDistance || this.maxDistance;
  34940. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34941. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34942. this.refDistance = options.refDistance || this.refDistance;
  34943. this.distanceModel = options.distanceModel || this.distanceModel;
  34944. this._playbackRate = options.playbackRate || this._playbackRate;
  34945. this._updateSpatialParameters();
  34946. if (this.isPlaying) {
  34947. if (this._streaming) {
  34948. this._htmlAudioElement.playbackRate = this._playbackRate;
  34949. }
  34950. else {
  34951. this._soundSource.playbackRate.value = this._playbackRate;
  34952. }
  34953. }
  34954. }
  34955. };
  34956. Sound.prototype._createSpatialParameters = function () {
  34957. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34958. if (this._scene.headphone) {
  34959. this._panningModel = "HRTF";
  34960. }
  34961. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34962. this._updateSpatialParameters();
  34963. this._soundPanner.connect(this._ouputAudioNode);
  34964. this._inputAudioNode = this._soundPanner;
  34965. }
  34966. };
  34967. Sound.prototype._updateSpatialParameters = function () {
  34968. if (this.spatialSound) {
  34969. if (this.useCustomAttenuation) {
  34970. // Tricks to disable in a way embedded Web Audio attenuation
  34971. this._soundPanner.distanceModel = "linear";
  34972. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34973. this._soundPanner.refDistance = 1;
  34974. this._soundPanner.rolloffFactor = 1;
  34975. this._soundPanner.panningModel = this._panningModel;
  34976. }
  34977. else {
  34978. this._soundPanner.distanceModel = this.distanceModel;
  34979. this._soundPanner.maxDistance = this.maxDistance;
  34980. this._soundPanner.refDistance = this.refDistance;
  34981. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34982. this._soundPanner.panningModel = this._panningModel;
  34983. }
  34984. }
  34985. };
  34986. Sound.prototype.switchPanningModelToHRTF = function () {
  34987. this._panningModel = "HRTF";
  34988. this._switchPanningModel();
  34989. };
  34990. Sound.prototype.switchPanningModelToEqualPower = function () {
  34991. this._panningModel = "equalpower";
  34992. this._switchPanningModel();
  34993. };
  34994. Sound.prototype._switchPanningModel = function () {
  34995. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34996. this._soundPanner.panningModel = this._panningModel;
  34997. }
  34998. };
  34999. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35000. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35001. if (this._isOutputConnected) {
  35002. this._ouputAudioNode.disconnect();
  35003. }
  35004. this._ouputAudioNode.connect(soundTrackAudioNode);
  35005. this._isOutputConnected = true;
  35006. }
  35007. };
  35008. /**
  35009. * Transform this sound into a directional source
  35010. * @param coneInnerAngle Size of the inner cone in degree
  35011. * @param coneOuterAngle Size of the outer cone in degree
  35012. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35013. */
  35014. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35015. if (coneOuterAngle < coneInnerAngle) {
  35016. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35017. return;
  35018. }
  35019. this._coneInnerAngle = coneInnerAngle;
  35020. this._coneOuterAngle = coneOuterAngle;
  35021. this._coneOuterGain = coneOuterGain;
  35022. this._isDirectional = true;
  35023. if (this.isPlaying && this.loop) {
  35024. this.stop();
  35025. this.play();
  35026. }
  35027. };
  35028. Sound.prototype.setPosition = function (newPosition) {
  35029. this._position = newPosition;
  35030. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35031. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35032. }
  35033. };
  35034. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35035. this._localDirection = newLocalDirection;
  35036. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35037. this._updateDirection();
  35038. }
  35039. };
  35040. Sound.prototype._updateDirection = function () {
  35041. var mat = this._connectedMesh.getWorldMatrix();
  35042. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35043. direction.normalize();
  35044. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35045. };
  35046. Sound.prototype.updateDistanceFromListener = function () {
  35047. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35048. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35049. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35050. }
  35051. };
  35052. Sound.prototype.setAttenuationFunction = function (callback) {
  35053. this._customAttenuationFunction = callback;
  35054. };
  35055. /**
  35056. * Play the sound
  35057. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35058. */
  35059. Sound.prototype.play = function (time) {
  35060. var _this = this;
  35061. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35062. try {
  35063. if (this._startOffset < 0) {
  35064. time = -this._startOffset;
  35065. this._startOffset = 0;
  35066. }
  35067. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35068. if (!this._soundSource || !this._streamingSource) {
  35069. if (this.spatialSound) {
  35070. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35071. if (this._isDirectional) {
  35072. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35073. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35074. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35075. if (this._connectedMesh) {
  35076. this._updateDirection();
  35077. }
  35078. else {
  35079. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35080. }
  35081. }
  35082. }
  35083. }
  35084. if (this._streaming) {
  35085. if (!this._streamingSource) {
  35086. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35087. this._htmlAudioElement.onended = function () { _this._onended(); };
  35088. this._htmlAudioElement.playbackRate = this._playbackRate;
  35089. }
  35090. this._streamingSource.disconnect();
  35091. this._streamingSource.connect(this._inputAudioNode);
  35092. this._htmlAudioElement.play();
  35093. }
  35094. else {
  35095. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35096. this._soundSource.buffer = this._audioBuffer;
  35097. this._soundSource.connect(this._inputAudioNode);
  35098. this._soundSource.loop = this.loop;
  35099. this._soundSource.playbackRate.value = this._playbackRate;
  35100. this._soundSource.onended = function () { _this._onended(); };
  35101. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  35102. }
  35103. this._startTime = startTime;
  35104. this.isPlaying = true;
  35105. this.isPaused = false;
  35106. }
  35107. catch (ex) {
  35108. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35109. }
  35110. }
  35111. };
  35112. Sound.prototype._onended = function () {
  35113. this.isPlaying = false;
  35114. if (this.onended) {
  35115. this.onended();
  35116. }
  35117. };
  35118. /**
  35119. * Stop the sound
  35120. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35121. */
  35122. Sound.prototype.stop = function (time) {
  35123. if (this.isPlaying) {
  35124. if (this._streaming) {
  35125. this._htmlAudioElement.pause();
  35126. // Test needed for Firefox or it will generate an Invalid State Error
  35127. if (this._htmlAudioElement.currentTime > 0) {
  35128. this._htmlAudioElement.currentTime = 0;
  35129. }
  35130. }
  35131. else {
  35132. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35133. this._soundSource.stop(stopTime);
  35134. if (!this.isPaused) {
  35135. this._startOffset = 0;
  35136. }
  35137. }
  35138. this.isPlaying = false;
  35139. }
  35140. };
  35141. Sound.prototype.pause = function () {
  35142. if (this.isPlaying) {
  35143. this.isPaused = true;
  35144. if (this._streaming) {
  35145. this._htmlAudioElement.pause();
  35146. }
  35147. else {
  35148. this.stop(0);
  35149. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35150. }
  35151. }
  35152. };
  35153. Sound.prototype.setVolume = function (newVolume, time) {
  35154. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35155. if (time) {
  35156. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35157. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35158. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35159. }
  35160. else {
  35161. this._soundGain.gain.value = newVolume;
  35162. }
  35163. }
  35164. this._volume = newVolume;
  35165. };
  35166. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35167. this._playbackRate = newPlaybackRate;
  35168. if (this.isPlaying) {
  35169. if (this._streaming) {
  35170. this._htmlAudioElement.playbackRate = this._playbackRate;
  35171. }
  35172. else {
  35173. this._soundSource.playbackRate.value = this._playbackRate;
  35174. }
  35175. }
  35176. };
  35177. Sound.prototype.getVolume = function () {
  35178. return this._volume;
  35179. };
  35180. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35181. var _this = this;
  35182. if (this._connectedMesh) {
  35183. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35184. this._registerFunc = null;
  35185. }
  35186. this._connectedMesh = meshToConnectTo;
  35187. if (!this.spatialSound) {
  35188. this.spatialSound = true;
  35189. this._createSpatialParameters();
  35190. if (this.isPlaying && this.loop) {
  35191. this.stop();
  35192. this.play();
  35193. }
  35194. }
  35195. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35196. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35197. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35198. };
  35199. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35200. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35201. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35202. this._updateDirection();
  35203. }
  35204. };
  35205. Sound.prototype.clone = function () {
  35206. var _this = this;
  35207. if (!this._streaming) {
  35208. var setBufferAndRun = function () {
  35209. if (_this._isReadyToPlay) {
  35210. clonedSound._audioBuffer = _this.getAudioBuffer();
  35211. clonedSound._isReadyToPlay = true;
  35212. if (clonedSound.autoplay) {
  35213. clonedSound.play();
  35214. }
  35215. }
  35216. else {
  35217. window.setTimeout(setBufferAndRun, 300);
  35218. }
  35219. };
  35220. var currentOptions = {
  35221. autoplay: this.autoplay, loop: this.loop,
  35222. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35223. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35224. refDistance: this.refDistance, distanceModel: this.distanceModel
  35225. };
  35226. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35227. if (this.useCustomAttenuation) {
  35228. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35229. }
  35230. clonedSound.setPosition(this._position);
  35231. clonedSound.setPlaybackRate(this._playbackRate);
  35232. setBufferAndRun();
  35233. return clonedSound;
  35234. }
  35235. else {
  35236. return null;
  35237. }
  35238. };
  35239. Sound.prototype.getAudioBuffer = function () {
  35240. return this._audioBuffer;
  35241. };
  35242. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35243. var soundName = parsedSound.name;
  35244. var soundUrl;
  35245. if (parsedSound.url) {
  35246. soundUrl = rootUrl + parsedSound.url;
  35247. }
  35248. else {
  35249. soundUrl = rootUrl + soundName;
  35250. }
  35251. var options = {
  35252. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35253. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35254. rolloffFactor: parsedSound.rolloffFactor,
  35255. refDistance: parsedSound.refDistance,
  35256. distanceModel: parsedSound.distanceModel,
  35257. playbackRate: parsedSound.playbackRate
  35258. };
  35259. var newSound;
  35260. if (!sourceSound) {
  35261. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35262. scene._addPendingData(newSound);
  35263. }
  35264. else {
  35265. var setBufferAndRun = function () {
  35266. if (sourceSound._isReadyToPlay) {
  35267. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35268. newSound._isReadyToPlay = true;
  35269. if (newSound.autoplay) {
  35270. newSound.play();
  35271. }
  35272. }
  35273. else {
  35274. window.setTimeout(setBufferAndRun, 300);
  35275. }
  35276. };
  35277. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35278. setBufferAndRun();
  35279. }
  35280. if (parsedSound.position) {
  35281. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35282. newSound.setPosition(soundPosition);
  35283. }
  35284. if (parsedSound.isDirectional) {
  35285. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35286. if (parsedSound.localDirectionToMesh) {
  35287. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35288. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35289. }
  35290. }
  35291. if (parsedSound.connectedMeshId) {
  35292. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35293. if (connectedMesh) {
  35294. newSound.attachToMesh(connectedMesh);
  35295. }
  35296. }
  35297. return newSound;
  35298. };
  35299. return Sound;
  35300. })();
  35301. BABYLON.Sound = Sound;
  35302. })(BABYLON || (BABYLON = {}));
  35303. var BABYLON;
  35304. (function (BABYLON) {
  35305. var SoundTrack = (function () {
  35306. function SoundTrack(scene, options) {
  35307. this.id = -1;
  35308. this._isMainTrack = false;
  35309. this._isInitialized = false;
  35310. this._scene = scene;
  35311. this.soundCollection = new Array();
  35312. this._options = options;
  35313. if (!this._isMainTrack) {
  35314. this._scene.soundTracks.push(this);
  35315. this.id = this._scene.soundTracks.length - 1;
  35316. }
  35317. }
  35318. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35319. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35320. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35321. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35322. if (this._options) {
  35323. if (this._options.volume) {
  35324. this._outputAudioNode.gain.value = this._options.volume;
  35325. }
  35326. if (this._options.mainTrack) {
  35327. this._isMainTrack = this._options.mainTrack;
  35328. }
  35329. }
  35330. this._isInitialized = true;
  35331. }
  35332. };
  35333. SoundTrack.prototype.dispose = function () {
  35334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35335. if (this._connectedAnalyser) {
  35336. this._connectedAnalyser.stopDebugCanvas();
  35337. }
  35338. while (this.soundCollection.length) {
  35339. this.soundCollection[0].dispose();
  35340. }
  35341. if (this._outputAudioNode) {
  35342. this._outputAudioNode.disconnect();
  35343. }
  35344. this._outputAudioNode = null;
  35345. }
  35346. };
  35347. SoundTrack.prototype.AddSound = function (sound) {
  35348. if (!this._isInitialized) {
  35349. this._initializeSoundTrackAudioGraph();
  35350. }
  35351. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35352. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35353. }
  35354. if (sound.soundTrackId) {
  35355. if (sound.soundTrackId === -1) {
  35356. this._scene.mainSoundTrack.RemoveSound(sound);
  35357. }
  35358. else {
  35359. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35360. }
  35361. }
  35362. this.soundCollection.push(sound);
  35363. sound.soundTrackId = this.id;
  35364. };
  35365. SoundTrack.prototype.RemoveSound = function (sound) {
  35366. var index = this.soundCollection.indexOf(sound);
  35367. if (index !== -1) {
  35368. this.soundCollection.splice(index, 1);
  35369. }
  35370. };
  35371. SoundTrack.prototype.setVolume = function (newVolume) {
  35372. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35373. this._outputAudioNode.gain.value = newVolume;
  35374. }
  35375. };
  35376. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35377. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35378. for (var i = 0; i < this.soundCollection.length; i++) {
  35379. this.soundCollection[i].switchPanningModelToHRTF();
  35380. }
  35381. }
  35382. };
  35383. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35384. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35385. for (var i = 0; i < this.soundCollection.length; i++) {
  35386. this.soundCollection[i].switchPanningModelToEqualPower();
  35387. }
  35388. }
  35389. };
  35390. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35391. if (this._connectedAnalyser) {
  35392. this._connectedAnalyser.stopDebugCanvas();
  35393. }
  35394. this._connectedAnalyser = analyser;
  35395. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35396. this._outputAudioNode.disconnect();
  35397. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35398. }
  35399. };
  35400. return SoundTrack;
  35401. })();
  35402. BABYLON.SoundTrack = SoundTrack;
  35403. })(BABYLON || (BABYLON = {}));
  35404. var BABYLON;
  35405. (function (BABYLON) {
  35406. var DepthRenderer = (function () {
  35407. function DepthRenderer(scene, type) {
  35408. var _this = this;
  35409. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35410. this._viewMatrix = BABYLON.Matrix.Zero();
  35411. this._projectionMatrix = BABYLON.Matrix.Zero();
  35412. this._transformMatrix = BABYLON.Matrix.Zero();
  35413. this._worldViewProjection = BABYLON.Matrix.Zero();
  35414. this._scene = scene;
  35415. var engine = scene.getEngine();
  35416. // Render target
  35417. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35418. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35419. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35420. this._depthMap.refreshRate = 1;
  35421. this._depthMap.renderParticles = false;
  35422. this._depthMap.renderList = null;
  35423. // set default depth value to 1.0 (far away)
  35424. this._depthMap.onClear = function (engine) {
  35425. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35426. };
  35427. // Custom render function
  35428. var renderSubMesh = function (subMesh) {
  35429. var mesh = subMesh.getRenderingMesh();
  35430. var scene = _this._scene;
  35431. var engine = scene.getEngine();
  35432. // Culling
  35433. engine.setState(subMesh.getMaterial().backFaceCulling);
  35434. // Managing instances
  35435. var batch = mesh._getInstancesRenderList(subMesh._id);
  35436. if (batch.mustReturn) {
  35437. return;
  35438. }
  35439. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35440. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35441. engine.enableEffect(_this._effect);
  35442. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35443. var material = subMesh.getMaterial();
  35444. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35445. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35446. // Alpha test
  35447. if (material && material.needAlphaTesting()) {
  35448. var alphaTexture = material.getAlphaTestTexture();
  35449. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35450. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35451. }
  35452. // Bones
  35453. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35454. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35455. }
  35456. // Draw
  35457. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35458. }
  35459. };
  35460. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35461. var index;
  35462. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35463. renderSubMesh(opaqueSubMeshes.data[index]);
  35464. }
  35465. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35466. renderSubMesh(alphaTestSubMeshes.data[index]);
  35467. }
  35468. };
  35469. }
  35470. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35471. var defines = [];
  35472. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35473. var mesh = subMesh.getMesh();
  35474. var scene = mesh.getScene();
  35475. var material = subMesh.getMaterial();
  35476. // Alpha test
  35477. if (material && material.needAlphaTesting()) {
  35478. defines.push("#define ALPHATEST");
  35479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35480. attribs.push(BABYLON.VertexBuffer.UVKind);
  35481. defines.push("#define UV1");
  35482. }
  35483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35485. defines.push("#define UV2");
  35486. }
  35487. }
  35488. // Bones
  35489. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35492. if (mesh.numBoneInfluencers > 4) {
  35493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35495. }
  35496. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35497. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35498. }
  35499. else {
  35500. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35501. }
  35502. // Instances
  35503. if (useInstances) {
  35504. defines.push("#define INSTANCES");
  35505. attribs.push("world0");
  35506. attribs.push("world1");
  35507. attribs.push("world2");
  35508. attribs.push("world3");
  35509. }
  35510. // Get correct effect
  35511. var join = defines.join("\n");
  35512. if (this._cachedDefines !== join) {
  35513. this._cachedDefines = join;
  35514. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35515. }
  35516. return this._effect.isReady();
  35517. };
  35518. DepthRenderer.prototype.getDepthMap = function () {
  35519. return this._depthMap;
  35520. };
  35521. // Methods
  35522. DepthRenderer.prototype.dispose = function () {
  35523. this._depthMap.dispose();
  35524. };
  35525. return DepthRenderer;
  35526. })();
  35527. BABYLON.DepthRenderer = DepthRenderer;
  35528. })(BABYLON || (BABYLON = {}));
  35529. var BABYLON;
  35530. (function (BABYLON) {
  35531. var SSAORenderingPipeline = (function (_super) {
  35532. __extends(SSAORenderingPipeline, _super);
  35533. /**
  35534. * @constructor
  35535. * @param {string} name - The rendering pipeline name
  35536. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35537. * @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 }
  35538. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35539. */
  35540. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35541. var _this = this;
  35542. _super.call(this, scene.getEngine(), name);
  35543. // Members
  35544. /**
  35545. * The PassPostProcess id in the pipeline that contains the original scene color
  35546. * @type {string}
  35547. */
  35548. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35549. /**
  35550. * The SSAO PostProcess id in the pipeline
  35551. * @type {string}
  35552. */
  35553. this.SSAORenderEffect = "SSAORenderEffect";
  35554. /**
  35555. * The horizontal blur PostProcess id in the pipeline
  35556. * @type {string}
  35557. */
  35558. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35559. /**
  35560. * The vertical blur PostProcess id in the pipeline
  35561. * @type {string}
  35562. */
  35563. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35564. /**
  35565. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35566. * @type {string}
  35567. */
  35568. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35569. /**
  35570. * The output strength of the SSAO post-process. Default value is 1.0.
  35571. * @type {number}
  35572. */
  35573. this.totalStrength = 1.0;
  35574. /**
  35575. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35576. * @type {number}
  35577. */
  35578. this.radius = 0.0001;
  35579. /**
  35580. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35581. * Must not be equal to fallOff and superior to fallOff.
  35582. * Default value is 0.975
  35583. * @type {number}
  35584. */
  35585. this.area = 0.0075;
  35586. /**
  35587. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35588. * Must not be equal to area and inferior to area.
  35589. * Default value is 0.0
  35590. * @type {number}
  35591. */
  35592. this.fallOff = 0.000001;
  35593. /**
  35594. * The base color of the SSAO post-process
  35595. * The final result is "base + ssao" between [0, 1]
  35596. * @type {number}
  35597. */
  35598. this.base = 0.5;
  35599. this._firstUpdate = true;
  35600. this._scene = scene;
  35601. // Set up assets
  35602. this._createRandomTexture();
  35603. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35604. var ssaoRatio = ratio.ssaoRatio || ratio;
  35605. var combineRatio = ratio.combineRatio || ratio;
  35606. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35607. this._createSSAOPostProcess(ssaoRatio);
  35608. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35609. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35610. this._createSSAOCombinePostProcess(combineRatio);
  35611. // Set up pipeline
  35612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35614. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35615. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35616. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35617. // Finish
  35618. scene.postProcessRenderPipelineManager.addPipeline(this);
  35619. if (cameras)
  35620. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35621. }
  35622. // Public Methods
  35623. /**
  35624. * Returns the horizontal blur PostProcess
  35625. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35626. */
  35627. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35628. return this._blurHPostProcess;
  35629. };
  35630. /**
  35631. * Returns the vertical blur PostProcess
  35632. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35633. */
  35634. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35635. return this._blurVPostProcess;
  35636. };
  35637. /**
  35638. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35639. */
  35640. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35641. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35642. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35643. this._originalColorPostProcess = undefined;
  35644. this._ssaoPostProcess = undefined;
  35645. this._blurHPostProcess = undefined;
  35646. this._blurVPostProcess = undefined;
  35647. this._ssaoCombinePostProcess = undefined;
  35648. this._randomTexture.dispose();
  35649. if (disableDepthRender)
  35650. this._scene.disableDepthRenderer();
  35651. };
  35652. // Private Methods
  35653. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35654. var _this = this;
  35655. var numSamples = 16;
  35656. var sampleSphere = [
  35657. 0.5381, 0.1856, -0.4319,
  35658. 0.1379, 0.2486, 0.4430,
  35659. 0.3371, 0.5679, -0.0057,
  35660. -0.6999, -0.0451, -0.0019,
  35661. 0.0689, -0.1598, -0.8547,
  35662. 0.0560, 0.0069, -0.1843,
  35663. -0.0146, 0.1402, 0.0762,
  35664. 0.0100, -0.1924, -0.0344,
  35665. -0.3577, -0.5301, -0.4358,
  35666. -0.3169, 0.1063, 0.0158,
  35667. 0.0103, -0.5869, 0.0046,
  35668. -0.0897, -0.4940, 0.3287,
  35669. 0.7119, -0.0154, -0.0918,
  35670. -0.0533, 0.0596, -0.5411,
  35671. 0.0352, -0.0631, 0.5460,
  35672. -0.4776, 0.2847, -0.0271
  35673. ];
  35674. var samplesFactor = 1.0 / numSamples;
  35675. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35676. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35677. "area", "fallOff", "base"
  35678. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35679. this._ssaoPostProcess.onApply = function (effect) {
  35680. if (_this._firstUpdate) {
  35681. effect.setArray3("sampleSphere", sampleSphere);
  35682. effect.setFloat("samplesFactor", samplesFactor);
  35683. effect.setFloat("randTextureTiles", 4.0);
  35684. _this._firstUpdate = false;
  35685. }
  35686. effect.setFloat("totalStrength", _this.totalStrength);
  35687. effect.setFloat("radius", _this.radius);
  35688. effect.setFloat("area", _this.area);
  35689. effect.setFloat("fallOff", _this.fallOff);
  35690. effect.setFloat("base", _this.base);
  35691. effect.setTexture("textureSampler", _this._depthTexture);
  35692. effect.setTexture("randomSampler", _this._randomTexture);
  35693. };
  35694. };
  35695. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35696. var _this = this;
  35697. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35698. this._ssaoCombinePostProcess.onApply = function (effect) {
  35699. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35700. };
  35701. };
  35702. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35703. var size = 512;
  35704. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35705. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35706. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35707. var context = this._randomTexture.getContext();
  35708. var rand = function (min, max) {
  35709. return Math.random() * (max - min) + min;
  35710. };
  35711. var randVector = BABYLON.Vector3.Zero();
  35712. for (var x = 0; x < size; x++) {
  35713. for (var y = 0; y < size; y++) {
  35714. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35715. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35716. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35717. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35718. context.fillRect(x, y, 1, 1);
  35719. }
  35720. }
  35721. this._randomTexture.update(false);
  35722. };
  35723. return SSAORenderingPipeline;
  35724. })(BABYLON.PostProcessRenderPipeline);
  35725. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35726. })(BABYLON || (BABYLON = {}));
  35727. var BABYLON;
  35728. (function (BABYLON) {
  35729. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35730. var VolumetricLightScatteringPostProcess = (function (_super) {
  35731. __extends(VolumetricLightScatteringPostProcess, _super);
  35732. /**
  35733. * @constructor
  35734. * @param {string} name - The post-process name
  35735. * @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)
  35736. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35737. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35738. * @param {number} samples - The post-process quality, default 100
  35739. * @param {number} samplingMode - The post-process filtering mode
  35740. * @param {BABYLON.Engine} engine - The babylon engine
  35741. * @param {boolean} reusable - If the post-process is reusable
  35742. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35743. */
  35744. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35745. var _this = this;
  35746. if (samples === void 0) { samples = 100; }
  35747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35748. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35749. this._screenCoordinates = BABYLON.Vector2.Zero();
  35750. /**
  35751. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35752. * @type {boolean}
  35753. */
  35754. this.useCustomMeshPosition = false;
  35755. /**
  35756. * If the post-process should inverse the light scattering direction
  35757. * @type {boolean}
  35758. */
  35759. this.invert = true;
  35760. /**
  35761. * Set to true to use the diffuseColor instead of the diffuseTexture
  35762. * @type {boolean}
  35763. */
  35764. this.useDiffuseColor = false;
  35765. /**
  35766. * Array containing the excluded meshes not rendered in the internal pass
  35767. */
  35768. this.excludedMeshes = new Array();
  35769. /**
  35770. * Controls the overall intensity of the post-process
  35771. * @type {number}
  35772. */
  35773. this.exposure = 0.3;
  35774. /**
  35775. * Dissipates each sample's contribution in range [0, 1]
  35776. * @type {number}
  35777. */
  35778. this.decay = 0.96815;
  35779. /**
  35780. * Controls the overall intensity of each sample
  35781. * @type {number}
  35782. */
  35783. this.weight = 0.58767;
  35784. /**
  35785. * Controls the density of each sample
  35786. * @type {number}
  35787. */
  35788. this.density = 0.926;
  35789. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35790. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35791. // Configure mesh
  35792. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35793. // Configure
  35794. this._createPass(scene, ratio.passRatio || ratio);
  35795. this.onActivate = function (camera) {
  35796. if (!_this.isSupported) {
  35797. _this.dispose(camera);
  35798. }
  35799. _this.onActivate = null;
  35800. };
  35801. this.onApply = function (effect) {
  35802. _this._updateMeshScreenCoordinates(scene);
  35803. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35804. effect.setFloat("exposure", _this.exposure);
  35805. effect.setFloat("decay", _this.decay);
  35806. effect.setFloat("weight", _this.weight);
  35807. effect.setFloat("density", _this.density);
  35808. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35809. };
  35810. }
  35811. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35812. var mesh = subMesh.getMesh();
  35813. var defines = [];
  35814. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35815. var material = subMesh.getMaterial();
  35816. var needUV = false;
  35817. // Render this.mesh as default
  35818. if (mesh === this.mesh) {
  35819. if (this.useDiffuseColor) {
  35820. defines.push("#define DIFFUSE_COLOR_RENDER");
  35821. }
  35822. else if (material) {
  35823. if (material.diffuseTexture !== undefined) {
  35824. defines.push("#define BASIC_RENDER");
  35825. }
  35826. else {
  35827. defines.push("#define DIFFUSE_COLOR_RENDER");
  35828. }
  35829. }
  35830. defines.push("#define NEED_UV");
  35831. needUV = true;
  35832. }
  35833. // Alpha test
  35834. if (material) {
  35835. if (material.needAlphaTesting()) {
  35836. defines.push("#define ALPHATEST");
  35837. }
  35838. if (material.opacityTexture !== undefined) {
  35839. defines.push("#define OPACITY");
  35840. if (material.opacityTexture.getAlphaFromRGB) {
  35841. defines.push("#define OPACITYRGB");
  35842. }
  35843. if (!needUV) {
  35844. defines.push("#define NEED_UV");
  35845. }
  35846. }
  35847. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35848. attribs.push(BABYLON.VertexBuffer.UVKind);
  35849. defines.push("#define UV1");
  35850. }
  35851. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35852. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35853. defines.push("#define UV2");
  35854. }
  35855. }
  35856. // Bones
  35857. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35858. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35859. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35860. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35861. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35862. }
  35863. else {
  35864. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35865. }
  35866. // Instances
  35867. if (useInstances) {
  35868. defines.push("#define INSTANCES");
  35869. attribs.push("world0");
  35870. attribs.push("world1");
  35871. attribs.push("world2");
  35872. attribs.push("world3");
  35873. }
  35874. // Get correct effect
  35875. var join = defines.join("\n");
  35876. if (this._cachedDefines !== join) {
  35877. this._cachedDefines = join;
  35878. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35879. }
  35880. return this._volumetricLightScatteringPass.isReady();
  35881. };
  35882. /**
  35883. * Sets the new light position for light scattering effect
  35884. * @param {BABYLON.Vector3} The new custom light position
  35885. */
  35886. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35887. this._customMeshPosition = position;
  35888. };
  35889. /**
  35890. * Returns the light position for light scattering effect
  35891. * @return {BABYLON.Vector3} The custom light position
  35892. */
  35893. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35894. return this._customMeshPosition;
  35895. };
  35896. /**
  35897. * Disposes the internal assets and detaches the post-process from the camera
  35898. */
  35899. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35900. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35901. if (rttIndex !== -1) {
  35902. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35903. }
  35904. this._volumetricLightScatteringRTT.dispose();
  35905. _super.prototype.dispose.call(this, camera);
  35906. };
  35907. /**
  35908. * Returns the render target texture used by the post-process
  35909. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35910. */
  35911. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35912. return this._volumetricLightScatteringRTT;
  35913. };
  35914. // Private methods
  35915. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35916. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35917. return true;
  35918. }
  35919. return false;
  35920. };
  35921. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35922. var _this = this;
  35923. var engine = scene.getEngine();
  35924. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35925. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35926. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35927. this._volumetricLightScatteringRTT.renderList = null;
  35928. this._volumetricLightScatteringRTT.renderParticles = false;
  35929. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35930. // Custom render function for submeshes
  35931. var renderSubMesh = function (subMesh) {
  35932. var mesh = subMesh.getRenderingMesh();
  35933. if (_this._meshExcluded(mesh)) {
  35934. return;
  35935. }
  35936. var scene = mesh.getScene();
  35937. var engine = scene.getEngine();
  35938. // Culling
  35939. engine.setState(subMesh.getMaterial().backFaceCulling);
  35940. // Managing instances
  35941. var batch = mesh._getInstancesRenderList(subMesh._id);
  35942. if (batch.mustReturn) {
  35943. return;
  35944. }
  35945. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35946. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35947. engine.enableEffect(_this._volumetricLightScatteringPass);
  35948. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35949. var material = subMesh.getMaterial();
  35950. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35951. // Alpha test
  35952. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35953. var alphaTexture = material.getAlphaTestTexture();
  35954. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35955. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35956. }
  35957. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35958. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35959. if (alphaTexture) {
  35960. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35961. }
  35962. }
  35963. if (material.opacityTexture !== undefined) {
  35964. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35965. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35966. }
  35967. }
  35968. // Bones
  35969. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35970. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35971. }
  35972. // Draw
  35973. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35974. }
  35975. };
  35976. // Render target texture callbacks
  35977. var savedSceneClearColor;
  35978. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35979. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35980. savedSceneClearColor = scene.clearColor;
  35981. scene.clearColor = sceneClearColor;
  35982. };
  35983. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35984. scene.clearColor = savedSceneClearColor;
  35985. };
  35986. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35987. var engine = scene.getEngine();
  35988. var index;
  35989. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35990. renderSubMesh(opaqueSubMeshes.data[index]);
  35991. }
  35992. engine.setAlphaTesting(true);
  35993. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35994. renderSubMesh(alphaTestSubMeshes.data[index]);
  35995. }
  35996. engine.setAlphaTesting(false);
  35997. if (transparentSubMeshes.length) {
  35998. // Sort sub meshes
  35999. for (index = 0; index < transparentSubMeshes.length; index++) {
  36000. var submesh = transparentSubMeshes.data[index];
  36001. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36002. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36003. }
  36004. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36005. sortedArray.sort(function (a, b) {
  36006. // Alpha index first
  36007. if (a._alphaIndex > b._alphaIndex) {
  36008. return 1;
  36009. }
  36010. if (a._alphaIndex < b._alphaIndex) {
  36011. return -1;
  36012. }
  36013. // Then distance to camera
  36014. if (a._distanceToCamera < b._distanceToCamera) {
  36015. return 1;
  36016. }
  36017. if (a._distanceToCamera > b._distanceToCamera) {
  36018. return -1;
  36019. }
  36020. return 0;
  36021. });
  36022. // Render sub meshes
  36023. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36024. for (index = 0; index < sortedArray.length; index++) {
  36025. renderSubMesh(sortedArray[index]);
  36026. }
  36027. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36028. }
  36029. };
  36030. };
  36031. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36032. var transform = scene.getTransformMatrix();
  36033. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36034. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36035. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36036. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36037. if (this.invert)
  36038. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36039. };
  36040. // Static methods
  36041. /**
  36042. * Creates a default mesh for the Volumeric Light Scattering post-process
  36043. * @param {string} The mesh name
  36044. * @param {BABYLON.Scene} The scene where to create the mesh
  36045. * @return {BABYLON.Mesh} the default mesh
  36046. */
  36047. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36048. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36049. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36050. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36051. return mesh;
  36052. };
  36053. return VolumetricLightScatteringPostProcess;
  36054. })(BABYLON.PostProcess);
  36055. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36056. })(BABYLON || (BABYLON = {}));
  36057. // BABYLON.JS Chromatic Aberration GLSL Shader
  36058. // Author: Olivier Guyot
  36059. // Separates very slightly R, G and B colors on the edges of the screen
  36060. // Inspired by Francois Tarlier & Martins Upitis
  36061. var BABYLON;
  36062. (function (BABYLON) {
  36063. var LensRenderingPipeline = (function (_super) {
  36064. __extends(LensRenderingPipeline, _super);
  36065. /**
  36066. * @constructor
  36067. *
  36068. * Effect parameters are as follow:
  36069. * {
  36070. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36071. * edge_blur: number; // from 0 to x (1 for realism)
  36072. * distortion: number; // from 0 to x (1 for realism)
  36073. * grain_amount: number; // from 0 to 1
  36074. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36075. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36076. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36077. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36078. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36079. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36080. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36081. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36082. * }
  36083. * Note: if an effect parameter is unset, effect is disabled
  36084. *
  36085. * @param {string} name - The rendering pipeline name
  36086. * @param {object} parameters - An object containing all parameters (see above)
  36087. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36088. * @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)
  36089. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36090. */
  36091. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36092. var _this = this;
  36093. if (ratio === void 0) { ratio = 1.0; }
  36094. _super.call(this, scene.getEngine(), name);
  36095. // Lens effects can be of the following:
  36096. // - chromatic aberration (slight shift of RGB colors)
  36097. // - blur on the edge of the lens
  36098. // - lens distortion
  36099. // - depth-of-field blur & highlights enhancing
  36100. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36101. // - grain effect (noise or custom texture)
  36102. // Two additional texture samplers are needed:
  36103. // - depth map (for depth-of-field)
  36104. // - grain texture
  36105. /**
  36106. * The chromatic aberration PostProcess id in the pipeline
  36107. * @type {string}
  36108. */
  36109. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36110. /**
  36111. * The highlights enhancing PostProcess id in the pipeline
  36112. * @type {string}
  36113. */
  36114. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36115. /**
  36116. * The depth-of-field PostProcess id in the pipeline
  36117. * @type {string}
  36118. */
  36119. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36120. this._scene = scene;
  36121. // Fetch texture samplers
  36122. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36123. if (parameters.grain_texture) {
  36124. this._grainTexture = parameters.grain_texture;
  36125. }
  36126. else {
  36127. this._createGrainTexture();
  36128. }
  36129. // save parameters
  36130. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36131. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36132. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36133. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36134. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36135. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36136. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36137. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36138. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36139. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36140. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36141. // Create effects
  36142. this._createChromaticAberrationPostProcess(ratio);
  36143. this._createHighlightsPostProcess(ratio);
  36144. this._createDepthOfFieldPostProcess(ratio / 4);
  36145. // Set up pipeline
  36146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36149. if (this._highlightsGain === -1) {
  36150. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36151. }
  36152. // Finish
  36153. scene.postProcessRenderPipelineManager.addPipeline(this);
  36154. if (cameras) {
  36155. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36156. }
  36157. }
  36158. // public methods (self explanatory)
  36159. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36160. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36161. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36162. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36163. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36164. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36165. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36166. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36167. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36168. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36169. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36170. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36171. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36172. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36173. };
  36174. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36175. this._highlightsPostProcess.updateEffect();
  36176. };
  36177. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36178. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36179. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36180. this._highlightsGain = amount;
  36181. };
  36182. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36183. if (this._highlightsGain === -1) {
  36184. this._highlightsGain = 1.0;
  36185. }
  36186. this._highlightsThreshold = amount;
  36187. };
  36188. LensRenderingPipeline.prototype.disableHighlights = function () {
  36189. this._highlightsGain = -1;
  36190. };
  36191. /**
  36192. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36193. */
  36194. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36195. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36196. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36197. this._chromaticAberrationPostProcess = undefined;
  36198. this._highlightsPostProcess = undefined;
  36199. this._depthOfFieldPostProcess = undefined;
  36200. this._grainTexture.dispose();
  36201. if (disableDepthRender)
  36202. this._scene.disableDepthRenderer();
  36203. };
  36204. // colors shifting and distortion
  36205. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36206. var _this = this;
  36207. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36208. [], // samplers
  36209. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36210. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36211. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36212. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36213. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36214. };
  36215. };
  36216. // highlights enhancing
  36217. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36218. var _this = this;
  36219. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36220. [], // samplers
  36221. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36222. this._highlightsPostProcess.onApply = function (effect) {
  36223. effect.setFloat('gain', _this._highlightsGain);
  36224. effect.setFloat('threshold', _this._highlightsThreshold);
  36225. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36226. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36227. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36228. };
  36229. };
  36230. // colors shifting and distortion
  36231. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36232. var _this = this;
  36233. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36234. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36235. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36236. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36237. this._depthOfFieldPostProcess.onApply = function (effect) {
  36238. effect.setTexture("depthSampler", _this._depthTexture);
  36239. effect.setTexture("grainSampler", _this._grainTexture);
  36240. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36241. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36242. effect.setFloat('grain_amount', _this._grainAmount);
  36243. effect.setBool('blur_noise', _this._blurNoise);
  36244. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36245. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36246. effect.setFloat('distortion', _this._distortion);
  36247. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36248. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36249. effect.setFloat('aperture', _this._dofAperture);
  36250. effect.setFloat('darken', _this._dofDarken);
  36251. effect.setFloat('edge_blur', _this._edgeBlur);
  36252. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36253. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36254. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36255. };
  36256. };
  36257. // creates a black and white random noise texture, 512x512
  36258. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36259. var size = 512;
  36260. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36261. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36262. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36263. var context = this._grainTexture.getContext();
  36264. var rand = function (min, max) {
  36265. return Math.random() * (max - min) + min;
  36266. };
  36267. var value;
  36268. for (var x = 0; x < size; x++) {
  36269. for (var y = 0; y < size; y++) {
  36270. value = Math.floor(rand(0.42, 0.58) * 255);
  36271. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36272. context.fillRect(x, y, 1, 1);
  36273. }
  36274. }
  36275. this._grainTexture.update(false);
  36276. };
  36277. return LensRenderingPipeline;
  36278. })(BABYLON.PostProcessRenderPipeline);
  36279. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36280. })(BABYLON || (BABYLON = {}));
  36281. //
  36282. // This post-process allows the modification of rendered colors by using
  36283. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36284. //
  36285. // The object needs to be provided an url to a texture containing the color
  36286. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36287. // Use an image editing software to tweak the LUT to match your needs.
  36288. //
  36289. // For an example of a color LUT, see here:
  36290. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36291. // For explanations on color grading, see here:
  36292. // http://udn.epicgames.com/Three/ColorGrading.html
  36293. //
  36294. var BABYLON;
  36295. (function (BABYLON) {
  36296. var ColorCorrectionPostProcess = (function (_super) {
  36297. __extends(ColorCorrectionPostProcess, _super);
  36298. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36299. var _this = this;
  36300. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36301. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36302. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36303. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36304. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36305. this.onApply = function (effect) {
  36306. effect.setTexture("colorTable", _this._colorTableTexture);
  36307. };
  36308. }
  36309. return ColorCorrectionPostProcess;
  36310. })(BABYLON.PostProcess);
  36311. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36312. })(BABYLON || (BABYLON = {}));
  36313. var BABYLON;
  36314. (function (BABYLON) {
  36315. var HDRRenderingPipeline = (function (_super) {
  36316. __extends(HDRRenderingPipeline, _super);
  36317. /**
  36318. * @constructor
  36319. * @param {string} name - The rendering pipeline name
  36320. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36321. * @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)
  36322. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36323. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36324. */
  36325. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36326. var _this = this;
  36327. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36328. _super.call(this, scene.getEngine(), name);
  36329. /**
  36330. * Public members
  36331. */
  36332. // Gaussian Blur
  36333. /**
  36334. * Gaussian blur coefficient
  36335. * @type {number}
  36336. */
  36337. this.gaussCoeff = 0.3;
  36338. /**
  36339. * Gaussian blur mean
  36340. * @type {number}
  36341. */
  36342. this.gaussMean = 1.0;
  36343. /**
  36344. * Gaussian blur standard deviation
  36345. * @type {number}
  36346. */
  36347. this.gaussStandDev = 0.8;
  36348. /**
  36349. * Gaussian blur multiplier. Multiplies the blur effect
  36350. * @type {number}
  36351. */
  36352. this.gaussMultiplier = 4.0;
  36353. // HDR
  36354. /**
  36355. * Exposure, controls the overall intensity of the pipeline
  36356. * @type {number}
  36357. */
  36358. this.exposure = 1.0;
  36359. /**
  36360. * Minimum luminance that the post-process can output. Luminance is >= 0
  36361. * @type {number}
  36362. */
  36363. this.minimumLuminance = 1.0;
  36364. /**
  36365. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36366. * @type {number}
  36367. */
  36368. this.maximumLuminance = 1e20;
  36369. /**
  36370. * Increase rate for luminance: eye adaptation speed to dark
  36371. * @type {number}
  36372. */
  36373. this.luminanceIncreaserate = 0.5;
  36374. /**
  36375. * Decrease rate for luminance: eye adaptation speed to bright
  36376. * @type {number}
  36377. */
  36378. this.luminanceDecreaseRate = 0.5;
  36379. // Bright pass
  36380. /**
  36381. * Minimum luminance needed to compute HDR
  36382. * @type {number}
  36383. */
  36384. this.brightThreshold = 0.8;
  36385. this._needUpdate = true;
  36386. this._scene = scene;
  36387. // Bright pass
  36388. this._createBrightPassPostProcess(scene, ratio);
  36389. // Down sample X4
  36390. this._createDownSampleX4PostProcess(scene, ratio);
  36391. // Create gaussian blur post-processes
  36392. this._createGaussianBlurPostProcess(scene, ratio);
  36393. // Texture adder
  36394. this._createTextureAdderPostProcess(scene, ratio);
  36395. // Luminance generator
  36396. this._createLuminanceGeneratorPostProcess(scene);
  36397. // HDR
  36398. this._createHDRPostProcess(scene, ratio);
  36399. // Pass postprocess
  36400. if (originalPostProcess === null) {
  36401. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36402. }
  36403. else {
  36404. this._originalPostProcess = originalPostProcess;
  36405. }
  36406. // Configure pipeline
  36407. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36408. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36409. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36410. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36412. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36413. var addDownSamplerPostProcess = function (id) {
  36414. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36415. };
  36416. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36417. addDownSamplerPostProcess(i);
  36418. }
  36419. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36420. // Finish
  36421. scene.postProcessRenderPipelineManager.addPipeline(this);
  36422. if (cameras !== null) {
  36423. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36424. }
  36425. this.update();
  36426. }
  36427. /**
  36428. * Tells the pipeline to update its post-processes
  36429. */
  36430. HDRRenderingPipeline.prototype.update = function () {
  36431. this._needUpdate = true;
  36432. };
  36433. /**
  36434. * Returns the current calculated luminance
  36435. */
  36436. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36437. return this._hdrCurrentLuminance;
  36438. };
  36439. /**
  36440. * Returns the currently drawn luminance
  36441. */
  36442. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36443. return this._hdrOutputLuminance;
  36444. };
  36445. /**
  36446. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36447. */
  36448. HDRRenderingPipeline.prototype.dispose = function () {
  36449. this._originalPostProcess = undefined;
  36450. this._brightPassPostProcess = undefined;
  36451. this._downSampleX4PostProcess = undefined;
  36452. this._guassianBlurHPostProcess = undefined;
  36453. this._guassianBlurVPostProcess = undefined;
  36454. this._textureAdderPostProcess = undefined;
  36455. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36456. this._downSamplePostProcesses[i] = undefined;
  36457. }
  36458. this._hdrPostProcess = undefined;
  36459. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36460. };
  36461. /**
  36462. * Creates the HDR post-process and computes the luminance adaptation
  36463. */
  36464. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36465. var _this = this;
  36466. var hdrLastLuminance = 0.0;
  36467. this._hdrOutputLuminance = -1.0;
  36468. this._hdrCurrentLuminance = 1.0;
  36469. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36470. this._hdrPostProcess.onApply = function (effect) {
  36471. if (_this._hdrOutputLuminance < 0.0) {
  36472. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36473. }
  36474. else {
  36475. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36476. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36477. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36478. }
  36479. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36480. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36481. }
  36482. else {
  36483. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36484. }
  36485. }
  36486. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36487. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36488. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36489. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36490. effect.setFloat("exposure", _this.exposure);
  36491. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36492. _this._needUpdate = false;
  36493. };
  36494. };
  36495. /**
  36496. * Texture Adder post-process
  36497. */
  36498. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36499. var _this = this;
  36500. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36501. this._textureAdderPostProcess.onApply = function (effect) {
  36502. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36503. };
  36504. };
  36505. /**
  36506. * Down sample X4 post-process
  36507. */
  36508. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36509. var _this = this;
  36510. var downSampleX4Offsets = new Array(32);
  36511. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36512. this._downSampleX4PostProcess.onApply = function (effect) {
  36513. if (_this._needUpdate) {
  36514. var id = 0;
  36515. for (var i = -2; i < 2; i++) {
  36516. for (var j = -2; j < 2; j++) {
  36517. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36518. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36519. id += 2;
  36520. }
  36521. }
  36522. }
  36523. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36524. };
  36525. };
  36526. /**
  36527. * Bright pass post-process
  36528. */
  36529. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36530. var _this = this;
  36531. var brightOffsets = new Array(8);
  36532. var brightPassCallback = function (effect) {
  36533. if (_this._needUpdate) {
  36534. var sU = (1.0 / _this._brightPassPostProcess.width);
  36535. var sV = (1.0 / _this._brightPassPostProcess.height);
  36536. brightOffsets[0] = -0.5 * sU;
  36537. brightOffsets[1] = 0.5 * sV;
  36538. brightOffsets[2] = 0.5 * sU;
  36539. brightOffsets[3] = 0.5 * sV;
  36540. brightOffsets[4] = -0.5 * sU;
  36541. brightOffsets[5] = -0.5 * sV;
  36542. brightOffsets[6] = 0.5 * sU;
  36543. brightOffsets[7] = -0.5 * sV;
  36544. }
  36545. effect.setArray2("dsOffsets", brightOffsets);
  36546. effect.setFloat("brightThreshold", _this.brightThreshold);
  36547. };
  36548. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36549. this._brightPassPostProcess.onApply = brightPassCallback;
  36550. };
  36551. /**
  36552. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36553. */
  36554. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36555. var _this = this;
  36556. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36557. var luminanceOffsets = new Array(8);
  36558. var downSampleOffsets = new Array(18);
  36559. var halfDestPixelSize;
  36560. this._downSamplePostProcesses = new Array(lumSteps);
  36561. // Utils for luminance
  36562. var luminanceUpdateSourceOffsets = function (width, height) {
  36563. var sU = (1.0 / width);
  36564. var sV = (1.0 / height);
  36565. luminanceOffsets[0] = -0.5 * sU;
  36566. luminanceOffsets[1] = 0.5 * sV;
  36567. luminanceOffsets[2] = 0.5 * sU;
  36568. luminanceOffsets[3] = 0.5 * sV;
  36569. luminanceOffsets[4] = -0.5 * sU;
  36570. luminanceOffsets[5] = -0.5 * sV;
  36571. luminanceOffsets[6] = 0.5 * sU;
  36572. luminanceOffsets[7] = -0.5 * sV;
  36573. };
  36574. var luminanceUpdateDestOffsets = function (width, height) {
  36575. var id = 0;
  36576. for (var x = -1; x < 2; x++) {
  36577. for (var y = -1; y < 2; y++) {
  36578. downSampleOffsets[id] = (x) / width;
  36579. downSampleOffsets[id + 1] = (y) / height;
  36580. id += 2;
  36581. }
  36582. }
  36583. };
  36584. // Luminance callback
  36585. var luminanceCallback = function (effect) {
  36586. if (_this._needUpdate) {
  36587. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36588. }
  36589. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36590. effect.setArray2("lumOffsets", luminanceOffsets);
  36591. };
  36592. // Down sample callbacks
  36593. var downSampleCallback = function (indice) {
  36594. var i = indice;
  36595. return function (effect) {
  36596. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36597. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36598. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36599. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36600. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36601. effect.setArray2("dsOffsets", downSampleOffsets);
  36602. };
  36603. };
  36604. var downSampleAfterRenderCallback = function (effect) {
  36605. // Unpack result
  36606. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36607. 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);
  36608. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36609. };
  36610. // Create luminance post-process
  36611. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36612. 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);
  36613. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36614. // Create down sample post-processes
  36615. for (var i = lumSteps - 2; i >= 0; i--) {
  36616. var length = Math.pow(3, i);
  36617. ratio = { width: length, height: length };
  36618. var defines = "#define DOWN_SAMPLE\n";
  36619. if (i === 0) {
  36620. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36621. }
  36622. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36623. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36624. if (i === 0) {
  36625. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36626. }
  36627. }
  36628. };
  36629. /**
  36630. * Gaussian blur post-processes. Horizontal and Vertical
  36631. */
  36632. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36633. var _this = this;
  36634. var blurOffsetsW = new Array(9);
  36635. var blurOffsetsH = new Array(9);
  36636. var blurWeights = new Array(9);
  36637. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36638. // Utils for gaussian blur
  36639. var calculateBlurOffsets = function (height) {
  36640. var lastOutputDimensions = {
  36641. width: scene.getEngine().getRenderWidth(),
  36642. height: scene.getEngine().getRenderHeight()
  36643. };
  36644. for (var i = 0; i < 9; i++) {
  36645. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36646. if (height) {
  36647. blurOffsetsH[i] = value;
  36648. }
  36649. else {
  36650. blurOffsetsW[i] = value;
  36651. }
  36652. }
  36653. };
  36654. var calculateWeights = function () {
  36655. var x = 0.0;
  36656. for (var i = 0; i < 9; i++) {
  36657. x = (i - 4.0) / 4.0;
  36658. 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));
  36659. }
  36660. };
  36661. // Callback
  36662. var gaussianBlurCallback = function (height) {
  36663. return function (effect) {
  36664. if (_this._needUpdate) {
  36665. calculateWeights();
  36666. calculateBlurOffsets(height);
  36667. }
  36668. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36669. effect.setArray("blurWeights", blurWeights);
  36670. effect.setFloat("multiplier", _this.gaussMultiplier);
  36671. };
  36672. };
  36673. // Create horizontal gaussian blur post-processes
  36674. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36675. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36676. // Create vertical gaussian blur post-process
  36677. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36678. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36679. };
  36680. // Luminance generator
  36681. HDRRenderingPipeline.LUM_STEPS = 6;
  36682. return HDRRenderingPipeline;
  36683. })(BABYLON.PostProcessRenderPipeline);
  36684. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36685. })(BABYLON || (BABYLON = {}));
  36686. var BABYLON;
  36687. (function (BABYLON) {
  36688. var FaceAdjacencies = (function () {
  36689. function FaceAdjacencies() {
  36690. this.edges = new Array();
  36691. this.edgesConnectedCount = 0;
  36692. }
  36693. return FaceAdjacencies;
  36694. })();
  36695. var EdgesRenderer = (function () {
  36696. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36697. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36698. if (epsilon === void 0) { epsilon = 0.95; }
  36699. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36700. this.edgesWidthScalerForOrthographic = 1000.0;
  36701. this.edgesWidthScalerForPerspective = 50.0;
  36702. this._linesPositions = new Array();
  36703. this._linesNormals = new Array();
  36704. this._linesIndices = new Array();
  36705. this._buffers = new Array();
  36706. this._checkVerticesInsteadOfIndices = false;
  36707. this._source = source;
  36708. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36709. this._epsilon = epsilon;
  36710. this._prepareRessources();
  36711. this._generateEdgesLines();
  36712. }
  36713. EdgesRenderer.prototype._prepareRessources = function () {
  36714. if (this._lineShader) {
  36715. return;
  36716. }
  36717. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36718. attributes: ["position", "normal"],
  36719. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36720. });
  36721. this._lineShader.disableDepthWrite = true;
  36722. this._lineShader.backFaceCulling = false;
  36723. };
  36724. EdgesRenderer.prototype.dispose = function () {
  36725. this._vb0.dispose();
  36726. this._vb1.dispose();
  36727. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36728. this._lineShader.dispose();
  36729. };
  36730. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36731. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36732. return 0;
  36733. }
  36734. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36735. return 1;
  36736. }
  36737. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36738. return 2;
  36739. }
  36740. return -1;
  36741. };
  36742. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36743. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36744. return 0;
  36745. }
  36746. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36747. return 1;
  36748. }
  36749. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36750. return 2;
  36751. }
  36752. return -1;
  36753. };
  36754. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36755. var needToCreateLine;
  36756. if (edge === undefined) {
  36757. needToCreateLine = true;
  36758. }
  36759. else {
  36760. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36761. needToCreateLine = dotProduct < this._epsilon;
  36762. }
  36763. if (needToCreateLine) {
  36764. var offset = this._linesPositions.length / 3;
  36765. var normal = p0.subtract(p1);
  36766. normal.normalize();
  36767. // Positions
  36768. this._linesPositions.push(p0.x);
  36769. this._linesPositions.push(p0.y);
  36770. this._linesPositions.push(p0.z);
  36771. this._linesPositions.push(p0.x);
  36772. this._linesPositions.push(p0.y);
  36773. this._linesPositions.push(p0.z);
  36774. this._linesPositions.push(p1.x);
  36775. this._linesPositions.push(p1.y);
  36776. this._linesPositions.push(p1.z);
  36777. this._linesPositions.push(p1.x);
  36778. this._linesPositions.push(p1.y);
  36779. this._linesPositions.push(p1.z);
  36780. // Normals
  36781. this._linesNormals.push(p1.x);
  36782. this._linesNormals.push(p1.y);
  36783. this._linesNormals.push(p1.z);
  36784. this._linesNormals.push(-1);
  36785. this._linesNormals.push(p1.x);
  36786. this._linesNormals.push(p1.y);
  36787. this._linesNormals.push(p1.z);
  36788. this._linesNormals.push(1);
  36789. this._linesNormals.push(p0.x);
  36790. this._linesNormals.push(p0.y);
  36791. this._linesNormals.push(p0.z);
  36792. this._linesNormals.push(-1);
  36793. this._linesNormals.push(p0.x);
  36794. this._linesNormals.push(p0.y);
  36795. this._linesNormals.push(p0.z);
  36796. this._linesNormals.push(1);
  36797. // Indices
  36798. this._linesIndices.push(offset);
  36799. this._linesIndices.push(offset + 1);
  36800. this._linesIndices.push(offset + 2);
  36801. this._linesIndices.push(offset);
  36802. this._linesIndices.push(offset + 2);
  36803. this._linesIndices.push(offset + 3);
  36804. }
  36805. };
  36806. EdgesRenderer.prototype._generateEdgesLines = function () {
  36807. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36808. var indices = this._source.getIndices();
  36809. // First let's find adjacencies
  36810. var adjacencies = new Array();
  36811. var faceNormals = new Array();
  36812. var index;
  36813. var faceAdjacencies;
  36814. // Prepare faces
  36815. for (index = 0; index < indices.length; index += 3) {
  36816. faceAdjacencies = new FaceAdjacencies();
  36817. var p0Index = indices[index];
  36818. var p1Index = indices[index + 1];
  36819. var p2Index = indices[index + 2];
  36820. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36821. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36822. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36823. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36824. faceNormal.normalize();
  36825. faceNormals.push(faceNormal);
  36826. adjacencies.push(faceAdjacencies);
  36827. }
  36828. // Scan
  36829. for (index = 0; index < adjacencies.length; index++) {
  36830. faceAdjacencies = adjacencies[index];
  36831. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36832. var otherFaceAdjacencies = adjacencies[otherIndex];
  36833. if (faceAdjacencies.edgesConnectedCount === 3) {
  36834. break;
  36835. }
  36836. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36837. continue;
  36838. }
  36839. var otherP0 = indices[otherIndex * 3];
  36840. var otherP1 = indices[otherIndex * 3 + 1];
  36841. var otherP2 = indices[otherIndex * 3 + 2];
  36842. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36843. var otherEdgeIndex;
  36844. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36845. continue;
  36846. }
  36847. switch (edgeIndex) {
  36848. case 0:
  36849. if (this._checkVerticesInsteadOfIndices) {
  36850. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36851. }
  36852. else {
  36853. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36854. }
  36855. break;
  36856. case 1:
  36857. if (this._checkVerticesInsteadOfIndices) {
  36858. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36859. }
  36860. else {
  36861. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36862. }
  36863. break;
  36864. case 2:
  36865. if (this._checkVerticesInsteadOfIndices) {
  36866. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36867. }
  36868. else {
  36869. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36870. }
  36871. break;
  36872. }
  36873. if (otherEdgeIndex === -1) {
  36874. continue;
  36875. }
  36876. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36877. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36878. faceAdjacencies.edgesConnectedCount++;
  36879. otherFaceAdjacencies.edgesConnectedCount++;
  36880. if (faceAdjacencies.edgesConnectedCount === 3) {
  36881. break;
  36882. }
  36883. }
  36884. }
  36885. }
  36886. // Create lines
  36887. for (index = 0; index < adjacencies.length; index++) {
  36888. // 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
  36889. var current = adjacencies[index];
  36890. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36891. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36892. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36893. }
  36894. // Merge into a single mesh
  36895. var engine = this._source.getScene().getEngine();
  36896. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36897. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36898. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36899. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36900. this._ib = engine.createIndexBuffer(this._linesIndices);
  36901. this._indicesCount = this._linesIndices.length;
  36902. };
  36903. EdgesRenderer.prototype.render = function () {
  36904. if (!this._lineShader.isReady()) {
  36905. return;
  36906. }
  36907. var scene = this._source.getScene();
  36908. var engine = scene.getEngine();
  36909. this._lineShader._preBind();
  36910. // VBOs
  36911. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36912. scene.resetCachedMaterial();
  36913. this._lineShader.setColor4("color", this._source.edgesColor);
  36914. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36915. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36916. }
  36917. else {
  36918. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36919. }
  36920. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36921. this._lineShader.bind(this._source.getWorldMatrix());
  36922. // Draw order
  36923. engine.draw(true, 0, this._indicesCount);
  36924. this._lineShader.unbind();
  36925. engine.setDepthWrite(true);
  36926. };
  36927. return EdgesRenderer;
  36928. })();
  36929. BABYLON.EdgesRenderer = EdgesRenderer;
  36930. })(BABYLON || (BABYLON = {}));
  36931. var BABYLON;
  36932. (function (BABYLON) {
  36933. (function (TonemappingOperator) {
  36934. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36935. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36936. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36937. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36938. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36939. var TonemappingOperator = BABYLON.TonemappingOperator;
  36940. ;
  36941. var TonemapPostProcess = (function (_super) {
  36942. __extends(TonemapPostProcess, _super);
  36943. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36944. var _this = this;
  36945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36946. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36947. this._operator = operator;
  36948. this.exposureAdjustment = exposureAdjustment;
  36949. var params = ["_ExposureAdjustment"];
  36950. var defines = "#define ";
  36951. if (operator === TonemappingOperator.Hable)
  36952. defines += "HABLE_TONEMAPPING";
  36953. else if (operator === TonemappingOperator.Reinhard)
  36954. defines += "REINHARD_TONEMAPPING";
  36955. else if (operator === TonemappingOperator.HejiDawson)
  36956. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36957. else if (operator === TonemappingOperator.Photographic)
  36958. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36959. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36960. this.onApply = function (effect) {
  36961. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  36962. };
  36963. }
  36964. return TonemapPostProcess;
  36965. })(BABYLON.PostProcess);
  36966. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36967. })(BABYLON || (BABYLON = {}));
  36968. var BABYLON;
  36969. (function (BABYLON) {
  36970. var ReflectionProbe = (function () {
  36971. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36972. var _this = this;
  36973. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36974. this.name = name;
  36975. this._viewMatrix = BABYLON.Matrix.Identity();
  36976. this._target = BABYLON.Vector3.Zero();
  36977. this._add = BABYLON.Vector3.Zero();
  36978. this.position = BABYLON.Vector3.Zero();
  36979. this._scene = scene;
  36980. this._scene.reflectionProbes.push(this);
  36981. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36982. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36983. switch (faceIndex) {
  36984. case 0:
  36985. _this._add.copyFromFloats(1, 0, 0);
  36986. break;
  36987. case 1:
  36988. _this._add.copyFromFloats(-1, 0, 0);
  36989. break;
  36990. case 2:
  36991. _this._add.copyFromFloats(0, -1, 0);
  36992. break;
  36993. case 3:
  36994. _this._add.copyFromFloats(0, 1, 0);
  36995. break;
  36996. case 4:
  36997. _this._add.copyFromFloats(0, 0, 1);
  36998. break;
  36999. case 5:
  37000. _this._add.copyFromFloats(0, 0, -1);
  37001. break;
  37002. }
  37003. if (_this._attachedMesh) {
  37004. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37005. }
  37006. _this.position.addToRef(_this._add, _this._target);
  37007. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37008. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37009. };
  37010. this._renderTargetTexture.onAfterUnbind = function () {
  37011. scene.updateTransformMatrix(true);
  37012. };
  37013. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37014. }
  37015. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37016. get: function () {
  37017. return this._renderTargetTexture.refreshRate;
  37018. },
  37019. set: function (value) {
  37020. this._renderTargetTexture.refreshRate = value;
  37021. },
  37022. enumerable: true,
  37023. configurable: true
  37024. });
  37025. ReflectionProbe.prototype.getScene = function () {
  37026. return this._scene;
  37027. };
  37028. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37029. get: function () {
  37030. return this._renderTargetTexture;
  37031. },
  37032. enumerable: true,
  37033. configurable: true
  37034. });
  37035. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37036. get: function () {
  37037. return this._renderTargetTexture.renderList;
  37038. },
  37039. enumerable: true,
  37040. configurable: true
  37041. });
  37042. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37043. this._attachedMesh = mesh;
  37044. };
  37045. ReflectionProbe.prototype.dispose = function () {
  37046. var index = this._scene.reflectionProbes.indexOf(this);
  37047. if (index !== -1) {
  37048. // Remove from the scene if found
  37049. this._scene.reflectionProbes.splice(index, 1);
  37050. }
  37051. if (this._renderTargetTexture) {
  37052. this._renderTargetTexture.dispose();
  37053. this._renderTargetTexture = null;
  37054. }
  37055. };
  37056. return ReflectionProbe;
  37057. })();
  37058. BABYLON.ReflectionProbe = ReflectionProbe;
  37059. })(BABYLON || (BABYLON = {}));
  37060. var BABYLON;
  37061. (function (BABYLON) {
  37062. var SolidParticle = (function () {
  37063. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37064. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37065. this.position = BABYLON.Vector3.Zero(); // position
  37066. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37067. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37068. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37069. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37070. this.alive = true; // alive
  37071. this.idx = particleIndex;
  37072. this._pos = positionIndex;
  37073. this._model = model;
  37074. this.shapeId = shapeId;
  37075. this.idxInShape = idxInShape;
  37076. }
  37077. return SolidParticle;
  37078. })();
  37079. BABYLON.SolidParticle = SolidParticle;
  37080. var ModelShape = (function () {
  37081. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37082. this.shapeID = id;
  37083. this._shape = shape;
  37084. this._shapeUV = shapeUV;
  37085. this._positionFunction = posFunction;
  37086. this._vertexFunction = vtxFunction;
  37087. }
  37088. return ModelShape;
  37089. })();
  37090. BABYLON.ModelShape = ModelShape;
  37091. })(BABYLON || (BABYLON = {}));
  37092. var BABYLON;
  37093. (function (BABYLON) {
  37094. /**
  37095. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37096. */
  37097. var SolidParticleSystem = (function () {
  37098. /**
  37099. * Creates a SPS (Solid Particle System) object.
  37100. * @param name the SPS name, this will be the underlying mesh name
  37101. * @param scene the scene in which the SPS is added
  37102. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37103. */
  37104. function SolidParticleSystem(name, scene, options) {
  37105. // public members
  37106. /**
  37107. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37108. * Example : var p = SPS.particles[i];
  37109. */
  37110. this.particles = new Array();
  37111. /**
  37112. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37113. */
  37114. this.nbParticles = 0;
  37115. /**
  37116. * If the particles must ever face the camera (default false). Useful for planar particles.
  37117. */
  37118. this.billboard = false;
  37119. /**
  37120. * This a counter ofr your own usage. It's not set by any SPS functions.
  37121. */
  37122. this.counter = 0;
  37123. /**
  37124. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37125. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37126. */
  37127. this.vars = {};
  37128. this._positions = new Array();
  37129. this._indices = new Array();
  37130. this._normals = new Array();
  37131. this._colors = new Array();
  37132. this._uvs = new Array();
  37133. this._index = 0; // indices index
  37134. this._updatable = true;
  37135. this._pickable = false;
  37136. this._isVisibilityBoxLocked = false;
  37137. this._alwaysVisible = false;
  37138. this._shapeCounter = 0;
  37139. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37140. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37141. this._computeParticleColor = true;
  37142. this._computeParticleTexture = true;
  37143. this._computeParticleRotation = true;
  37144. this._computeParticleVertex = false;
  37145. this._computeBoundingBox = false;
  37146. this._cam_axisZ = BABYLON.Vector3.Zero();
  37147. this._cam_axisY = BABYLON.Vector3.Zero();
  37148. this._cam_axisX = BABYLON.Vector3.Zero();
  37149. this._axisX = BABYLON.Axis.X;
  37150. this._axisY = BABYLON.Axis.Y;
  37151. this._axisZ = BABYLON.Axis.Z;
  37152. this._fakeCamPos = BABYLON.Vector3.Zero();
  37153. this._rotMatrix = new BABYLON.Matrix();
  37154. this._invertMatrix = new BABYLON.Matrix();
  37155. this._rotated = BABYLON.Vector3.Zero();
  37156. this._quaternion = new BABYLON.Quaternion();
  37157. this._vertex = BABYLON.Vector3.Zero();
  37158. this._normal = BABYLON.Vector3.Zero();
  37159. this._yaw = 0.0;
  37160. this._pitch = 0.0;
  37161. this._roll = 0.0;
  37162. this._halfroll = 0.0;
  37163. this._halfpitch = 0.0;
  37164. this._halfyaw = 0.0;
  37165. this._sinRoll = 0.0;
  37166. this._cosRoll = 0.0;
  37167. this._sinPitch = 0.0;
  37168. this._cosPitch = 0.0;
  37169. this._sinYaw = 0.0;
  37170. this._cosYaw = 0.0;
  37171. this._w = 0.0;
  37172. this._minimum = BABYLON.Tmp.Vector3[0];
  37173. this._maximum = BABYLON.Tmp.Vector3[1];
  37174. this.name = name;
  37175. this._scene = scene;
  37176. this._camera = scene.activeCamera;
  37177. this._pickable = options ? options.isPickable : false;
  37178. if (options && options.updatable) {
  37179. this._updatable = options.updatable;
  37180. }
  37181. else {
  37182. this._updatable = true;
  37183. }
  37184. if (this._pickable) {
  37185. this.pickedParticles = [];
  37186. }
  37187. }
  37188. /**
  37189. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37190. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37191. */
  37192. SolidParticleSystem.prototype.buildMesh = function () {
  37193. if (this.nbParticles === 0) {
  37194. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37195. this.addShape(triangle, 1);
  37196. triangle.dispose();
  37197. }
  37198. this._positions32 = new Float32Array(this._positions);
  37199. this._uvs32 = new Float32Array(this._uvs);
  37200. this._colors32 = new Float32Array(this._colors);
  37201. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37202. this._normals32 = new Float32Array(this._normals);
  37203. this._fixedNormal32 = new Float32Array(this._normals);
  37204. var vertexData = new BABYLON.VertexData();
  37205. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37206. vertexData.indices = this._indices;
  37207. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37208. if (this._uvs32) {
  37209. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37210. ;
  37211. }
  37212. if (this._colors32) {
  37213. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37214. }
  37215. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37216. vertexData.applyToMesh(mesh, this._updatable);
  37217. this.mesh = mesh;
  37218. this.mesh.isPickable = this._pickable;
  37219. // free memory
  37220. this._positions = null;
  37221. this._normals = null;
  37222. this._uvs = null;
  37223. this._colors = null;
  37224. if (!this._updatable) {
  37225. this.particles.length = 0;
  37226. }
  37227. return mesh;
  37228. };
  37229. /**
  37230. * Digests the mesh and generates as many solid particles in the system as wanted.
  37231. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37232. * Thus the particles generated from digest() have their property "positiion" yet set.
  37233. * @param mesh the mesh to be digested
  37234. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37235. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37236. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37237. */
  37238. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37239. var size = (options && options.facetNb) || 1;
  37240. var number = (options && options.number);
  37241. var delta = (options && options.delta) || 0;
  37242. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37243. var meshInd = mesh.getIndices();
  37244. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37245. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37246. var f = 0; // facet counter
  37247. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37248. // compute size from number
  37249. if (number) {
  37250. number = (number > totalFacets) ? totalFacets : number;
  37251. size = Math.round(totalFacets / number);
  37252. delta = 0;
  37253. }
  37254. else {
  37255. size = (size > totalFacets) ? totalFacets : size;
  37256. }
  37257. var facetPos = []; // submesh positions
  37258. var facetInd = []; // submesh indices
  37259. var facetUV = []; // submesh UV
  37260. var facetCol = []; // submesh colors
  37261. var barycenter = BABYLON.Tmp.Vector3[0];
  37262. var rand;
  37263. var sizeO = size;
  37264. while (f < totalFacets) {
  37265. size = sizeO + Math.floor((1 + delta) * Math.random());
  37266. if (f > totalFacets - size) {
  37267. size = totalFacets - f;
  37268. }
  37269. // reset temp arrays
  37270. facetPos.length = 0;
  37271. facetInd.length = 0;
  37272. facetUV.length = 0;
  37273. facetCol.length = 0;
  37274. // iterate over "size" facets
  37275. var fi = 0;
  37276. for (var j = f * 3; j < (f + size) * 3; j++) {
  37277. facetInd.push(fi);
  37278. var i = meshInd[j];
  37279. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37280. if (meshUV) {
  37281. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37282. }
  37283. if (meshCol) {
  37284. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37285. }
  37286. fi++;
  37287. }
  37288. // create a model shape for each single particle
  37289. var idx = this.nbParticles;
  37290. var shape = this._posToShape(facetPos);
  37291. var shapeUV = this._uvsToShapeUV(facetUV);
  37292. // compute the barycenter of the shape
  37293. var v;
  37294. for (v = 0; v < shape.length; v++) {
  37295. barycenter.addInPlace(shape[v]);
  37296. }
  37297. barycenter.scaleInPlace(1 / shape.length);
  37298. // shift the shape from its barycenter to the origin
  37299. for (v = 0; v < shape.length; v++) {
  37300. shape[v].subtractInPlace(barycenter);
  37301. }
  37302. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37303. // add the particle in the SPS
  37304. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37305. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37306. // initialize the particle position
  37307. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37308. this._index += shape.length;
  37309. idx++;
  37310. this.nbParticles++;
  37311. this._shapeCounter++;
  37312. f += size;
  37313. }
  37314. };
  37315. //reset copy
  37316. SolidParticleSystem.prototype._resetCopy = function () {
  37317. this._copy.position.x = 0;
  37318. this._copy.position.y = 0;
  37319. this._copy.position.z = 0;
  37320. this._copy.rotation.x = 0;
  37321. this._copy.rotation.y = 0;
  37322. this._copy.rotation.z = 0;
  37323. this._copy.quaternion = null;
  37324. this._copy.scale.x = 1;
  37325. this._copy.scale.y = 1;
  37326. this._copy.scale.z = 1;
  37327. this._copy.uvs.x = 0;
  37328. this._copy.uvs.y = 0;
  37329. this._copy.uvs.z = 1;
  37330. this._copy.uvs.w = 1;
  37331. this._copy.color = null;
  37332. };
  37333. // _meshBuilder : inserts the shape model in the global SPS mesh
  37334. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37335. var i;
  37336. var u = 0;
  37337. var c = 0;
  37338. this._resetCopy();
  37339. if (options && options.positionFunction) {
  37340. options.positionFunction(this._copy, idx, idxInShape);
  37341. }
  37342. if (this._copy.quaternion) {
  37343. this._quaternion.x = this._copy.quaternion.x;
  37344. this._quaternion.y = this._copy.quaternion.y;
  37345. this._quaternion.z = this._copy.quaternion.z;
  37346. this._quaternion.w = this._copy.quaternion.w;
  37347. }
  37348. else {
  37349. this._yaw = this._copy.rotation.y;
  37350. this._pitch = this._copy.rotation.x;
  37351. this._roll = this._copy.rotation.z;
  37352. this._quaternionRotationYPR();
  37353. }
  37354. this._quaternionToRotationMatrix();
  37355. for (i = 0; i < shape.length; i++) {
  37356. this._vertex.x = shape[i].x;
  37357. this._vertex.y = shape[i].y;
  37358. this._vertex.z = shape[i].z;
  37359. if (options && options.vertexFunction) {
  37360. options.vertexFunction(this._copy, this._vertex, i);
  37361. }
  37362. this._vertex.x *= this._copy.scale.x;
  37363. this._vertex.y *= this._copy.scale.y;
  37364. this._vertex.z *= this._copy.scale.z;
  37365. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37366. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37367. if (meshUV) {
  37368. 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);
  37369. u += 2;
  37370. }
  37371. if (this._copy.color) {
  37372. this._color = this._copy.color;
  37373. }
  37374. else if (meshCol && meshCol[c]) {
  37375. this._color.r = meshCol[c];
  37376. this._color.g = meshCol[c + 1];
  37377. this._color.b = meshCol[c + 2];
  37378. this._color.a = meshCol[c + 3];
  37379. }
  37380. else {
  37381. this._color.r = 1;
  37382. this._color.g = 1;
  37383. this._color.b = 1;
  37384. this._color.a = 1;
  37385. }
  37386. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37387. c += 4;
  37388. }
  37389. for (i = 0; i < meshInd.length; i++) {
  37390. indices.push(p + meshInd[i]);
  37391. }
  37392. if (this._pickable) {
  37393. var nbfaces = meshInd.length / 3;
  37394. for (i = 0; i < nbfaces; i++) {
  37395. this.pickedParticles.push({ idx: idx, faceId: i });
  37396. }
  37397. }
  37398. };
  37399. // returns a shape array from positions array
  37400. SolidParticleSystem.prototype._posToShape = function (positions) {
  37401. var shape = [];
  37402. for (var i = 0; i < positions.length; i += 3) {
  37403. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37404. }
  37405. return shape;
  37406. };
  37407. // returns a shapeUV array from a Vector4 uvs
  37408. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37409. var shapeUV = [];
  37410. if (uvs) {
  37411. for (var i = 0; i < uvs.length; i++)
  37412. shapeUV.push(uvs[i]);
  37413. }
  37414. return shapeUV;
  37415. };
  37416. // adds a new particle object in the particles array
  37417. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37418. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37419. };
  37420. /**
  37421. * Adds some particles to the SPS from the model shape.
  37422. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37423. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37424. * @param nb the number of particles to be created from this model
  37425. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37426. */
  37427. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37428. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37429. var meshInd = mesh.getIndices();
  37430. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37431. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37432. var shape = this._posToShape(meshPos);
  37433. var shapeUV = this._uvsToShapeUV(meshUV);
  37434. var posfunc = options ? options.positionFunction : null;
  37435. var vtxfunc = options ? options.vertexFunction : null;
  37436. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37437. // particles
  37438. var idx = this.nbParticles;
  37439. for (var i = 0; i < nb; i++) {
  37440. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37441. if (this._updatable) {
  37442. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37443. }
  37444. this._index += shape.length;
  37445. idx++;
  37446. }
  37447. this.nbParticles += nb;
  37448. this._shapeCounter++;
  37449. return this._shapeCounter - 1;
  37450. };
  37451. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37452. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37453. this._resetCopy();
  37454. if (particle._model._positionFunction) {
  37455. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37456. }
  37457. if (this._copy.quaternion) {
  37458. this._quaternion.x = this._copy.quaternion.x;
  37459. this._quaternion.y = this._copy.quaternion.y;
  37460. this._quaternion.z = this._copy.quaternion.z;
  37461. this._quaternion.w = this._copy.quaternion.w;
  37462. }
  37463. else {
  37464. this._yaw = this._copy.rotation.y;
  37465. this._pitch = this._copy.rotation.x;
  37466. this._roll = this._copy.rotation.z;
  37467. this._quaternionRotationYPR();
  37468. }
  37469. this._quaternionToRotationMatrix();
  37470. this._shape = particle._model._shape;
  37471. for (var pt = 0; pt < this._shape.length; pt++) {
  37472. this._vertex.x = this._shape[pt].x;
  37473. this._vertex.y = this._shape[pt].y;
  37474. this._vertex.z = this._shape[pt].z;
  37475. if (particle._model._vertexFunction) {
  37476. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37477. }
  37478. this._vertex.x *= this._copy.scale.x;
  37479. this._vertex.y *= this._copy.scale.y;
  37480. this._vertex.z *= this._copy.scale.z;
  37481. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37482. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37483. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37484. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37485. }
  37486. particle.position.x = 0;
  37487. particle.position.y = 0;
  37488. particle.position.z = 0;
  37489. particle.rotation.x = 0;
  37490. particle.rotation.y = 0;
  37491. particle.rotation.z = 0;
  37492. particle.quaternion = null;
  37493. particle.scale.x = 1;
  37494. particle.scale.y = 1;
  37495. particle.scale.z = 1;
  37496. };
  37497. /**
  37498. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37499. */
  37500. SolidParticleSystem.prototype.rebuildMesh = function () {
  37501. for (var p = 0; p < this.particles.length; p++) {
  37502. this._rebuildParticle(this.particles[p]);
  37503. }
  37504. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37505. };
  37506. /**
  37507. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37508. * This method calls updateParticle() for each particles of the SPS.
  37509. * For an animated SPS, it is usually called within the render loop.
  37510. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37511. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37512. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37513. */
  37514. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37515. if (start === void 0) { start = 0; }
  37516. if (end === void 0) { end = this.nbParticles - 1; }
  37517. if (update === void 0) { update = true; }
  37518. if (!this._updatable) {
  37519. return;
  37520. }
  37521. // custom beforeUpdate
  37522. this.beforeUpdateParticles(start, end, update);
  37523. this._cam_axisX.x = 1;
  37524. this._cam_axisX.y = 0;
  37525. this._cam_axisX.z = 0;
  37526. this._cam_axisY.x = 0;
  37527. this._cam_axisY.y = 1;
  37528. this._cam_axisY.z = 0;
  37529. this._cam_axisZ.x = 0;
  37530. this._cam_axisZ.y = 0;
  37531. this._cam_axisZ.z = 1;
  37532. // if the particles will always face the camera
  37533. if (this.billboard) {
  37534. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37535. this._yaw = this.mesh.rotation.y;
  37536. this._pitch = this.mesh.rotation.x;
  37537. this._roll = this.mesh.rotation.z;
  37538. this._quaternionRotationYPR();
  37539. this._quaternionToRotationMatrix();
  37540. this._rotMatrix.invertToRef(this._invertMatrix);
  37541. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37542. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37543. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37544. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37545. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37546. this._cam_axisY.normalize();
  37547. this._cam_axisX.normalize();
  37548. this._cam_axisZ.normalize();
  37549. }
  37550. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37551. var idx = 0;
  37552. var index = 0;
  37553. var colidx = 0;
  37554. var colorIndex = 0;
  37555. var uvidx = 0;
  37556. var uvIndex = 0;
  37557. if (this._computeBoundingBox) {
  37558. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37559. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37560. }
  37561. // particle loop
  37562. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37563. for (var p = start; p <= end; p++) {
  37564. this._particle = this.particles[p];
  37565. this._shape = this._particle._model._shape;
  37566. this._shapeUV = this._particle._model._shapeUV;
  37567. // call to custom user function to update the particle properties
  37568. this.updateParticle(this._particle);
  37569. // particle rotation matrix
  37570. if (this.billboard) {
  37571. this._particle.rotation.x = 0.0;
  37572. this._particle.rotation.y = 0.0;
  37573. }
  37574. if (this._computeParticleRotation) {
  37575. if (this._particle.quaternion) {
  37576. this._quaternion.x = this._particle.quaternion.x;
  37577. this._quaternion.y = this._particle.quaternion.y;
  37578. this._quaternion.z = this._particle.quaternion.z;
  37579. this._quaternion.w = this._particle.quaternion.w;
  37580. }
  37581. else {
  37582. this._yaw = this._particle.rotation.y;
  37583. this._pitch = this._particle.rotation.x;
  37584. this._roll = this._particle.rotation.z;
  37585. this._quaternionRotationYPR();
  37586. }
  37587. this._quaternionToRotationMatrix();
  37588. }
  37589. for (var pt = 0; pt < this._shape.length; pt++) {
  37590. idx = index + pt * 3;
  37591. colidx = colorIndex + pt * 4;
  37592. uvidx = uvIndex + pt * 2;
  37593. this._vertex.x = this._shape[pt].x;
  37594. this._vertex.y = this._shape[pt].y;
  37595. this._vertex.z = this._shape[pt].z;
  37596. if (this._computeParticleVertex) {
  37597. this.updateParticleVertex(this._particle, this._vertex, pt);
  37598. }
  37599. // positions
  37600. this._vertex.x *= this._particle.scale.x;
  37601. this._vertex.y *= this._particle.scale.y;
  37602. this._vertex.z *= this._particle.scale.z;
  37603. 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];
  37604. 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;
  37605. 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;
  37606. 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;
  37607. 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;
  37608. 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;
  37609. 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;
  37610. if (this._computeBoundingBox) {
  37611. if (this._positions32[idx] < this._minimum.x) {
  37612. this._minimum.x = this._positions32[idx];
  37613. }
  37614. if (this._positions32[idx] > this._maximum.x) {
  37615. this._maximum.x = this._positions32[idx];
  37616. }
  37617. if (this._positions32[idx + 1] < this._minimum.y) {
  37618. this._minimum.y = this._positions32[idx + 1];
  37619. }
  37620. if (this._positions32[idx + 1] > this._maximum.y) {
  37621. this._maximum.y = this._positions32[idx + 1];
  37622. }
  37623. if (this._positions32[idx + 2] < this._minimum.z) {
  37624. this._minimum.z = this._positions32[idx + 2];
  37625. }
  37626. if (this._positions32[idx + 2] > this._maximum.z) {
  37627. this._maximum.z = this._positions32[idx + 2];
  37628. }
  37629. }
  37630. // normals : if the particles can't be morphed then just rotate the normals
  37631. if (!this._computeParticleVertex && !this.billboard) {
  37632. this._normal.x = this._fixedNormal32[idx];
  37633. this._normal.y = this._fixedNormal32[idx + 1];
  37634. this._normal.z = this._fixedNormal32[idx + 2];
  37635. 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];
  37636. 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;
  37637. 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;
  37638. 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;
  37639. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37640. 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;
  37641. 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;
  37642. }
  37643. if (this._computeParticleColor) {
  37644. this._colors32[colidx] = this._particle.color.r;
  37645. this._colors32[colidx + 1] = this._particle.color.g;
  37646. this._colors32[colidx + 2] = this._particle.color.b;
  37647. this._colors32[colidx + 3] = this._particle.color.a;
  37648. }
  37649. if (this._computeParticleTexture) {
  37650. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37651. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37652. }
  37653. }
  37654. index = idx + 3;
  37655. colorIndex = colidx + 4;
  37656. uvIndex = uvidx + 2;
  37657. }
  37658. if (update) {
  37659. if (this._computeParticleColor) {
  37660. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37661. }
  37662. if (this._computeParticleTexture) {
  37663. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37664. }
  37665. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37666. if (!this.mesh.areNormalsFrozen) {
  37667. if (this._computeParticleVertex || this.billboard) {
  37668. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37669. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37670. for (var i = 0; i < this._normals32.length; i++) {
  37671. this._fixedNormal32[i] = this._normals32[i];
  37672. }
  37673. }
  37674. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37675. }
  37676. }
  37677. if (this._computeBoundingBox) {
  37678. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37679. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37680. }
  37681. this.afterUpdateParticles(start, end, update);
  37682. };
  37683. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37684. this._halfroll = this._roll * 0.5;
  37685. this._halfpitch = this._pitch * 0.5;
  37686. this._halfyaw = this._yaw * 0.5;
  37687. this._sinRoll = Math.sin(this._halfroll);
  37688. this._cosRoll = Math.cos(this._halfroll);
  37689. this._sinPitch = Math.sin(this._halfpitch);
  37690. this._cosPitch = Math.cos(this._halfpitch);
  37691. this._sinYaw = Math.sin(this._halfyaw);
  37692. this._cosYaw = Math.cos(this._halfyaw);
  37693. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37694. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37695. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37696. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37697. };
  37698. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37699. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37700. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37701. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37702. this._rotMatrix.m[3] = 0;
  37703. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37704. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37705. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37706. this._rotMatrix.m[7] = 0;
  37707. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37708. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37709. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37710. this._rotMatrix.m[11] = 0;
  37711. this._rotMatrix.m[12] = 0;
  37712. this._rotMatrix.m[13] = 0;
  37713. this._rotMatrix.m[14] = 0;
  37714. this._rotMatrix.m[15] = 1.0;
  37715. };
  37716. /**
  37717. * Disposes the SPS
  37718. */
  37719. SolidParticleSystem.prototype.dispose = function () {
  37720. this.mesh.dispose();
  37721. this.vars = null;
  37722. // drop references to internal big arrays for the GC
  37723. this._positions = null;
  37724. this._indices = null;
  37725. this._normals = null;
  37726. this._uvs = null;
  37727. this._colors = null;
  37728. this._positions32 = null;
  37729. this._normals32 = null;
  37730. this._fixedNormal32 = null;
  37731. this._uvs32 = null;
  37732. this._colors32 = null;
  37733. this.pickedParticles = null;
  37734. };
  37735. /**
  37736. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37737. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37738. */
  37739. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37740. if (!this._isVisibilityBoxLocked) {
  37741. this.mesh.refreshBoundingInfo();
  37742. }
  37743. };
  37744. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37745. * @param size the size (float) of the visibility box
  37746. * note : this doesn't lock the SPS mesh bounding box.
  37747. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37748. */
  37749. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37750. var vis = size / 2;
  37751. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37752. };
  37753. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37754. // getter and setter
  37755. /**
  37756. * True if the SPS is set as always visible
  37757. */
  37758. get: function () {
  37759. return this._alwaysVisible;
  37760. },
  37761. /**
  37762. * Sets the SPS as always visible or not
  37763. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37764. */
  37765. set: function (val) {
  37766. this._alwaysVisible = val;
  37767. this.mesh.alwaysSelectAsActiveMesh = val;
  37768. },
  37769. enumerable: true,
  37770. configurable: true
  37771. });
  37772. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37773. /**
  37774. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  37775. */
  37776. get: function () {
  37777. return this._isVisibilityBoxLocked;
  37778. },
  37779. /**
  37780. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37781. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37782. */
  37783. set: function (val) {
  37784. this._isVisibilityBoxLocked = val;
  37785. this.mesh.getBoundingInfo().isLocked = val;
  37786. },
  37787. enumerable: true,
  37788. configurable: true
  37789. });
  37790. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37791. // getters
  37792. get: function () {
  37793. return this._computeParticleRotation;
  37794. },
  37795. // Optimizer setters
  37796. /**
  37797. * Tells to setParticles() to compute the particle rotations or not.
  37798. * Default value : true. The SPS is faster when it's set to false.
  37799. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37800. */
  37801. set: function (val) {
  37802. this._computeParticleRotation = val;
  37803. },
  37804. enumerable: true,
  37805. configurable: true
  37806. });
  37807. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37808. get: function () {
  37809. return this._computeParticleColor;
  37810. },
  37811. /**
  37812. * Tells to setParticles() to compute the particle colors or not.
  37813. * Default value : true. The SPS is faster when it's set to false.
  37814. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37815. */
  37816. set: function (val) {
  37817. this._computeParticleColor = val;
  37818. },
  37819. enumerable: true,
  37820. configurable: true
  37821. });
  37822. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37823. get: function () {
  37824. return this._computeParticleTexture;
  37825. },
  37826. /**
  37827. * Tells to setParticles() to compute the particle textures or not.
  37828. * Default value : true. The SPS is faster when it's set to false.
  37829. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37830. */
  37831. set: function (val) {
  37832. this._computeParticleTexture = val;
  37833. },
  37834. enumerable: true,
  37835. configurable: true
  37836. });
  37837. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37838. get: function () {
  37839. return this._computeParticleVertex;
  37840. },
  37841. /**
  37842. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  37843. * Default value : false. The SPS is faster when it's set to false.
  37844. * Note : the particle custom vertex positions aren't stored values.
  37845. */
  37846. set: function (val) {
  37847. this._computeParticleVertex = val;
  37848. },
  37849. enumerable: true,
  37850. configurable: true
  37851. });
  37852. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37853. get: function () {
  37854. return this._computeBoundingBox;
  37855. },
  37856. /**
  37857. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  37858. */
  37859. set: function (val) {
  37860. this._computeBoundingBox = val;
  37861. },
  37862. enumerable: true,
  37863. configurable: true
  37864. });
  37865. // =======================================================================
  37866. // Particle behavior logic
  37867. // these following methods may be overwritten by the user to fit his needs
  37868. /**
  37869. * This function does nothing. It may be overwritten to set all the particles first values.
  37870. * The SPS doesn't call this function, you may have to call it by your own.
  37871. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37872. */
  37873. SolidParticleSystem.prototype.initParticles = function () {
  37874. };
  37875. /**
  37876. * This function does nothing. It may be overwritten to recycle a particle.
  37877. * The SPS doesn't call this function, you may have to call it by your own.
  37878. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37879. */
  37880. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37881. return particle;
  37882. };
  37883. /**
  37884. * Updates a particle : this function should be overwritten by the user.
  37885. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37886. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37887. * ex : just set a particle position or velocity and recycle conditions
  37888. */
  37889. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37890. return particle;
  37891. };
  37892. /**
  37893. * Updates a vertex of a particle : it can be overwritten by the user.
  37894. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37895. * @param particle the current particle
  37896. * @param vertex the current index of the current particle
  37897. * @param pt the index of the current vertex in the particle shape
  37898. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37899. * ex : just set a vertex particle position
  37900. */
  37901. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37902. return vertex;
  37903. };
  37904. /**
  37905. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37906. * This does nothing and may be overwritten by the user.
  37907. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37908. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37909. * @param update the boolean update value actually passed to setParticles()
  37910. */
  37911. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37912. };
  37913. /**
  37914. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37915. * This will be passed three parameters.
  37916. * This does nothing and may be overwritten by the user.
  37917. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37918. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37919. * @param update the boolean update value actually passed to setParticles()
  37920. */
  37921. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37922. };
  37923. return SolidParticleSystem;
  37924. })();
  37925. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37926. })(BABYLON || (BABYLON = {}));
  37927. var BABYLON;
  37928. (function (BABYLON) {
  37929. // We're mainly based on the logic defined into the FreeCamera code
  37930. var UniversalCamera = (function (_super) {
  37931. __extends(UniversalCamera, _super);
  37932. function UniversalCamera(name, position, scene) {
  37933. var _this = this;
  37934. _super.call(this, name, position, scene);
  37935. this.gamepadAngularSensibility = 200;
  37936. this.gamepadMoveSensibility = 40;
  37937. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  37938. }
  37939. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  37940. // Only the first gamepad can control the camera
  37941. if (gamepad.index === 0) {
  37942. this.gamepad = gamepad;
  37943. }
  37944. };
  37945. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  37946. _super.prototype.attachControl.call(this, canvas, false);
  37947. };
  37948. UniversalCamera.prototype.detachControl = function (canvas) {
  37949. _super.prototype.detachControl.call(this, canvas);
  37950. };
  37951. UniversalCamera.prototype._checkInputs = function () {
  37952. if (this.gamepad) {
  37953. var LSValues = this.gamepad.leftStick;
  37954. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  37955. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  37956. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  37957. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  37958. var RSValues = this.gamepad.rightStick;
  37959. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  37960. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  37961. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  37962. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  37963. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  37964. var speed = this._computeLocalCameraSpeed() * 50.0;
  37965. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  37966. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  37967. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  37968. }
  37969. _super.prototype._checkInputs.call(this);
  37970. };
  37971. UniversalCamera.prototype.dispose = function () {
  37972. this._gamepads.dispose();
  37973. _super.prototype.dispose.call(this);
  37974. };
  37975. UniversalCamera.prototype.getTypeName = function () {
  37976. return "UniversalCamera";
  37977. };
  37978. __decorate([
  37979. BABYLON.serialize()
  37980. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  37981. __decorate([
  37982. BABYLON.serialize()
  37983. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  37984. return UniversalCamera;
  37985. })(BABYLON.TouchCamera);
  37986. BABYLON.UniversalCamera = UniversalCamera;
  37987. })(BABYLON || (BABYLON = {}));
  37988. var BABYLON;
  37989. (function (BABYLON) {
  37990. var Gamepads = (function () {
  37991. function Gamepads(ongamedpadconnected) {
  37992. var _this = this;
  37993. this.babylonGamepads = [];
  37994. this.oneGamepadConnected = false;
  37995. this.isMonitoring = false;
  37996. this.gamepadEventSupported = 'GamepadEvent' in window;
  37997. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37998. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37999. this._callbackGamepadConnected = ongamedpadconnected;
  38000. if (this.gamepadSupportAvailable) {
  38001. // Checking if the gamepad connected event is supported (like in Firefox)
  38002. if (this.gamepadEventSupported) {
  38003. window.addEventListener('gamepadconnected', function (evt) {
  38004. _this._onGamepadConnected(evt);
  38005. }, false);
  38006. window.addEventListener('gamepaddisconnected', function (evt) {
  38007. _this._onGamepadDisconnected(evt);
  38008. }, false);
  38009. }
  38010. else {
  38011. this._startMonitoringGamepads();
  38012. }
  38013. }
  38014. }
  38015. Gamepads.prototype.dispose = function () {
  38016. if (Gamepads.gamepadDOMInfo) {
  38017. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38018. }
  38019. };
  38020. Gamepads.prototype._onGamepadConnected = function (evt) {
  38021. var newGamepad = this._addNewGamepad(evt.gamepad);
  38022. if (this._callbackGamepadConnected)
  38023. this._callbackGamepadConnected(newGamepad);
  38024. this._startMonitoringGamepads();
  38025. };
  38026. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38027. if (!this.oneGamepadConnected) {
  38028. this.oneGamepadConnected = true;
  38029. if (Gamepads.gamepadDOMInfo) {
  38030. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38031. Gamepads.gamepadDOMInfo = null;
  38032. }
  38033. }
  38034. var newGamepad;
  38035. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38036. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38037. }
  38038. else {
  38039. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38040. }
  38041. this.babylonGamepads.push(newGamepad);
  38042. return newGamepad;
  38043. };
  38044. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38045. // Remove the gamepad from the list of gamepads to monitor.
  38046. for (var i in this.babylonGamepads) {
  38047. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38048. this.babylonGamepads.splice(i, 1);
  38049. break;
  38050. }
  38051. }
  38052. // If no gamepads are left, stop the polling loop.
  38053. if (this.babylonGamepads.length == 0) {
  38054. this._stopMonitoringGamepads();
  38055. }
  38056. };
  38057. Gamepads.prototype._startMonitoringGamepads = function () {
  38058. if (!this.isMonitoring) {
  38059. this.isMonitoring = true;
  38060. this._checkGamepadsStatus();
  38061. }
  38062. };
  38063. Gamepads.prototype._stopMonitoringGamepads = function () {
  38064. this.isMonitoring = false;
  38065. };
  38066. Gamepads.prototype._checkGamepadsStatus = function () {
  38067. var _this = this;
  38068. // updating gamepad objects
  38069. this._updateGamepadObjects();
  38070. for (var i in this.babylonGamepads) {
  38071. this.babylonGamepads[i].update();
  38072. }
  38073. if (this.isMonitoring) {
  38074. if (window.requestAnimationFrame) {
  38075. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38076. }
  38077. else if (window.mozRequestAnimationFrame) {
  38078. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38079. }
  38080. else if (window.webkitRequestAnimationFrame) {
  38081. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38082. }
  38083. }
  38084. };
  38085. // This function is called only on Chrome, which does not yet support
  38086. // connection/disconnection events, but requires you to monitor
  38087. // an array for changes.
  38088. Gamepads.prototype._updateGamepadObjects = function () {
  38089. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38090. for (var i = 0; i < gamepads.length; i++) {
  38091. if (gamepads[i]) {
  38092. if (!(gamepads[i].index in this.babylonGamepads)) {
  38093. var newGamepad = this._addNewGamepad(gamepads[i]);
  38094. if (this._callbackGamepadConnected) {
  38095. this._callbackGamepadConnected(newGamepad);
  38096. }
  38097. }
  38098. else {
  38099. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38100. }
  38101. }
  38102. }
  38103. };
  38104. return Gamepads;
  38105. })();
  38106. BABYLON.Gamepads = Gamepads;
  38107. var StickValues = (function () {
  38108. function StickValues(x, y) {
  38109. this.x = x;
  38110. this.y = y;
  38111. }
  38112. return StickValues;
  38113. })();
  38114. BABYLON.StickValues = StickValues;
  38115. var Gamepad = (function () {
  38116. function Gamepad(id, index, browserGamepad) {
  38117. this.id = id;
  38118. this.index = index;
  38119. this.browserGamepad = browserGamepad;
  38120. if (this.browserGamepad.axes.length >= 2) {
  38121. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38122. }
  38123. if (this.browserGamepad.axes.length >= 4) {
  38124. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38125. }
  38126. }
  38127. Gamepad.prototype.onleftstickchanged = function (callback) {
  38128. this._onleftstickchanged = callback;
  38129. };
  38130. Gamepad.prototype.onrightstickchanged = function (callback) {
  38131. this._onrightstickchanged = callback;
  38132. };
  38133. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38134. get: function () {
  38135. return this._leftStick;
  38136. },
  38137. set: function (newValues) {
  38138. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38139. this._onleftstickchanged(newValues);
  38140. }
  38141. this._leftStick = newValues;
  38142. },
  38143. enumerable: true,
  38144. configurable: true
  38145. });
  38146. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38147. get: function () {
  38148. return this._rightStick;
  38149. },
  38150. set: function (newValues) {
  38151. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38152. this._onrightstickchanged(newValues);
  38153. }
  38154. this._rightStick = newValues;
  38155. },
  38156. enumerable: true,
  38157. configurable: true
  38158. });
  38159. Gamepad.prototype.update = function () {
  38160. if (this._leftStick) {
  38161. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38162. }
  38163. if (this._rightStick) {
  38164. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38165. }
  38166. };
  38167. return Gamepad;
  38168. })();
  38169. BABYLON.Gamepad = Gamepad;
  38170. var GenericPad = (function (_super) {
  38171. __extends(GenericPad, _super);
  38172. function GenericPad(id, index, gamepad) {
  38173. _super.call(this, id, index, gamepad);
  38174. this.id = id;
  38175. this.index = index;
  38176. this.gamepad = gamepad;
  38177. this._buttons = new Array(gamepad.buttons.length);
  38178. }
  38179. GenericPad.prototype.onbuttondown = function (callback) {
  38180. this._onbuttondown = callback;
  38181. };
  38182. GenericPad.prototype.onbuttonup = function (callback) {
  38183. this._onbuttonup = callback;
  38184. };
  38185. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38186. if (newValue !== currentValue) {
  38187. if (this._onbuttondown && newValue === 1) {
  38188. this._onbuttondown(buttonIndex);
  38189. }
  38190. if (this._onbuttonup && newValue === 0) {
  38191. this._onbuttonup(buttonIndex);
  38192. }
  38193. }
  38194. return newValue;
  38195. };
  38196. GenericPad.prototype.update = function () {
  38197. _super.prototype.update.call(this);
  38198. for (var index = 0; index < this._buttons.length; index++) {
  38199. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38200. }
  38201. };
  38202. return GenericPad;
  38203. })(Gamepad);
  38204. BABYLON.GenericPad = GenericPad;
  38205. (function (Xbox360Button) {
  38206. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38207. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38208. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38209. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38210. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38211. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38212. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38213. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38214. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38215. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38216. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38217. var Xbox360Button = BABYLON.Xbox360Button;
  38218. (function (Xbox360Dpad) {
  38219. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38220. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38221. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38222. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38223. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38224. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38225. var Xbox360Pad = (function (_super) {
  38226. __extends(Xbox360Pad, _super);
  38227. function Xbox360Pad() {
  38228. _super.apply(this, arguments);
  38229. this._leftTrigger = 0;
  38230. this._rightTrigger = 0;
  38231. this._buttonA = 0;
  38232. this._buttonB = 0;
  38233. this._buttonX = 0;
  38234. this._buttonY = 0;
  38235. this._buttonBack = 0;
  38236. this._buttonStart = 0;
  38237. this._buttonLB = 0;
  38238. this._buttonRB = 0;
  38239. this._buttonLeftStick = 0;
  38240. this._buttonRightStick = 0;
  38241. this._dPadUp = 0;
  38242. this._dPadDown = 0;
  38243. this._dPadLeft = 0;
  38244. this._dPadRight = 0;
  38245. }
  38246. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38247. this._onlefttriggerchanged = callback;
  38248. };
  38249. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38250. this._onrighttriggerchanged = callback;
  38251. };
  38252. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38253. get: function () {
  38254. return this._leftTrigger;
  38255. },
  38256. set: function (newValue) {
  38257. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38258. this._onlefttriggerchanged(newValue);
  38259. }
  38260. this._leftTrigger = newValue;
  38261. },
  38262. enumerable: true,
  38263. configurable: true
  38264. });
  38265. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38266. get: function () {
  38267. return this._rightTrigger;
  38268. },
  38269. set: function (newValue) {
  38270. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38271. this._onrighttriggerchanged(newValue);
  38272. }
  38273. this._rightTrigger = newValue;
  38274. },
  38275. enumerable: true,
  38276. configurable: true
  38277. });
  38278. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38279. this._onbuttondown = callback;
  38280. };
  38281. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38282. this._onbuttonup = callback;
  38283. };
  38284. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38285. this._ondpaddown = callback;
  38286. };
  38287. Xbox360Pad.prototype.ondpadup = function (callback) {
  38288. this._ondpadup = callback;
  38289. };
  38290. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38291. if (newValue !== currentValue) {
  38292. if (this._onbuttondown && newValue === 1) {
  38293. this._onbuttondown(buttonType);
  38294. }
  38295. if (this._onbuttonup && newValue === 0) {
  38296. this._onbuttonup(buttonType);
  38297. }
  38298. }
  38299. return newValue;
  38300. };
  38301. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38302. if (newValue !== currentValue) {
  38303. if (this._ondpaddown && newValue === 1) {
  38304. this._ondpaddown(buttonType);
  38305. }
  38306. if (this._ondpadup && newValue === 0) {
  38307. this._ondpadup(buttonType);
  38308. }
  38309. }
  38310. return newValue;
  38311. };
  38312. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38313. get: function () {
  38314. return this._buttonA;
  38315. },
  38316. set: function (value) {
  38317. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38318. },
  38319. enumerable: true,
  38320. configurable: true
  38321. });
  38322. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38323. get: function () {
  38324. return this._buttonB;
  38325. },
  38326. set: function (value) {
  38327. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38328. },
  38329. enumerable: true,
  38330. configurable: true
  38331. });
  38332. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38333. get: function () {
  38334. return this._buttonX;
  38335. },
  38336. set: function (value) {
  38337. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38338. },
  38339. enumerable: true,
  38340. configurable: true
  38341. });
  38342. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38343. get: function () {
  38344. return this._buttonY;
  38345. },
  38346. set: function (value) {
  38347. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38348. },
  38349. enumerable: true,
  38350. configurable: true
  38351. });
  38352. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38353. get: function () {
  38354. return this._buttonStart;
  38355. },
  38356. set: function (value) {
  38357. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  38358. },
  38359. enumerable: true,
  38360. configurable: true
  38361. });
  38362. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  38363. get: function () {
  38364. return this._buttonBack;
  38365. },
  38366. set: function (value) {
  38367. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  38373. get: function () {
  38374. return this._buttonLB;
  38375. },
  38376. set: function (value) {
  38377. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  38378. },
  38379. enumerable: true,
  38380. configurable: true
  38381. });
  38382. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  38383. get: function () {
  38384. return this._buttonRB;
  38385. },
  38386. set: function (value) {
  38387. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  38388. },
  38389. enumerable: true,
  38390. configurable: true
  38391. });
  38392. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  38393. get: function () {
  38394. return this._buttonLeftStick;
  38395. },
  38396. set: function (value) {
  38397. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38398. },
  38399. enumerable: true,
  38400. configurable: true
  38401. });
  38402. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38403. get: function () {
  38404. return this._buttonRightStick;
  38405. },
  38406. set: function (value) {
  38407. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38408. },
  38409. enumerable: true,
  38410. configurable: true
  38411. });
  38412. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38413. get: function () {
  38414. return this._dPadUp;
  38415. },
  38416. set: function (value) {
  38417. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38418. },
  38419. enumerable: true,
  38420. configurable: true
  38421. });
  38422. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38423. get: function () {
  38424. return this._dPadDown;
  38425. },
  38426. set: function (value) {
  38427. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38428. },
  38429. enumerable: true,
  38430. configurable: true
  38431. });
  38432. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38433. get: function () {
  38434. return this._dPadLeft;
  38435. },
  38436. set: function (value) {
  38437. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38438. },
  38439. enumerable: true,
  38440. configurable: true
  38441. });
  38442. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38443. get: function () {
  38444. return this._dPadRight;
  38445. },
  38446. set: function (value) {
  38447. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38448. },
  38449. enumerable: true,
  38450. configurable: true
  38451. });
  38452. Xbox360Pad.prototype.update = function () {
  38453. _super.prototype.update.call(this);
  38454. this.buttonA = this.browserGamepad.buttons[0].value;
  38455. this.buttonB = this.browserGamepad.buttons[1].value;
  38456. this.buttonX = this.browserGamepad.buttons[2].value;
  38457. this.buttonY = this.browserGamepad.buttons[3].value;
  38458. this.buttonLB = this.browserGamepad.buttons[4].value;
  38459. this.buttonRB = this.browserGamepad.buttons[5].value;
  38460. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38461. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38462. this.buttonBack = this.browserGamepad.buttons[8].value;
  38463. this.buttonStart = this.browserGamepad.buttons[9].value;
  38464. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38465. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38466. this.dPadUp = this.browserGamepad.buttons[12].value;
  38467. this.dPadDown = this.browserGamepad.buttons[13].value;
  38468. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38469. this.dPadRight = this.browserGamepad.buttons[15].value;
  38470. };
  38471. return Xbox360Pad;
  38472. })(Gamepad);
  38473. BABYLON.Xbox360Pad = Xbox360Pad;
  38474. })(BABYLON || (BABYLON = {}));
  38475. var BABYLON;
  38476. (function (BABYLON) {
  38477. // We're mainly based on the logic defined into the FreeCamera code
  38478. var GamepadCamera = (function (_super) {
  38479. __extends(GamepadCamera, _super);
  38480. function GamepadCamera(name, position, scene) {
  38481. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38482. _super.call(this, name, position, scene);
  38483. }
  38484. GamepadCamera.prototype.getTypeName = function () {
  38485. return "GamepadCamera";
  38486. };
  38487. return GamepadCamera;
  38488. })(BABYLON.UniversalCamera);
  38489. BABYLON.GamepadCamera = GamepadCamera;
  38490. })(BABYLON || (BABYLON = {}));
  38491. var BABYLON;
  38492. (function (BABYLON) {
  38493. var AnaglyphFreeCamera = (function (_super) {
  38494. __extends(AnaglyphFreeCamera, _super);
  38495. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38496. _super.call(this, name, position, scene);
  38497. this.interaxialDistance = interaxialDistance;
  38498. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38499. }
  38500. AnaglyphFreeCamera.prototype.getTypeName = function () {
  38501. return "AnaglyphFreeCamera";
  38502. };
  38503. return AnaglyphFreeCamera;
  38504. })(BABYLON.FreeCamera);
  38505. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  38506. var AnaglyphArcRotateCamera = (function (_super) {
  38507. __extends(AnaglyphArcRotateCamera, _super);
  38508. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  38509. _super.call(this, name, alpha, beta, radius, target, scene);
  38510. this.interaxialDistance = interaxialDistance;
  38511. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38512. }
  38513. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  38514. return "AnaglyphArcRotateCamera";
  38515. };
  38516. return AnaglyphArcRotateCamera;
  38517. })(BABYLON.ArcRotateCamera);
  38518. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  38519. var AnaglyphGamepadCamera = (function (_super) {
  38520. __extends(AnaglyphGamepadCamera, _super);
  38521. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  38522. _super.call(this, name, position, scene);
  38523. this.interaxialDistance = interaxialDistance;
  38524. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38525. }
  38526. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  38527. return "AnaglyphGamepadCamera";
  38528. };
  38529. return AnaglyphGamepadCamera;
  38530. })(BABYLON.GamepadCamera);
  38531. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  38532. var AnaglyphUniversalCamera = (function (_super) {
  38533. __extends(AnaglyphUniversalCamera, _super);
  38534. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  38535. _super.call(this, name, position, scene);
  38536. this.interaxialDistance = interaxialDistance;
  38537. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38538. }
  38539. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  38540. return "AnaglyphUniversalCamera";
  38541. };
  38542. return AnaglyphUniversalCamera;
  38543. })(BABYLON.UniversalCamera);
  38544. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  38545. var StereoscopicFreeCamera = (function (_super) {
  38546. __extends(StereoscopicFreeCamera, _super);
  38547. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38548. _super.call(this, name, position, scene);
  38549. this.interaxialDistance = interaxialDistance;
  38550. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38551. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38552. }
  38553. StereoscopicFreeCamera.prototype.getTypeName = function () {
  38554. return "StereoscopicFreeCamera";
  38555. };
  38556. return StereoscopicFreeCamera;
  38557. })(BABYLON.FreeCamera);
  38558. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  38559. var StereoscopicArcRotateCamera = (function (_super) {
  38560. __extends(StereoscopicArcRotateCamera, _super);
  38561. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  38562. _super.call(this, name, alpha, beta, radius, target, scene);
  38563. this.interaxialDistance = interaxialDistance;
  38564. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38565. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38566. }
  38567. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  38568. return "StereoscopicArcRotateCamera";
  38569. };
  38570. return StereoscopicArcRotateCamera;
  38571. })(BABYLON.ArcRotateCamera);
  38572. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  38573. var StereoscopicGamepadCamera = (function (_super) {
  38574. __extends(StereoscopicGamepadCamera, _super);
  38575. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38576. _super.call(this, name, position, scene);
  38577. this.interaxialDistance = interaxialDistance;
  38578. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38579. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38580. }
  38581. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  38582. return "StereoscopicGamepadCamera";
  38583. };
  38584. return StereoscopicGamepadCamera;
  38585. })(BABYLON.GamepadCamera);
  38586. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  38587. var StereoscopicUniversalCamera = (function (_super) {
  38588. __extends(StereoscopicUniversalCamera, _super);
  38589. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  38590. _super.call(this, name, position, scene);
  38591. this.interaxialDistance = interaxialDistance;
  38592. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  38593. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38594. }
  38595. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  38596. return "StereoscopicUniversalCamera";
  38597. };
  38598. return StereoscopicUniversalCamera;
  38599. })(BABYLON.UniversalCamera);
  38600. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  38601. })(BABYLON || (BABYLON = {}));
  38602. var BABYLON;
  38603. (function (BABYLON) {
  38604. var Internals;
  38605. (function (Internals) {
  38606. var PMREMGenerator = (function () {
  38607. function PMREMGenerator() {
  38608. }
  38609. return PMREMGenerator;
  38610. })();
  38611. Internals.PMREMGenerator = PMREMGenerator;
  38612. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38613. })(BABYLON || (BABYLON = {}));
  38614. var BABYLON;
  38615. (function (BABYLON) {
  38616. var Internals;
  38617. (function (Internals) {
  38618. var FileFaceOrientation = (function () {
  38619. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  38620. this.name = name;
  38621. this.worldAxisForNormal = worldAxisForNormal;
  38622. this.worldAxisForFileX = worldAxisForFileX;
  38623. this.worldAxisForFileY = worldAxisForFileY;
  38624. }
  38625. return FileFaceOrientation;
  38626. })();
  38627. ;
  38628. var CubeMapToSphericalPolynomialTools = (function () {
  38629. function CubeMapToSphericalPolynomialTools() {
  38630. }
  38631. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  38632. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  38633. var totalSolidAngle = 0.0;
  38634. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  38635. var du = 2.0 / cubeInfo.size;
  38636. var dv = du;
  38637. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  38638. var minUV = du * 0.5 - 1.0;
  38639. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  38640. var fileFace = this.FileFaces[faceIndex];
  38641. var dataArray = cubeInfo[fileFace.name];
  38642. var v = minUV;
  38643. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  38644. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  38645. // Because SP is still linear, so summation is fine in that basis.
  38646. for (var y = 0; y < cubeInfo.size; y++) {
  38647. var u = minUV;
  38648. for (var x = 0; x < cubeInfo.size; x++) {
  38649. // World direction (not normalised)
  38650. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  38651. worldDirection.normalize();
  38652. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  38653. if (1) {
  38654. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  38655. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  38656. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  38657. var color = new BABYLON.Color3(r, g, b);
  38658. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38659. }
  38660. else {
  38661. if (faceIndex == 0) {
  38662. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38663. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38664. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38665. }
  38666. else if (faceIndex == 1) {
  38667. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38668. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38669. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38670. }
  38671. else if (faceIndex == 2) {
  38672. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38673. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38674. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38675. }
  38676. else if (faceIndex == 3) {
  38677. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38678. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38679. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38680. }
  38681. else if (faceIndex == 4) {
  38682. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38683. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38684. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38685. }
  38686. else if (faceIndex == 5) {
  38687. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38688. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38689. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38690. }
  38691. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  38692. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38693. }
  38694. totalSolidAngle += deltaSolidAngle;
  38695. u += du;
  38696. }
  38697. v += dv;
  38698. }
  38699. }
  38700. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  38701. var correction = correctSolidAngle / totalSolidAngle;
  38702. sphericalHarmonics.scale(correction);
  38703. // Additionally scale by pi -- audit needed
  38704. sphericalHarmonics.scale(1.0 / Math.PI);
  38705. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  38706. };
  38707. CubeMapToSphericalPolynomialTools.FileFaces = [
  38708. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  38709. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  38710. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  38711. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  38712. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  38713. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  38714. ];
  38715. return CubeMapToSphericalPolynomialTools;
  38716. })();
  38717. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  38718. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38719. })(BABYLON || (BABYLON = {}));
  38720. var BABYLON;
  38721. (function (BABYLON) {
  38722. var Internals;
  38723. (function (Internals) {
  38724. var PanoramaToCubeMapTools = (function () {
  38725. function PanoramaToCubeMapTools() {
  38726. }
  38727. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  38728. if (!float32Array) {
  38729. throw "ConvertPanoramaToCubemap: input cannot be null";
  38730. }
  38731. if (float32Array.length != inputWidth * inputHeight * 3) {
  38732. throw "ConvertPanoramaToCubemap: input size is wrong";
  38733. }
  38734. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  38735. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  38736. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  38737. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  38738. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  38739. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  38740. return {
  38741. front: textureFront,
  38742. back: textureBack,
  38743. left: textureLeft,
  38744. right: textureRight,
  38745. up: textureUp,
  38746. down: textureDown,
  38747. size: size
  38748. };
  38749. };
  38750. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  38751. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  38752. var textureArray = new Float32Array(buffer);
  38753. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  38754. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  38755. var dy = 1 / texSize;
  38756. var fy = 0;
  38757. for (var y = 0; y < texSize; y++) {
  38758. var xv1 = faceData[0];
  38759. var xv2 = faceData[2];
  38760. for (var x = 0; x < texSize; x++) {
  38761. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  38762. v.normalize();
  38763. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  38764. // 3 channels per pixels
  38765. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  38766. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  38767. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  38768. xv1 = xv1.add(rotDX1);
  38769. xv2 = xv2.add(rotDX2);
  38770. }
  38771. fy += dy;
  38772. }
  38773. return textureArray;
  38774. };
  38775. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  38776. var theta = Math.atan2(vDir.z, vDir.x);
  38777. var phi = Math.acos(vDir.y);
  38778. while (theta < -Math.PI)
  38779. theta += 2 * Math.PI;
  38780. while (theta > Math.PI)
  38781. theta -= 2 * Math.PI;
  38782. var dx = theta / Math.PI;
  38783. var dy = phi / Math.PI;
  38784. // recenter.
  38785. dx = dx * 0.5 + 0.5;
  38786. var px = Math.round(dx * inputWidth);
  38787. if (px < 0)
  38788. px = 0;
  38789. else if (px >= inputWidth)
  38790. px = inputWidth - 1;
  38791. var py = Math.round(dy * inputHeight);
  38792. if (py < 0)
  38793. py = 0;
  38794. else if (py >= inputHeight)
  38795. py = inputHeight - 1;
  38796. var inputY = (inputHeight - py - 1);
  38797. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  38798. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  38799. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  38800. return {
  38801. r: r,
  38802. g: g,
  38803. b: b
  38804. };
  38805. };
  38806. PanoramaToCubeMapTools.FACE_FRONT = [
  38807. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38808. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38809. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38810. new BABYLON.Vector3(1.0, 1.0, -1.0)
  38811. ];
  38812. PanoramaToCubeMapTools.FACE_BACK = [
  38813. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38814. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38815. new BABYLON.Vector3(1.0, 1.0, 1.0),
  38816. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  38817. ];
  38818. PanoramaToCubeMapTools.FACE_LEFT = [
  38819. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38820. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38821. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38822. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38823. ];
  38824. PanoramaToCubeMapTools.FACE_RIGHT = [
  38825. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38826. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38827. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38828. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  38829. ];
  38830. PanoramaToCubeMapTools.FACE_UP = [
  38831. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38832. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38833. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38834. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38835. ];
  38836. PanoramaToCubeMapTools.FACE_DOWN = [
  38837. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38838. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38839. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38840. new BABYLON.Vector3(1.0, -1.0, -1.0)
  38841. ];
  38842. return PanoramaToCubeMapTools;
  38843. })();
  38844. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  38845. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38846. })(BABYLON || (BABYLON = {}));
  38847. var BABYLON;
  38848. (function (BABYLON) {
  38849. var Internals;
  38850. (function (Internals) {
  38851. ;
  38852. var HDRTools = (function () {
  38853. function HDRTools() {
  38854. }
  38855. HDRTools.Ldexp = function (mantissa, exponent) {
  38856. if (exponent > 1023) {
  38857. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  38858. }
  38859. if (exponent < -1074) {
  38860. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  38861. }
  38862. return mantissa * Math.pow(2, exponent);
  38863. };
  38864. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  38865. if (exponent > 0) {
  38866. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  38867. float32array[index + 0] = red * exponent;
  38868. float32array[index + 1] = green * exponent;
  38869. float32array[index + 2] = blue * exponent;
  38870. }
  38871. else {
  38872. float32array[index + 0] = 0;
  38873. float32array[index + 1] = 0;
  38874. float32array[index + 2] = 0;
  38875. }
  38876. };
  38877. HDRTools.readStringLine = function (uint8array, startIndex) {
  38878. var line = "";
  38879. var character = "";
  38880. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  38881. character = String.fromCharCode(uint8array[i]);
  38882. if (character == "\n") {
  38883. break;
  38884. }
  38885. line += character;
  38886. }
  38887. return line;
  38888. };
  38889. /* minimal header reading. modify if you want to parse more information */
  38890. HDRTools.RGBE_ReadHeader = function (uint8array) {
  38891. var height = 0;
  38892. var width = 0;
  38893. var line = this.readStringLine(uint8array, 0);
  38894. if (line[0] != '#' || line[1] != '?') {
  38895. throw "Bad HDR Format.";
  38896. }
  38897. var endOfHeader = false;
  38898. var findFormat = false;
  38899. var lineIndex = 0;
  38900. do {
  38901. lineIndex += (line.length + 1);
  38902. line = this.readStringLine(uint8array, lineIndex);
  38903. if (line == "FORMAT=32-bit_rle_rgbe") {
  38904. findFormat = true;
  38905. }
  38906. else if (line.length == 0) {
  38907. endOfHeader = true;
  38908. }
  38909. } while (!endOfHeader);
  38910. if (!findFormat) {
  38911. throw "HDR Bad header format, unsupported FORMAT";
  38912. }
  38913. lineIndex += (line.length + 1);
  38914. line = this.readStringLine(uint8array, lineIndex);
  38915. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  38916. var match = sizeRegexp.exec(line);
  38917. // TODO. Support +Y and -X if needed.
  38918. if (match.length < 3) {
  38919. throw "HDR Bad header format, no size";
  38920. }
  38921. width = parseInt(match[2]);
  38922. height = parseInt(match[1]);
  38923. if (width < 8 || width > 0x7fff) {
  38924. throw "HDR Bad header format, unsupported size";
  38925. }
  38926. lineIndex += (line.length + 1);
  38927. return {
  38928. height: height,
  38929. width: width,
  38930. dataPosition: lineIndex
  38931. };
  38932. };
  38933. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  38934. var uint8array = new Uint8Array(buffer);
  38935. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  38936. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38937. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  38938. return cubeMapData;
  38939. };
  38940. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  38941. // Keep for multi format supports.
  38942. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38943. };
  38944. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  38945. var num_scanlines = hdrInfo.height;
  38946. var scanline_width = hdrInfo.width;
  38947. var a, b, c, d, count;
  38948. var dataIndex = hdrInfo.dataPosition;
  38949. var index = 0, endIndex = 0, i = 0;
  38950. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  38951. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  38952. // 3 channels of 4 bytes per pixel in float.
  38953. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  38954. var resultArray = new Float32Array(resultBuffer);
  38955. // read in each successive scanline
  38956. while (num_scanlines > 0) {
  38957. a = uint8array[dataIndex++];
  38958. b = uint8array[dataIndex++];
  38959. c = uint8array[dataIndex++];
  38960. d = uint8array[dataIndex++];
  38961. if (a != 2 || b != 2 || (c & 0x80)) {
  38962. // this file is not run length encoded
  38963. throw "HDR Bad header format, not RLE";
  38964. }
  38965. if (((c << 8) | d) != scanline_width) {
  38966. throw "HDR Bad header format, wrong scan line width";
  38967. }
  38968. index = 0;
  38969. // read each of the four channels for the scanline into the buffer
  38970. for (i = 0; i < 4; i++) {
  38971. endIndex = (i + 1) * scanline_width;
  38972. while (index < endIndex) {
  38973. a = uint8array[dataIndex++];
  38974. b = uint8array[dataIndex++];
  38975. if (a > 128) {
  38976. // a run of the same value
  38977. count = a - 128;
  38978. if ((count == 0) || (count > endIndex - index)) {
  38979. throw "HDR Bad Format, bad scanline data (run)";
  38980. }
  38981. while (count-- > 0) {
  38982. scanLineArray[index++] = b;
  38983. }
  38984. }
  38985. else {
  38986. // a non-run
  38987. count = a;
  38988. if ((count == 0) || (count > endIndex - index)) {
  38989. throw "HDR Bad Format, bad scanline data (non-run)";
  38990. }
  38991. scanLineArray[index++] = b;
  38992. if (--count > 0) {
  38993. for (var j = 0; j < count; j++) {
  38994. scanLineArray[index++] = uint8array[dataIndex++];
  38995. }
  38996. }
  38997. }
  38998. }
  38999. }
  39000. // now convert data from buffer into floats
  39001. for (i = 0; i < scanline_width; i++) {
  39002. a = scanLineArray[i];
  39003. b = scanLineArray[i + scanline_width];
  39004. c = scanLineArray[i + 2 * scanline_width];
  39005. d = scanLineArray[i + 3 * scanline_width];
  39006. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  39007. }
  39008. num_scanlines--;
  39009. }
  39010. return resultArray;
  39011. };
  39012. return HDRTools;
  39013. })();
  39014. Internals.HDRTools = HDRTools;
  39015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39016. })(BABYLON || (BABYLON = {}));
  39017. var BABYLON;
  39018. (function (BABYLON) {
  39019. var HDRCubeTexture = (function (_super) {
  39020. __extends(HDRCubeTexture, _super);
  39021. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace) {
  39022. if (noMipmap === void 0) { noMipmap = false; }
  39023. if (generateHarmonics === void 0) { generateHarmonics = true; }
  39024. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  39025. _super.call(this, scene);
  39026. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  39027. this._useInGammaSpace = false;
  39028. this._generateHarmonics = true;
  39029. this.sphericalPolynomial = null;
  39030. this.name = url;
  39031. this.url = url;
  39032. this._noMipmap = noMipmap;
  39033. this.hasAlpha = false;
  39034. this._size = size;
  39035. this._useInGammaSpace = useInGammaSpace;
  39036. if (!url) {
  39037. return;
  39038. }
  39039. this._texture = this._getFromCache(url, noMipmap);
  39040. if (!this._texture) {
  39041. if (!scene.useDelayedTextureLoading) {
  39042. this.loadTexture();
  39043. }
  39044. else {
  39045. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39046. }
  39047. }
  39048. this.isCube = true;
  39049. this._textureMatrix = BABYLON.Matrix.Identity();
  39050. }
  39051. HDRCubeTexture.prototype.loadTexture = function () {
  39052. var _this = this;
  39053. var callback = function (buffer) {
  39054. // Extract the raw linear data.
  39055. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  39056. // Generate harmonics if needed.
  39057. if (_this._generateHarmonics) {
  39058. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  39059. }
  39060. var results = [];
  39061. var byteArray = null;
  39062. // Create uintarray fallback.
  39063. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  39064. // 3 channels of 1 bytes per pixel in bytes.
  39065. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  39066. byteArray = new Uint8Array(byteBuffer);
  39067. }
  39068. // Push each faces.
  39069. for (var j = 0; j < 6; j++) {
  39070. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  39071. // If special cases.
  39072. if (_this._useInGammaSpace || byteArray) {
  39073. for (var i = 0; i < _this._size * _this._size; i++) {
  39074. // Put in gamma space if requested.
  39075. if (_this._useInGammaSpace) {
  39076. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  39077. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  39078. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  39079. }
  39080. // Convert to int texture for fallback.
  39081. if (byteArray) {
  39082. // R
  39083. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  39084. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  39085. // G
  39086. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  39087. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  39088. // B
  39089. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  39090. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  39091. }
  39092. }
  39093. }
  39094. results.push(dataFace);
  39095. }
  39096. return results;
  39097. };
  39098. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  39099. };
  39100. HDRCubeTexture.prototype.clone = function () {
  39101. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace);
  39102. // Base texture
  39103. newTexture.level = this.level;
  39104. newTexture.wrapU = this.wrapU;
  39105. newTexture.wrapV = this.wrapV;
  39106. newTexture.coordinatesIndex = this.coordinatesIndex;
  39107. newTexture.coordinatesMode = this.coordinatesMode;
  39108. return newTexture;
  39109. };
  39110. // Methods
  39111. HDRCubeTexture.prototype.delayLoad = function () {
  39112. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39113. return;
  39114. }
  39115. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39116. this._texture = this._getFromCache(this.url, this._noMipmap);
  39117. if (!this._texture) {
  39118. this.loadTexture();
  39119. }
  39120. };
  39121. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  39122. return this._textureMatrix;
  39123. };
  39124. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39125. var texture = null;
  39126. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39127. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace);
  39128. texture.name = parsedTexture.name;
  39129. texture.hasAlpha = parsedTexture.hasAlpha;
  39130. texture.level = parsedTexture.level;
  39131. texture.coordinatesMode = parsedTexture.coordinatesMode;
  39132. }
  39133. return texture;
  39134. };
  39135. HDRCubeTexture.prototype.serialize = function () {
  39136. if (!this.name) {
  39137. return null;
  39138. }
  39139. var serializationObject = {};
  39140. serializationObject.name = this.name;
  39141. serializationObject.hasAlpha = this.hasAlpha;
  39142. serializationObject.isCube = true;
  39143. serializationObject.level = this.level;
  39144. serializationObject.size = this._size;
  39145. serializationObject.coordinatesMode = this.coordinatesMode;
  39146. serializationObject.useInGammaSpace = this._useInGammaSpace;
  39147. serializationObject.generateHarmonics = this._generateHarmonics;
  39148. return serializationObject;
  39149. };
  39150. HDRCubeTexture._facesMapping = [
  39151. "left",
  39152. "down",
  39153. "front",
  39154. "right",
  39155. "up",
  39156. "back"
  39157. ];
  39158. return HDRCubeTexture;
  39159. })(BABYLON.BaseTexture);
  39160. BABYLON.HDRCubeTexture = HDRCubeTexture;
  39161. })(BABYLON || (BABYLON = {}));
  39162. 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#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\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(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\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#include<fresnelFunction>\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#endif\r\n\r\n#include<reflectionFunction>\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#include<bumpFragmentFunctions>\r\n#include<clipPlaneFragmentDeclaration>\r\n#include<logDepthDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\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\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#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\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\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 REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\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#ifdef REFLECTIONOVERALPHA\r\n\talpha = clamp(alpha + dot(reflectionColor, 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 + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, 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#include<logDepthFragment>\r\n#include<fogFragment>\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#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<pointCloudVertexDeclaration>\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#include<clipPlaneVertexDeclaration>\r\n\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<logDepthDeclaration>\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\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#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n#include<pointCloudVertex>\r\n#include<logDepthVertex>\r\n\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n\r\n#include<bonesVertex>\r\n\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#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\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#include<fresnelFunction>\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#include<clipPlaneFragmentDeclaration>\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n#include<clipPlaneFragment>\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\tfloat glossiness = 0.;\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tglossiness = vSpecularColor.a;\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\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#include<fogFragment>\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#include<bonesDeclaration>\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#include<clipPlaneVertexDeclaration>\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\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#include<bonesVertex>\r\n\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#include<clipPlaneVertex>\r\n#include<fogVertex>\r\n#include<shadowsVertex>\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#include<bonesDeclaration>\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\r\n\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\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\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#include<instancesVertex>\r\n#include<bonesVertex>\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#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\tvec4 color = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (color.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tcolor *= vColor;\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\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#include<fogVertexDeclaration>\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}"};
  39163. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2;var i=function(){function i(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.prototype.toLinearSpace=function(){var t=new i;return this.toLinearSpaceToRef(t),t},i.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},i.prototype.toGammaSpace=function(){var t=new i;return this.toGammaSpaceToRef(t),t},i.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=n;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=r;var o=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=y.X,u=y.Y,m=0,c=0,p=0,f=0,l=0,x=0,z=0,w=-1,v=0,d=M.Vector3[0],g=0,T=M.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?f=1:(z=h.z/h.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=f,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),p=Math.acos(g)*w,i.Dot(T,a)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),v++);var R=M.Vector3[2],_=M.Vector3[3];f=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?f=1:(z=T.z/T.x,f=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=f,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=p},i}();t.Vector3=o;var s=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=s;var e=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=o.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=e;var h=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,S=h*y-a*c,E=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*S-r*E+o*q)*b,t.m[7]=(i*S-r*D+o*V)*b,t.m[11]=-(i*E-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],c=this.m[8],y=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],S=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*S,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*S,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*S,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*S,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=c,x.m[12]=y,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=c,z.m[11]=y,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,\ni.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){e.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var s=new o(0,0,0),h=new e,a=new o(0,0,0);t.decompose(s,h,a);var u=new o(0,0,0),m=new e,c=new o(0,0,0);n.decompose(u,m,c);var y=o.Lerp(s,u,r),p=e.Slerp(h,m,r),f=o.Lerp(a,c,r);return i.Compose(y,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(c)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,c)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return o.Dot(n,i)+r},t}();t.Plane=a;var u=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var c=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var y=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=y;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new o(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new r(i,n),u=new r(o,s),m=new x(h,a,u),c=m.angle.radians()/e;m.orientation===f.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var l=Math.cos(y)*m.radius+m.centerPoint.x,z=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(l,z),y+=c}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var c=u.normalize(),y=n-o;return new r(h.x+c.x*y,h.y+c.y*y)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var s;if(void 0===r||null===r){var e;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=o.Zero(),this.L1_1=o.Zero(),this.L10=o.Zero(),this.L11=o.Zero(),this.L2_2=o.Zero(),this.L2_1=o.Zero(),this.L20=o.Zero(),this.L21=o.Zero(),this.L22=o.Zero()}return t.prototype.addLight=function(t,i,n){var r=new o(i.r,i.g,i.b),s=r.scale(n);this.L00=this.L00.add(s.scale(.282095)),this.L1_1=this.L1_1.add(s.scale(.488603*t.y)),this.L10=this.L10.add(s.scale(.488603*t.z)),this.L11=this.L11.add(s.scale(.488603*t.x)),this.L2_2=this.L2_2.add(s.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(s.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(s.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(s.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(s.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=o.Zero(),this.y=o.Zero(),this.z=o.Zero(),this.xx=o.Zero(),this.yy=o.Zero(),this.zz=o.Zero(),this.xy=o.Zero(),this.yz=o.Zero(),this.zx=o.Zero()}return t.prototype.addAmbient=function(t){var i=new o(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[i.Black(),i.Black(),i.Black()],t.Vector2=[r.Zero(),r.Zero(),r.Zero()],t.Vector3=[o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero(),o.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new e(0,0,0,0)],t.Matrix=[h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero(),h.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  39164. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#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","bonesVertex":"#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\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","bumpFragmentFunctions":"#ifdef BUMP\r\n\tvarying vec2 vBumpUV;\r\n\tuniform vec2 vBumpInfos;\r\n\tuniform sampler2D bumpSampler;\r\n\r\n\t// Thanks to http://www.thetenthplanet.de/archives/1180\r\n\tmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n\t{\r\n\t\t// get edge vectors of the pixel triangle\r\n\t\tvec3 dp1 = dFdx(p);\r\n\t\tvec3 dp2 = dFdy(p);\r\n\t\tvec2 duv1 = dFdx(uv);\r\n\t\tvec2 duv2 = dFdy(uv);\r\n\r\n\t\t// solve the linear system\r\n\t\tvec3 dp2perp = cross(dp2, normal);\r\n\t\tvec3 dp1perp = cross(normal, dp1);\r\n\t\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\t\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t\t// construct a scale-invariant frame \r\n\t\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\t\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n\t}\r\n\r\n\tvec3 perturbNormal(vec3 viewDir)\r\n\t{\r\n\t\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\t\tmap = map * 255. / 127. - 128. / 127.;\r\n\t\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\t\treturn normalize(TBN * map);\r\n\t}\r\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t{\r\n\t\tdiscard;\r\n\t}\r\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\r\n\tvarying float fClipDistance;\r\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\r\n\tuniform vec4 vClipPlane;\r\n\tvarying float fClipDistance;\r\n#endif","fogFragment":"#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif","fogFragmentDeclaration":"#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","fogVertex":"#ifdef FOG\r\nfFogDistance = (view * worldPos).z;\r\n#endif","fogVertexDeclaration":"#ifdef FOG\r\n\tvarying float fFogDistance;\r\n#endif","fresnelFunction":"#ifdef FRESNEL\r\n\tfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n\t{\r\n\t\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\t\treturn clamp(fresnelTerm, 0., 1.);\r\n\t}\r\n#endif","instancesDeclaration":"#ifdef INSTANCES\r\n\tattribute vec4 world0;\r\n\tattribute vec4 world1;\r\n\tattribute vec4 world2;\r\n\tattribute vec4 world3;\r\n#else\r\n\tuniform mat4 world;\r\n#endif","instancesVertex":"#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif","light0Fragment":"#ifdef LIGHT0\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular0 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#ifdef SHADOWVSM0\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t#else\r\n\t\t#ifdef SHADOWPCF0\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\t\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\r\n\tuniform vec4 vLightData0;\r\n\tuniform vec4 vLightDiffuse0;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular0;\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\t\tvarying vec4 vPositionFromLight0;\r\n\t\t\tuniform sampler2D shadowSampler0;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler0;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo0;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tuniform vec4 vLightDirection0;\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tuniform vec3 vLightGround0;\r\n\t#endif\r\n#endif","light1Fragment":"#ifdef LIGHT1\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular1 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#ifdef SHADOWVSM1\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF1\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#else\r\n\t\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\r\n\tuniform vec4 vLightData1;\r\n\tuniform vec4 vLightDiffuse1;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular1;\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\t\tvarying vec4 vPositionFromLight1;\r\n\t\t\tuniform sampler2D shadowSampler1;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler1;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo1;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tuniform vec4 vLightDirection1;\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tuniform vec3 vLightGround1;\r\n\t#endif\r\n#endif","light2Fragment":"#ifdef LIGHT2\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular2 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#ifdef SHADOWVSM2\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF2\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\r\n\tuniform vec4 vLightData2;\r\n\tuniform vec4 vLightDiffuse2;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular2;\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\t\tvarying vec4 vPositionFromLight2;\r\n\t\t\tuniform sampler2D shadowSampler2;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler2;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo2;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tuniform vec4 vLightDirection2;\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tuniform vec3 vLightGround2;\r\n\t#endif\r\n#endif","light3Fragment":"#ifdef LIGHT3\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular3 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#ifdef SHADOWVSM3\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF3\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\r\n\tuniform vec4 vLightData3;\r\n\tuniform vec4 vLightDiffuse3;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular3;\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\t\tvarying vec4 vPositionFromLight3;\r\n\t\t\tuniform sampler2D shadowSampler3;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler3;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo3;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tuniform vec4 vLightDirection3;\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tuniform vec3 vLightGround3;\r\n\t#endif\r\n#endif","lightsFragmentFunctions":"// 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\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","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\r\n\tuniform float logarithmicDepthConstant;\r\n\tvarying float vFragmentDepth;\r\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif","pointCloudVertex":"#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\r\n\tuniform float pointSize;\r\n#endif","reflectionFunction":"vec3 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}","shadowsFragmentFunctions":"#ifdef SHADOWS\r\n\tfloat unpack(vec4 color)\r\n\t{\r\n\t\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\t\treturn dot(color, bit_shift);\r\n\t}\r\n\r\n\t#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\n\t\tuniform vec2 depthValues;\r\n\r\n\t\tfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\t\t\tif (depth > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.0;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec3 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\t\t\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth - bias;\r\n\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\t#endif\r\n\r\n\t#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\n\t\tfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\t\t\tif (depth.z > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec2 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\t\t\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\t\t\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\t\t\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth.z - bias;\r\n\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\r\n\t\t// Thanks to http://devmaster.net/\r\n\t\tfloat unpackHalf(vec2 color)\r\n\t\t{\r\n\t\t\treturn color.x + (color.y / 255.0);\r\n\t\t}\r\n\r\n\t\tfloat linstep(float low, float high, float v) {\r\n\t\t\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n\t\t{\r\n\t\t\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\t\t\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\t\t\tfloat d = compare - moments.x;\r\n\t\t\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\t\t\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\t\t\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\t\t\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n\t\t}\r\n\t#endif\r\n#endif","shadowsVertex":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n\t#endif\r\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tuniform mat4 lightMatrix0;\r\n\t\tvarying vec4 vPositionFromLight0;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tuniform mat4 lightMatrix1;\r\n\t\tvarying vec4 vPositionFromLight1;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tuniform mat4 lightMatrix2;\r\n\t\tvarying vec4 vPositionFromLight2;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tuniform mat4 lightMatrix3;\r\n\t\tvarying vec4 vPositionFromLight3;\r\n\t#endif\r\n#endif"};
  39165. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  39166. module.exports = BABYLON;
  39167. };