babylon.max.js 2.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. })();
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. })();
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.toVector3 = function () {
  1188. return new Vector3(this.x, this.y, this.z);
  1189. };
  1190. Vector4.prototype.clone = function () {
  1191. return new Vector4(this.x, this.y, this.z, this.w);
  1192. };
  1193. Vector4.prototype.copyFrom = function (source) {
  1194. this.x = source.x;
  1195. this.y = source.y;
  1196. this.z = source.z;
  1197. this.w = source.w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1201. this.x = x;
  1202. this.y = y;
  1203. this.z = z;
  1204. this.w = w;
  1205. return this;
  1206. };
  1207. // Statics
  1208. Vector4.FromArray = function (array, offset) {
  1209. if (!offset) {
  1210. offset = 0;
  1211. }
  1212. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1213. };
  1214. Vector4.FromArrayToRef = function (array, offset, result) {
  1215. result.x = array[offset];
  1216. result.y = array[offset + 1];
  1217. result.z = array[offset + 2];
  1218. result.w = array[offset + 3];
  1219. };
  1220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1221. result.x = array[offset];
  1222. result.y = array[offset + 1];
  1223. result.z = array[offset + 2];
  1224. result.w = array[offset + 3];
  1225. };
  1226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1227. result.x = x;
  1228. result.y = y;
  1229. result.z = z;
  1230. result.w = w;
  1231. };
  1232. Vector4.Zero = function () {
  1233. return new Vector4(0, 0, 0, 0);
  1234. };
  1235. Vector4.Normalize = function (vector) {
  1236. var result = Vector4.Zero();
  1237. Vector4.NormalizeToRef(vector, result);
  1238. return result;
  1239. };
  1240. Vector4.NormalizeToRef = function (vector, result) {
  1241. result.copyFrom(vector);
  1242. result.normalize();
  1243. };
  1244. Vector4.Minimize = function (left, right) {
  1245. var min = left.clone();
  1246. min.MinimizeInPlace(right);
  1247. return min;
  1248. };
  1249. Vector4.Maximize = function (left, right) {
  1250. var max = left.clone();
  1251. max.MaximizeInPlace(right);
  1252. return max;
  1253. };
  1254. Vector4.Distance = function (value1, value2) {
  1255. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1256. };
  1257. Vector4.DistanceSquared = function (value1, value2) {
  1258. var x = value1.x - value2.x;
  1259. var y = value1.y - value2.y;
  1260. var z = value1.z - value2.z;
  1261. var w = value1.w - value2.w;
  1262. return (x * x) + (y * y) + (z * z) + (w * w);
  1263. };
  1264. Vector4.Center = function (value1, value2) {
  1265. var center = value1.add(value2);
  1266. center.scaleInPlace(0.5);
  1267. return center;
  1268. };
  1269. return Vector4;
  1270. })();
  1271. BABYLON.Vector4 = Vector4;
  1272. var Size = (function () {
  1273. function Size(width, height) {
  1274. this.width = width;
  1275. this.height = height;
  1276. }
  1277. Size.prototype.clone = function () {
  1278. return new Size(this.width, this.height);
  1279. };
  1280. Size.prototype.equals = function (other) {
  1281. if (!other) {
  1282. return false;
  1283. }
  1284. return (this.width === other.width) && (this.height === other.height);
  1285. };
  1286. Object.defineProperty(Size.prototype, "surface", {
  1287. get: function () {
  1288. return this.width * this.height;
  1289. },
  1290. enumerable: true,
  1291. configurable: true
  1292. });
  1293. Size.Zero = function () {
  1294. return new Size(0, 0);
  1295. };
  1296. return Size;
  1297. })();
  1298. BABYLON.Size = Size;
  1299. var Quaternion = (function () {
  1300. function Quaternion(x, y, z, w) {
  1301. if (x === void 0) { x = 0; }
  1302. if (y === void 0) { y = 0; }
  1303. if (z === void 0) { z = 0; }
  1304. if (w === void 0) { w = 1; }
  1305. this.x = x;
  1306. this.y = y;
  1307. this.z = z;
  1308. this.w = w;
  1309. }
  1310. Quaternion.prototype.toString = function () {
  1311. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1312. };
  1313. Quaternion.prototype.asArray = function () {
  1314. return [this.x, this.y, this.z, this.w];
  1315. };
  1316. Quaternion.prototype.equals = function (otherQuaternion) {
  1317. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1318. };
  1319. Quaternion.prototype.clone = function () {
  1320. return new Quaternion(this.x, this.y, this.z, this.w);
  1321. };
  1322. Quaternion.prototype.copyFrom = function (other) {
  1323. this.x = other.x;
  1324. this.y = other.y;
  1325. this.z = other.z;
  1326. this.w = other.w;
  1327. return this;
  1328. };
  1329. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1330. this.x = x;
  1331. this.y = y;
  1332. this.z = z;
  1333. this.w = w;
  1334. return this;
  1335. };
  1336. Quaternion.prototype.add = function (other) {
  1337. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1338. };
  1339. Quaternion.prototype.subtract = function (other) {
  1340. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1341. };
  1342. Quaternion.prototype.scale = function (value) {
  1343. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1344. };
  1345. Quaternion.prototype.multiply = function (q1) {
  1346. var result = new Quaternion(0, 0, 0, 1.0);
  1347. this.multiplyToRef(q1, result);
  1348. return result;
  1349. };
  1350. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1351. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1352. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1353. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1354. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1355. result.copyFromFloats(x, y, z, w);
  1356. return this;
  1357. };
  1358. Quaternion.prototype.multiplyInPlace = function (q1) {
  1359. this.multiplyToRef(q1, this);
  1360. return this;
  1361. };
  1362. Quaternion.prototype.conjugateToRef = function (ref) {
  1363. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1364. return this;
  1365. };
  1366. Quaternion.prototype.conjugateInPlace = function () {
  1367. this.x *= -1;
  1368. this.y *= -1;
  1369. this.z *= -1;
  1370. return this;
  1371. };
  1372. Quaternion.prototype.conjugate = function () {
  1373. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1374. return result;
  1375. };
  1376. Quaternion.prototype.length = function () {
  1377. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1378. };
  1379. Quaternion.prototype.normalize = function () {
  1380. var length = 1.0 / this.length();
  1381. this.x *= length;
  1382. this.y *= length;
  1383. this.z *= length;
  1384. this.w *= length;
  1385. return this;
  1386. };
  1387. Quaternion.prototype.toEulerAngles = function (order) {
  1388. if (order === void 0) { order = "YZX"; }
  1389. var result = Vector3.Zero();
  1390. this.toEulerAnglesToRef(result, order);
  1391. return result;
  1392. };
  1393. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1394. if (order === void 0) { order = "YZX"; }
  1395. var heading, attitude, bank;
  1396. var x = this.x, y = this.y, z = this.z, w = this.w;
  1397. switch (order) {
  1398. case "YZX":
  1399. var test = x * y + z * w;
  1400. if (test > 0.499) {
  1401. heading = 2 * Math.atan2(x, w);
  1402. attitude = Math.PI / 2;
  1403. bank = 0;
  1404. }
  1405. if (test < -0.499) {
  1406. heading = -2 * Math.atan2(x, w);
  1407. attitude = -Math.PI / 2;
  1408. bank = 0;
  1409. }
  1410. if (isNaN(heading)) {
  1411. var sqx = x * x;
  1412. var sqy = y * y;
  1413. var sqz = z * z;
  1414. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1415. attitude = Math.asin(2 * test); // attitude
  1416. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1417. }
  1418. break;
  1419. default:
  1420. throw new Error("Euler order " + order + " not supported yet.");
  1421. }
  1422. result.y = heading;
  1423. result.z = attitude;
  1424. result.x = bank;
  1425. return this;
  1426. };
  1427. ;
  1428. Quaternion.prototype.toRotationMatrix = function (result) {
  1429. var xx = this.x * this.x;
  1430. var yy = this.y * this.y;
  1431. var zz = this.z * this.z;
  1432. var xy = this.x * this.y;
  1433. var zw = this.z * this.w;
  1434. var zx = this.z * this.x;
  1435. var yw = this.y * this.w;
  1436. var yz = this.y * this.z;
  1437. var xw = this.x * this.w;
  1438. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1439. result.m[1] = 2.0 * (xy + zw);
  1440. result.m[2] = 2.0 * (zx - yw);
  1441. result.m[3] = 0;
  1442. result.m[4] = 2.0 * (xy - zw);
  1443. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1444. result.m[6] = 2.0 * (yz + xw);
  1445. result.m[7] = 0;
  1446. result.m[8] = 2.0 * (zx + yw);
  1447. result.m[9] = 2.0 * (yz - xw);
  1448. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1449. result.m[11] = 0;
  1450. result.m[12] = 0;
  1451. result.m[13] = 0;
  1452. result.m[14] = 0;
  1453. result.m[15] = 1.0;
  1454. return this;
  1455. };
  1456. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1457. Quaternion.FromRotationMatrixToRef(matrix, this);
  1458. return this;
  1459. };
  1460. // Statics
  1461. Quaternion.FromRotationMatrix = function (matrix) {
  1462. var result = new Quaternion();
  1463. Quaternion.FromRotationMatrixToRef(matrix, result);
  1464. return result;
  1465. };
  1466. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1467. var data = matrix.m;
  1468. var m11 = data[0], m12 = data[4], m13 = data[8];
  1469. var m21 = data[1], m22 = data[5], m23 = data[9];
  1470. var m31 = data[2], m32 = data[6], m33 = data[10];
  1471. var trace = m11 + m22 + m33;
  1472. var s;
  1473. if (trace > 0) {
  1474. s = 0.5 / Math.sqrt(trace + 1.0);
  1475. result.w = 0.25 / s;
  1476. result.x = (m32 - m23) * s;
  1477. result.y = (m13 - m31) * s;
  1478. result.z = (m21 - m12) * s;
  1479. }
  1480. else if (m11 > m22 && m11 > m33) {
  1481. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1482. result.w = (m32 - m23) / s;
  1483. result.x = 0.25 * s;
  1484. result.y = (m12 + m21) / s;
  1485. result.z = (m13 + m31) / s;
  1486. }
  1487. else if (m22 > m33) {
  1488. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1489. result.w = (m13 - m31) / s;
  1490. result.x = (m12 + m21) / s;
  1491. result.y = 0.25 * s;
  1492. result.z = (m23 + m32) / s;
  1493. }
  1494. else {
  1495. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1496. result.w = (m21 - m12) / s;
  1497. result.x = (m13 + m31) / s;
  1498. result.y = (m23 + m32) / s;
  1499. result.z = 0.25 * s;
  1500. }
  1501. };
  1502. Quaternion.Inverse = function (q) {
  1503. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1504. };
  1505. Quaternion.Identity = function () {
  1506. return new Quaternion(0, 0, 0, 1);
  1507. };
  1508. Quaternion.RotationAxis = function (axis, angle) {
  1509. var result = new Quaternion();
  1510. var sin = Math.sin(angle / 2);
  1511. axis.normalize();
  1512. result.w = Math.cos(angle / 2);
  1513. result.x = axis.x * sin;
  1514. result.y = axis.y * sin;
  1515. result.z = axis.z * sin;
  1516. return result;
  1517. };
  1518. Quaternion.FromArray = function (array, offset) {
  1519. if (!offset) {
  1520. offset = 0;
  1521. }
  1522. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1523. };
  1524. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1525. var result = new Quaternion();
  1526. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1527. return result;
  1528. };
  1529. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1530. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1531. var halfRoll = roll * 0.5;
  1532. var halfPitch = pitch * 0.5;
  1533. var halfYaw = yaw * 0.5;
  1534. var sinRoll = Math.sin(halfRoll);
  1535. var cosRoll = Math.cos(halfRoll);
  1536. var sinPitch = Math.sin(halfPitch);
  1537. var cosPitch = Math.cos(halfPitch);
  1538. var sinYaw = Math.sin(halfYaw);
  1539. var cosYaw = Math.cos(halfYaw);
  1540. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1541. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1542. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1543. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1544. };
  1545. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1546. var result = new Quaternion();
  1547. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1548. return result;
  1549. };
  1550. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1551. // Produces a quaternion from Euler angles in the z-x-z orientation
  1552. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1553. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1554. var halfBeta = beta * 0.5;
  1555. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1556. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1557. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1558. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1559. };
  1560. Quaternion.Slerp = function (left, right, amount) {
  1561. var num2;
  1562. var num3;
  1563. var num = amount;
  1564. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1565. var flag = false;
  1566. if (num4 < 0) {
  1567. flag = true;
  1568. num4 = -num4;
  1569. }
  1570. if (num4 > 0.999999) {
  1571. num3 = 1 - num;
  1572. num2 = flag ? -num : num;
  1573. }
  1574. else {
  1575. var num5 = Math.acos(num4);
  1576. var num6 = (1.0 / Math.sin(num5));
  1577. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1578. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1579. }
  1580. 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));
  1581. };
  1582. return Quaternion;
  1583. })();
  1584. BABYLON.Quaternion = Quaternion;
  1585. var Matrix = (function () {
  1586. function Matrix() {
  1587. this.m = new Float32Array(16);
  1588. }
  1589. // Properties
  1590. Matrix.prototype.isIdentity = function () {
  1591. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1592. return false;
  1593. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1594. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1595. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1596. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1597. return false;
  1598. return true;
  1599. };
  1600. Matrix.prototype.determinant = function () {
  1601. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1602. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1603. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1604. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1605. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1606. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1607. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1608. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1609. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1610. };
  1611. // Methods
  1612. Matrix.prototype.toArray = function () {
  1613. return this.m;
  1614. };
  1615. Matrix.prototype.asArray = function () {
  1616. return this.toArray();
  1617. };
  1618. Matrix.prototype.invert = function () {
  1619. this.invertToRef(this);
  1620. return this;
  1621. };
  1622. Matrix.prototype.reset = function () {
  1623. for (var index = 0; index < 16; index++) {
  1624. this.m[index] = 0;
  1625. }
  1626. return this;
  1627. };
  1628. Matrix.prototype.add = function (other) {
  1629. var result = new Matrix();
  1630. this.addToRef(other, result);
  1631. return result;
  1632. };
  1633. Matrix.prototype.addToRef = function (other, result) {
  1634. for (var index = 0; index < 16; index++) {
  1635. result.m[index] = this.m[index] + other.m[index];
  1636. }
  1637. return this;
  1638. };
  1639. Matrix.prototype.addToSelf = function (other) {
  1640. for (var index = 0; index < 16; index++) {
  1641. this.m[index] += other.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.invertToRef = function (other) {
  1646. var l1 = this.m[0];
  1647. var l2 = this.m[1];
  1648. var l3 = this.m[2];
  1649. var l4 = this.m[3];
  1650. var l5 = this.m[4];
  1651. var l6 = this.m[5];
  1652. var l7 = this.m[6];
  1653. var l8 = this.m[7];
  1654. var l9 = this.m[8];
  1655. var l10 = this.m[9];
  1656. var l11 = this.m[10];
  1657. var l12 = this.m[11];
  1658. var l13 = this.m[12];
  1659. var l14 = this.m[13];
  1660. var l15 = this.m[14];
  1661. var l16 = this.m[15];
  1662. var l17 = (l11 * l16) - (l12 * l15);
  1663. var l18 = (l10 * l16) - (l12 * l14);
  1664. var l19 = (l10 * l15) - (l11 * l14);
  1665. var l20 = (l9 * l16) - (l12 * l13);
  1666. var l21 = (l9 * l15) - (l11 * l13);
  1667. var l22 = (l9 * l14) - (l10 * l13);
  1668. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1669. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1670. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1671. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1672. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1673. var l28 = (l7 * l16) - (l8 * l15);
  1674. var l29 = (l6 * l16) - (l8 * l14);
  1675. var l30 = (l6 * l15) - (l7 * l14);
  1676. var l31 = (l5 * l16) - (l8 * l13);
  1677. var l32 = (l5 * l15) - (l7 * l13);
  1678. var l33 = (l5 * l14) - (l6 * l13);
  1679. var l34 = (l7 * l12) - (l8 * l11);
  1680. var l35 = (l6 * l12) - (l8 * l10);
  1681. var l36 = (l6 * l11) - (l7 * l10);
  1682. var l37 = (l5 * l12) - (l8 * l9);
  1683. var l38 = (l5 * l11) - (l7 * l9);
  1684. var l39 = (l5 * l10) - (l6 * l9);
  1685. other.m[0] = l23 * l27;
  1686. other.m[4] = l24 * l27;
  1687. other.m[8] = l25 * l27;
  1688. other.m[12] = l26 * l27;
  1689. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1690. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1691. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1692. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1693. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1694. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1695. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1696. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1697. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1698. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1699. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1700. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1701. return this;
  1702. };
  1703. Matrix.prototype.setTranslation = function (vector3) {
  1704. this.m[12] = vector3.x;
  1705. this.m[13] = vector3.y;
  1706. this.m[14] = vector3.z;
  1707. return this;
  1708. };
  1709. Matrix.prototype.getTranslation = function () {
  1710. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.equals = function (value) {
  1786. return value &&
  1787. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1788. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1789. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1790. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1791. };
  1792. Matrix.prototype.clone = function () {
  1793. 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]);
  1794. };
  1795. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1796. translation.x = this.m[12];
  1797. translation.y = this.m[13];
  1798. translation.z = this.m[14];
  1799. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1800. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1801. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1802. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1803. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1804. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1805. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1806. rotation.x = 0;
  1807. rotation.y = 0;
  1808. rotation.z = 0;
  1809. rotation.w = 1;
  1810. return false;
  1811. }
  1812. 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);
  1813. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1814. return true;
  1815. };
  1816. // Statics
  1817. Matrix.FromArray = function (array, offset) {
  1818. var result = new Matrix();
  1819. if (!offset) {
  1820. offset = 0;
  1821. }
  1822. Matrix.FromArrayToRef(array, offset, result);
  1823. return result;
  1824. };
  1825. Matrix.FromArrayToRef = function (array, offset, result) {
  1826. for (var index = 0; index < 16; index++) {
  1827. result.m[index] = array[index + offset];
  1828. }
  1829. };
  1830. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1831. for (var index = 0; index < 16; index++) {
  1832. result.m[index] = array[index + offset] * scale;
  1833. }
  1834. };
  1835. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1836. result.m[0] = initialM11;
  1837. result.m[1] = initialM12;
  1838. result.m[2] = initialM13;
  1839. result.m[3] = initialM14;
  1840. result.m[4] = initialM21;
  1841. result.m[5] = initialM22;
  1842. result.m[6] = initialM23;
  1843. result.m[7] = initialM24;
  1844. result.m[8] = initialM31;
  1845. result.m[9] = initialM32;
  1846. result.m[10] = initialM33;
  1847. result.m[11] = initialM34;
  1848. result.m[12] = initialM41;
  1849. result.m[13] = initialM42;
  1850. result.m[14] = initialM43;
  1851. result.m[15] = initialM44;
  1852. };
  1853. Matrix.prototype.getRow = function (index) {
  1854. if (index < 0 || index > 3) {
  1855. return null;
  1856. }
  1857. var i = index * 4;
  1858. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  1859. };
  1860. Matrix.prototype.setRow = function (index, row) {
  1861. if (index < 0 || index > 3) {
  1862. return this;
  1863. }
  1864. var i = index * 4;
  1865. this.m[i + 0] = row.x;
  1866. this.m[i + 1] = row.y;
  1867. this.m[i + 2] = row.z;
  1868. this.m[i + 3] = row.w;
  1869. return this;
  1870. };
  1871. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1872. var result = new Matrix();
  1873. result.m[0] = initialM11;
  1874. result.m[1] = initialM12;
  1875. result.m[2] = initialM13;
  1876. result.m[3] = initialM14;
  1877. result.m[4] = initialM21;
  1878. result.m[5] = initialM22;
  1879. result.m[6] = initialM23;
  1880. result.m[7] = initialM24;
  1881. result.m[8] = initialM31;
  1882. result.m[9] = initialM32;
  1883. result.m[10] = initialM33;
  1884. result.m[11] = initialM34;
  1885. result.m[12] = initialM41;
  1886. result.m[13] = initialM42;
  1887. result.m[14] = initialM43;
  1888. result.m[15] = initialM44;
  1889. return result;
  1890. };
  1891. Matrix.Compose = function (scale, rotation, translation) {
  1892. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1893. var rotationMatrix = Matrix.Identity();
  1894. rotation.toRotationMatrix(rotationMatrix);
  1895. result = result.multiply(rotationMatrix);
  1896. result.setTranslation(translation);
  1897. return result;
  1898. };
  1899. Matrix.Identity = function () {
  1900. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1901. };
  1902. Matrix.IdentityToRef = function (result) {
  1903. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1904. };
  1905. Matrix.Zero = function () {
  1906. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1907. };
  1908. Matrix.RotationX = function (angle) {
  1909. var result = new Matrix();
  1910. Matrix.RotationXToRef(angle, result);
  1911. return result;
  1912. };
  1913. Matrix.Invert = function (source) {
  1914. var result = new Matrix();
  1915. source.invertToRef(result);
  1916. return result;
  1917. };
  1918. Matrix.RotationXToRef = function (angle, result) {
  1919. var s = Math.sin(angle);
  1920. var c = Math.cos(angle);
  1921. result.m[0] = 1.0;
  1922. result.m[15] = 1.0;
  1923. result.m[5] = c;
  1924. result.m[10] = c;
  1925. result.m[9] = -s;
  1926. result.m[6] = s;
  1927. result.m[1] = 0;
  1928. result.m[2] = 0;
  1929. result.m[3] = 0;
  1930. result.m[4] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[11] = 0;
  1934. result.m[12] = 0;
  1935. result.m[13] = 0;
  1936. result.m[14] = 0;
  1937. };
  1938. Matrix.RotationY = function (angle) {
  1939. var result = new Matrix();
  1940. Matrix.RotationYToRef(angle, result);
  1941. return result;
  1942. };
  1943. Matrix.RotationYToRef = function (angle, result) {
  1944. var s = Math.sin(angle);
  1945. var c = Math.cos(angle);
  1946. result.m[5] = 1.0;
  1947. result.m[15] = 1.0;
  1948. result.m[0] = c;
  1949. result.m[2] = -s;
  1950. result.m[8] = s;
  1951. result.m[10] = c;
  1952. result.m[1] = 0;
  1953. result.m[3] = 0;
  1954. result.m[4] = 0;
  1955. result.m[6] = 0;
  1956. result.m[7] = 0;
  1957. result.m[9] = 0;
  1958. result.m[11] = 0;
  1959. result.m[12] = 0;
  1960. result.m[13] = 0;
  1961. result.m[14] = 0;
  1962. };
  1963. Matrix.RotationZ = function (angle) {
  1964. var result = new Matrix();
  1965. Matrix.RotationZToRef(angle, result);
  1966. return result;
  1967. };
  1968. Matrix.RotationZToRef = function (angle, result) {
  1969. var s = Math.sin(angle);
  1970. var c = Math.cos(angle);
  1971. result.m[10] = 1.0;
  1972. result.m[15] = 1.0;
  1973. result.m[0] = c;
  1974. result.m[1] = s;
  1975. result.m[4] = -s;
  1976. result.m[5] = c;
  1977. result.m[2] = 0;
  1978. result.m[3] = 0;
  1979. result.m[6] = 0;
  1980. result.m[7] = 0;
  1981. result.m[8] = 0;
  1982. result.m[9] = 0;
  1983. result.m[11] = 0;
  1984. result.m[12] = 0;
  1985. result.m[13] = 0;
  1986. result.m[14] = 0;
  1987. };
  1988. Matrix.RotationAxis = function (axis, angle) {
  1989. var result = Matrix.Zero();
  1990. Matrix.RotationAxisToRef(axis, angle, result);
  1991. return result;
  1992. };
  1993. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1994. var s = Math.sin(-angle);
  1995. var c = Math.cos(-angle);
  1996. var c1 = 1 - c;
  1997. axis.normalize();
  1998. result.m[0] = (axis.x * axis.x) * c1 + c;
  1999. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2000. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2001. result.m[3] = 0.0;
  2002. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2003. result.m[5] = (axis.y * axis.y) * c1 + c;
  2004. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2005. result.m[7] = 0.0;
  2006. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2007. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2008. result.m[10] = (axis.z * axis.z) * c1 + c;
  2009. result.m[11] = 0.0;
  2010. result.m[15] = 1.0;
  2011. };
  2012. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2013. var result = new Matrix();
  2014. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2015. return result;
  2016. };
  2017. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2018. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2019. this._tempQuaternion.toRotationMatrix(result);
  2020. };
  2021. Matrix.Scaling = function (x, y, z) {
  2022. var result = Matrix.Zero();
  2023. Matrix.ScalingToRef(x, y, z, result);
  2024. return result;
  2025. };
  2026. Matrix.ScalingToRef = function (x, y, z, result) {
  2027. result.m[0] = x;
  2028. result.m[1] = 0;
  2029. result.m[2] = 0;
  2030. result.m[3] = 0;
  2031. result.m[4] = 0;
  2032. result.m[5] = y;
  2033. result.m[6] = 0;
  2034. result.m[7] = 0;
  2035. result.m[8] = 0;
  2036. result.m[9] = 0;
  2037. result.m[10] = z;
  2038. result.m[11] = 0;
  2039. result.m[12] = 0;
  2040. result.m[13] = 0;
  2041. result.m[14] = 0;
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix.Translation = function (x, y, z) {
  2045. var result = Matrix.Identity();
  2046. Matrix.TranslationToRef(x, y, z, result);
  2047. return result;
  2048. };
  2049. Matrix.TranslationToRef = function (x, y, z, result) {
  2050. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2051. };
  2052. Matrix.Lerp = function (startValue, endValue, gradient) {
  2053. var result = Matrix.Zero();
  2054. for (var index = 0; index < 16; index++) {
  2055. result.m[index] = startValue.m[index] * gradient + endValue.m[index] * (1.0 - gradient);
  2056. }
  2057. return result;
  2058. };
  2059. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2060. var startScale = new Vector3(0, 0, 0);
  2061. var startRotation = new Quaternion();
  2062. var startTranslation = new Vector3(0, 0, 0);
  2063. startValue.decompose(startScale, startRotation, startTranslation);
  2064. var endScale = new Vector3(0, 0, 0);
  2065. var endRotation = new Quaternion();
  2066. var endTranslation = new Vector3(0, 0, 0);
  2067. endValue.decompose(endScale, endRotation, endTranslation);
  2068. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2069. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2070. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2071. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2072. };
  2073. Matrix.LookAtLH = function (eye, target, up) {
  2074. var result = Matrix.Zero();
  2075. Matrix.LookAtLHToRef(eye, target, up, result);
  2076. return result;
  2077. };
  2078. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2079. // Z axis
  2080. target.subtractToRef(eye, this._zAxis);
  2081. this._zAxis.normalize();
  2082. // X axis
  2083. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2084. if (this._xAxis.lengthSquared() === 0) {
  2085. this._xAxis.x = 1.0;
  2086. }
  2087. else {
  2088. this._xAxis.normalize();
  2089. }
  2090. // Y axis
  2091. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2092. this._yAxis.normalize();
  2093. // Eye angles
  2094. var ex = -Vector3.Dot(this._xAxis, eye);
  2095. var ey = -Vector3.Dot(this._yAxis, eye);
  2096. var ez = -Vector3.Dot(this._zAxis, eye);
  2097. 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);
  2098. };
  2099. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2100. var matrix = Matrix.Zero();
  2101. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2102. return matrix;
  2103. };
  2104. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2105. var hw = 2.0 / width;
  2106. var hh = 2.0 / height;
  2107. var id = 1.0 / (zfar - znear);
  2108. var nid = znear / (znear - zfar);
  2109. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2110. };
  2111. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2112. var matrix = Matrix.Zero();
  2113. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2114. return matrix;
  2115. };
  2116. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2117. result.m[0] = 2.0 / (right - left);
  2118. result.m[1] = result.m[2] = result.m[3] = 0;
  2119. result.m[5] = 2.0 / (top - bottom);
  2120. result.m[4] = result.m[6] = result.m[7] = 0;
  2121. result.m[10] = -1.0 / (znear - zfar);
  2122. result.m[8] = result.m[9] = result.m[11] = 0;
  2123. result.m[12] = (left + right) / (left - right);
  2124. result.m[13] = (top + bottom) / (bottom - top);
  2125. result.m[14] = znear / (znear - zfar);
  2126. result.m[15] = 1.0;
  2127. };
  2128. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2129. var matrix = Matrix.Zero();
  2130. matrix.m[0] = (2.0 * znear) / width;
  2131. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2132. matrix.m[5] = (2.0 * znear) / height;
  2133. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2134. matrix.m[10] = -zfar / (znear - zfar);
  2135. matrix.m[8] = matrix.m[9] = 0.0;
  2136. matrix.m[11] = 1.0;
  2137. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2138. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2139. return matrix;
  2140. };
  2141. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2142. var matrix = Matrix.Zero();
  2143. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2144. return matrix;
  2145. };
  2146. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2147. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2148. var tan = 1.0 / (Math.tan(fov * 0.5));
  2149. if (isVerticalFovFixed) {
  2150. result.m[0] = tan / aspect;
  2151. }
  2152. else {
  2153. result.m[0] = tan;
  2154. }
  2155. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2156. if (isVerticalFovFixed) {
  2157. result.m[5] = tan;
  2158. }
  2159. else {
  2160. result.m[5] = tan * aspect;
  2161. }
  2162. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2163. result.m[8] = result.m[9] = 0.0;
  2164. result.m[10] = -zfar / (znear - zfar);
  2165. result.m[11] = 1.0;
  2166. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2167. result.m[14] = (znear * zfar) / (znear - zfar);
  2168. };
  2169. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2170. var cw = viewport.width;
  2171. var ch = viewport.height;
  2172. var cx = viewport.x;
  2173. var cy = viewport.y;
  2174. 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);
  2175. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2176. };
  2177. Matrix.GetAsMatrix2x2 = function (matrix) {
  2178. return new Float32Array([
  2179. matrix.m[0], matrix.m[1],
  2180. matrix.m[4], matrix.m[5]
  2181. ]);
  2182. };
  2183. Matrix.GetAsMatrix3x3 = function (matrix) {
  2184. return new Float32Array([
  2185. matrix.m[0], matrix.m[1], matrix.m[2],
  2186. matrix.m[4], matrix.m[5], matrix.m[6],
  2187. matrix.m[8], matrix.m[9], matrix.m[10]
  2188. ]);
  2189. };
  2190. Matrix.Transpose = function (matrix) {
  2191. var result = new Matrix();
  2192. result.m[0] = matrix.m[0];
  2193. result.m[1] = matrix.m[4];
  2194. result.m[2] = matrix.m[8];
  2195. result.m[3] = matrix.m[12];
  2196. result.m[4] = matrix.m[1];
  2197. result.m[5] = matrix.m[5];
  2198. result.m[6] = matrix.m[9];
  2199. result.m[7] = matrix.m[13];
  2200. result.m[8] = matrix.m[2];
  2201. result.m[9] = matrix.m[6];
  2202. result.m[10] = matrix.m[10];
  2203. result.m[11] = matrix.m[14];
  2204. result.m[12] = matrix.m[3];
  2205. result.m[13] = matrix.m[7];
  2206. result.m[14] = matrix.m[11];
  2207. result.m[15] = matrix.m[15];
  2208. return result;
  2209. };
  2210. Matrix.Reflection = function (plane) {
  2211. var matrix = new Matrix();
  2212. Matrix.ReflectionToRef(plane, matrix);
  2213. return matrix;
  2214. };
  2215. Matrix.ReflectionToRef = function (plane, result) {
  2216. plane.normalize();
  2217. var x = plane.normal.x;
  2218. var y = plane.normal.y;
  2219. var z = plane.normal.z;
  2220. var temp = -2 * x;
  2221. var temp2 = -2 * y;
  2222. var temp3 = -2 * z;
  2223. result.m[0] = (temp * x) + 1;
  2224. result.m[1] = temp2 * x;
  2225. result.m[2] = temp3 * x;
  2226. result.m[3] = 0.0;
  2227. result.m[4] = temp * y;
  2228. result.m[5] = (temp2 * y) + 1;
  2229. result.m[6] = temp3 * y;
  2230. result.m[7] = 0.0;
  2231. result.m[8] = temp * z;
  2232. result.m[9] = temp2 * z;
  2233. result.m[10] = (temp3 * z) + 1;
  2234. result.m[11] = 0.0;
  2235. result.m[12] = temp * plane.d;
  2236. result.m[13] = temp2 * plane.d;
  2237. result.m[14] = temp3 * plane.d;
  2238. result.m[15] = 1.0;
  2239. };
  2240. Matrix._tempQuaternion = new Quaternion();
  2241. Matrix._xAxis = Vector3.Zero();
  2242. Matrix._yAxis = Vector3.Zero();
  2243. Matrix._zAxis = Vector3.Zero();
  2244. return Matrix;
  2245. })();
  2246. BABYLON.Matrix = Matrix;
  2247. var Plane = (function () {
  2248. function Plane(a, b, c, d) {
  2249. this.normal = new Vector3(a, b, c);
  2250. this.d = d;
  2251. }
  2252. Plane.prototype.asArray = function () {
  2253. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2254. };
  2255. // Methods
  2256. Plane.prototype.clone = function () {
  2257. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2258. };
  2259. Plane.prototype.normalize = function () {
  2260. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2261. var magnitude = 0;
  2262. if (norm !== 0) {
  2263. magnitude = 1.0 / norm;
  2264. }
  2265. this.normal.x *= magnitude;
  2266. this.normal.y *= magnitude;
  2267. this.normal.z *= magnitude;
  2268. this.d *= magnitude;
  2269. return this;
  2270. };
  2271. Plane.prototype.transform = function (transformation) {
  2272. var transposedMatrix = Matrix.Transpose(transformation);
  2273. var x = this.normal.x;
  2274. var y = this.normal.y;
  2275. var z = this.normal.z;
  2276. var d = this.d;
  2277. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2278. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2279. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2280. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2281. return new Plane(normalX, normalY, normalZ, finalD);
  2282. };
  2283. Plane.prototype.dotCoordinate = function (point) {
  2284. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2285. };
  2286. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2287. var x1 = point2.x - point1.x;
  2288. var y1 = point2.y - point1.y;
  2289. var z1 = point2.z - point1.z;
  2290. var x2 = point3.x - point1.x;
  2291. var y2 = point3.y - point1.y;
  2292. var z2 = point3.z - point1.z;
  2293. var yz = (y1 * z2) - (z1 * y2);
  2294. var xz = (z1 * x2) - (x1 * z2);
  2295. var xy = (x1 * y2) - (y1 * x2);
  2296. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2297. var invPyth;
  2298. if (pyth !== 0) {
  2299. invPyth = 1.0 / pyth;
  2300. }
  2301. else {
  2302. invPyth = 0;
  2303. }
  2304. this.normal.x = yz * invPyth;
  2305. this.normal.y = xz * invPyth;
  2306. this.normal.z = xy * invPyth;
  2307. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2308. return this;
  2309. };
  2310. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2311. var dot = Vector3.Dot(this.normal, direction);
  2312. return (dot <= epsilon);
  2313. };
  2314. Plane.prototype.signedDistanceTo = function (point) {
  2315. return Vector3.Dot(point, this.normal) + this.d;
  2316. };
  2317. // Statics
  2318. Plane.FromArray = function (array) {
  2319. return new Plane(array[0], array[1], array[2], array[3]);
  2320. };
  2321. Plane.FromPoints = function (point1, point2, point3) {
  2322. var result = new Plane(0, 0, 0, 0);
  2323. result.copyFromPoints(point1, point2, point3);
  2324. return result;
  2325. };
  2326. Plane.FromPositionAndNormal = function (origin, normal) {
  2327. var result = new Plane(0, 0, 0, 0);
  2328. normal.normalize();
  2329. result.normal = normal;
  2330. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2331. return result;
  2332. };
  2333. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2334. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2335. return Vector3.Dot(point, normal) + d;
  2336. };
  2337. return Plane;
  2338. })();
  2339. BABYLON.Plane = Plane;
  2340. var Viewport = (function () {
  2341. function Viewport(x, y, width, height) {
  2342. this.x = x;
  2343. this.y = y;
  2344. this.width = width;
  2345. this.height = height;
  2346. }
  2347. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2348. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2349. };
  2350. return Viewport;
  2351. })();
  2352. BABYLON.Viewport = Viewport;
  2353. var Frustum = (function () {
  2354. function Frustum() {
  2355. }
  2356. Frustum.GetPlanes = function (transform) {
  2357. var frustumPlanes = [];
  2358. for (var index = 0; index < 6; index++) {
  2359. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2360. }
  2361. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2362. return frustumPlanes;
  2363. };
  2364. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2365. // Near
  2366. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2367. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2368. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2369. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2370. frustumPlanes[0].normalize();
  2371. // Far
  2372. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2373. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2374. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2375. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2376. frustumPlanes[1].normalize();
  2377. // Left
  2378. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2379. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2380. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2381. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2382. frustumPlanes[2].normalize();
  2383. // Right
  2384. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2385. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2386. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2387. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2388. frustumPlanes[3].normalize();
  2389. // Top
  2390. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2391. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2392. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2393. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2394. frustumPlanes[4].normalize();
  2395. // Bottom
  2396. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2397. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2398. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2399. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2400. frustumPlanes[5].normalize();
  2401. };
  2402. return Frustum;
  2403. })();
  2404. BABYLON.Frustum = Frustum;
  2405. (function (Space) {
  2406. Space[Space["LOCAL"] = 0] = "LOCAL";
  2407. Space[Space["WORLD"] = 1] = "WORLD";
  2408. })(BABYLON.Space || (BABYLON.Space = {}));
  2409. var Space = BABYLON.Space;
  2410. var Axis = (function () {
  2411. function Axis() {
  2412. }
  2413. Axis.X = new Vector3(1, 0, 0);
  2414. Axis.Y = new Vector3(0, 1, 0);
  2415. Axis.Z = new Vector3(0, 0, 1);
  2416. return Axis;
  2417. })();
  2418. BABYLON.Axis = Axis;
  2419. ;
  2420. var BezierCurve = (function () {
  2421. function BezierCurve() {
  2422. }
  2423. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2424. // Extract X (which is equal to time here)
  2425. var f0 = 1 - 3 * x2 + 3 * x1;
  2426. var f1 = 3 * x2 - 6 * x1;
  2427. var f2 = 3 * x1;
  2428. var refinedT = t;
  2429. for (var i = 0; i < 5; i++) {
  2430. var refinedT2 = refinedT * refinedT;
  2431. var refinedT3 = refinedT2 * refinedT;
  2432. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2433. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2434. refinedT -= (x - t) * slope;
  2435. refinedT = Math.min(1, Math.max(0, refinedT));
  2436. }
  2437. // Resolve cubic bezier for the given x
  2438. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2439. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2440. Math.pow(refinedT, 3);
  2441. };
  2442. return BezierCurve;
  2443. })();
  2444. BABYLON.BezierCurve = BezierCurve;
  2445. (function (Orientation) {
  2446. Orientation[Orientation["CW"] = 0] = "CW";
  2447. Orientation[Orientation["CCW"] = 1] = "CCW";
  2448. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2449. var Orientation = BABYLON.Orientation;
  2450. var Angle = (function () {
  2451. function Angle(radians) {
  2452. var _this = this;
  2453. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2454. this.radians = function () { return _this._radians; };
  2455. this._radians = radians;
  2456. if (this._radians < 0)
  2457. this._radians += (2 * Math.PI);
  2458. }
  2459. Angle.BetweenTwoPoints = function (a, b) {
  2460. var delta = b.subtract(a);
  2461. var theta = Math.atan2(delta.y, delta.x);
  2462. return new Angle(theta);
  2463. };
  2464. Angle.FromRadians = function (radians) {
  2465. return new Angle(radians);
  2466. };
  2467. Angle.FromDegrees = function (degrees) {
  2468. return new Angle(degrees * Math.PI / 180);
  2469. };
  2470. return Angle;
  2471. })();
  2472. BABYLON.Angle = Angle;
  2473. var Arc2 = (function () {
  2474. function Arc2(startPoint, midPoint, endPoint) {
  2475. this.startPoint = startPoint;
  2476. this.midPoint = midPoint;
  2477. this.endPoint = endPoint;
  2478. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2479. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2480. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2481. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2482. 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);
  2483. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2484. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2485. var a1 = this.startAngle.degrees();
  2486. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2487. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2488. // angles correction
  2489. if (a2 - a1 > +180.0)
  2490. a2 -= 360.0;
  2491. if (a2 - a1 < -180.0)
  2492. a2 += 360.0;
  2493. if (a3 - a2 > +180.0)
  2494. a3 -= 360.0;
  2495. if (a3 - a2 < -180.0)
  2496. a3 += 360.0;
  2497. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2498. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2499. }
  2500. return Arc2;
  2501. })();
  2502. BABYLON.Arc2 = Arc2;
  2503. var Path2 = (function () {
  2504. function Path2(x, y) {
  2505. this._points = new Array();
  2506. this._length = 0;
  2507. this.closed = false;
  2508. this._points.push(new Vector2(x, y));
  2509. }
  2510. Path2.prototype.addLineTo = function (x, y) {
  2511. if (closed) {
  2512. //Tools.Error("cannot add lines to closed paths");
  2513. return this;
  2514. }
  2515. var newPoint = new Vector2(x, y);
  2516. var previousPoint = this._points[this._points.length - 1];
  2517. this._points.push(newPoint);
  2518. this._length += newPoint.subtract(previousPoint).length();
  2519. return this;
  2520. };
  2521. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2522. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2523. if (closed) {
  2524. //Tools.Error("cannot add arcs to closed paths");
  2525. return this;
  2526. }
  2527. var startPoint = this._points[this._points.length - 1];
  2528. var midPoint = new Vector2(midX, midY);
  2529. var endPoint = new Vector2(endX, endY);
  2530. var arc = new Arc2(startPoint, midPoint, endPoint);
  2531. var increment = arc.angle.radians() / numberOfSegments;
  2532. if (arc.orientation === Orientation.CW)
  2533. increment *= -1;
  2534. var currentAngle = arc.startAngle.radians() + increment;
  2535. for (var i = 0; i < numberOfSegments; i++) {
  2536. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2537. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2538. this.addLineTo(x, y);
  2539. currentAngle += increment;
  2540. }
  2541. return this;
  2542. };
  2543. Path2.prototype.close = function () {
  2544. this.closed = true;
  2545. return this;
  2546. };
  2547. Path2.prototype.length = function () {
  2548. var result = this._length;
  2549. if (!this.closed) {
  2550. var lastPoint = this._points[this._points.length - 1];
  2551. var firstPoint = this._points[0];
  2552. result += (firstPoint.subtract(lastPoint).length());
  2553. }
  2554. return result;
  2555. };
  2556. Path2.prototype.getPoints = function () {
  2557. return this._points;
  2558. };
  2559. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2560. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2561. //Tools.Error("normalized length position should be between 0 and 1.");
  2562. return Vector2.Zero();
  2563. }
  2564. var lengthPosition = normalizedLengthPosition * this.length();
  2565. var previousOffset = 0;
  2566. for (var i = 0; i < this._points.length; i++) {
  2567. var j = (i + 1) % this._points.length;
  2568. var a = this._points[i];
  2569. var b = this._points[j];
  2570. var bToA = b.subtract(a);
  2571. var nextOffset = (bToA.length() + previousOffset);
  2572. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2573. var dir = bToA.normalize();
  2574. var localOffset = lengthPosition - previousOffset;
  2575. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2576. }
  2577. previousOffset = nextOffset;
  2578. }
  2579. //Tools.Error("internal error");
  2580. return Vector2.Zero();
  2581. };
  2582. Path2.StartingAt = function (x, y) {
  2583. return new Path2(x, y);
  2584. };
  2585. return Path2;
  2586. })();
  2587. BABYLON.Path2 = Path2;
  2588. var Path3D = (function () {
  2589. /**
  2590. * new Path3D(path, normal, raw)
  2591. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2592. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2593. * path : an array of Vector3, the curve axis of the Path3D
  2594. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2595. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2596. */
  2597. function Path3D(path, firstNormal, raw) {
  2598. this.path = path;
  2599. this._curve = new Array();
  2600. this._distances = new Array();
  2601. this._tangents = new Array();
  2602. this._normals = new Array();
  2603. this._binormals = new Array();
  2604. for (var p = 0; p < path.length; p++) {
  2605. this._curve[p] = path[p].clone(); // hard copy
  2606. }
  2607. this._raw = raw || false;
  2608. this._compute(firstNormal);
  2609. }
  2610. /**
  2611. * Returns the Path3D array of successive Vector3 designing its curve.
  2612. */
  2613. Path3D.prototype.getCurve = function () {
  2614. return this._curve;
  2615. };
  2616. /**
  2617. * Returns an array populated with tangent vectors on each Path3D curve point.
  2618. */
  2619. Path3D.prototype.getTangents = function () {
  2620. return this._tangents;
  2621. };
  2622. /**
  2623. * Returns an array populated with normal vectors on each Path3D curve point.
  2624. */
  2625. Path3D.prototype.getNormals = function () {
  2626. return this._normals;
  2627. };
  2628. /**
  2629. * Returns an array populated with binormal vectors on each Path3D curve point.
  2630. */
  2631. Path3D.prototype.getBinormals = function () {
  2632. return this._binormals;
  2633. };
  2634. /**
  2635. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2636. */
  2637. Path3D.prototype.getDistances = function () {
  2638. return this._distances;
  2639. };
  2640. /**
  2641. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2642. * Returns the same object updated.
  2643. */
  2644. Path3D.prototype.update = function (path, firstNormal) {
  2645. for (var p = 0; p < path.length; p++) {
  2646. this._curve[p].x = path[p].x;
  2647. this._curve[p].y = path[p].y;
  2648. this._curve[p].z = path[p].z;
  2649. }
  2650. this._compute(firstNormal);
  2651. return this;
  2652. };
  2653. // private function compute() : computes tangents, normals and binormals
  2654. Path3D.prototype._compute = function (firstNormal) {
  2655. var l = this._curve.length;
  2656. // first and last tangents
  2657. this._tangents[0] = this._getFirstNonNullVector(0);
  2658. if (!this._raw) {
  2659. this._tangents[0].normalize();
  2660. }
  2661. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2662. if (!this._raw) {
  2663. this._tangents[l - 1].normalize();
  2664. }
  2665. // normals and binormals at first point : arbitrary vector with _normalVector()
  2666. var tg0 = this._tangents[0];
  2667. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2668. this._normals[0] = pp0;
  2669. if (!this._raw) {
  2670. this._normals[0].normalize();
  2671. }
  2672. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2673. if (!this._raw) {
  2674. this._binormals[0].normalize();
  2675. }
  2676. this._distances[0] = 0;
  2677. // normals and binormals : next points
  2678. var prev; // previous vector (segment)
  2679. var cur; // current vector (segment)
  2680. var curTang; // current tangent
  2681. // previous normal
  2682. var prevBinor; // previous binormal
  2683. for (var i = 1; i < l; i++) {
  2684. // tangents
  2685. prev = this._getLastNonNullVector(i);
  2686. if (i < l - 1) {
  2687. cur = this._getFirstNonNullVector(i);
  2688. this._tangents[i] = prev.add(cur);
  2689. this._tangents[i].normalize();
  2690. }
  2691. this._distances[i] = this._distances[i - 1] + prev.length();
  2692. // normals and binormals
  2693. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2694. curTang = this._tangents[i];
  2695. prevBinor = this._binormals[i - 1];
  2696. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2697. if (!this._raw) {
  2698. this._normals[i].normalize();
  2699. }
  2700. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2701. if (!this._raw) {
  2702. this._binormals[i].normalize();
  2703. }
  2704. }
  2705. };
  2706. // private function getFirstNonNullVector(index)
  2707. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2708. Path3D.prototype._getFirstNonNullVector = function (index) {
  2709. var i = 1;
  2710. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2711. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2712. i++;
  2713. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2714. }
  2715. return nNVector;
  2716. };
  2717. // private function getLastNonNullVector(index)
  2718. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2719. Path3D.prototype._getLastNonNullVector = function (index) {
  2720. var i = 1;
  2721. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2722. while (nLVector.length() === 0 && index > i + 1) {
  2723. i++;
  2724. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2725. }
  2726. return nLVector;
  2727. };
  2728. // private function normalVector(v0, vt, va) :
  2729. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2730. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2731. Path3D.prototype._normalVector = function (v0, vt, va) {
  2732. var normal0;
  2733. if (va === undefined || va === null) {
  2734. var point;
  2735. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2736. point = new Vector3(0, -1, 0);
  2737. }
  2738. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2739. point = new Vector3(1, 0, 0);
  2740. }
  2741. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2742. point = new Vector3(0, 0, 1);
  2743. }
  2744. normal0 = Vector3.Cross(vt, point);
  2745. }
  2746. else {
  2747. normal0 = Vector3.Cross(vt, va);
  2748. Vector3.CrossToRef(normal0, vt, normal0);
  2749. }
  2750. normal0.normalize();
  2751. return normal0;
  2752. };
  2753. return Path3D;
  2754. })();
  2755. BABYLON.Path3D = Path3D;
  2756. var Curve3 = (function () {
  2757. /**
  2758. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2759. * A Curve3 is designed from a series of successive Vector3.
  2760. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2761. */
  2762. function Curve3(points) {
  2763. this._length = 0;
  2764. this._points = points;
  2765. this._length = this._computeLength(points);
  2766. }
  2767. /**
  2768. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2769. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2770. * @param v1 (Vector3) the control point
  2771. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2772. * @param nbPoints (integer) the wanted number of points in the curve
  2773. */
  2774. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2775. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2776. var bez = new Array();
  2777. var equation = function (t, val0, val1, val2) {
  2778. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2779. return res;
  2780. };
  2781. for (var i = 0; i <= nbPoints; i++) {
  2782. 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)));
  2783. }
  2784. return new Curve3(bez);
  2785. };
  2786. /**
  2787. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2788. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2789. * @param v1 (Vector3) the first control point
  2790. * @param v2 (Vector3) the second control point
  2791. * @param v3 (Vector3) the end point of the Cubic Bezier
  2792. * @param nbPoints (integer) the wanted number of points in the curve
  2793. */
  2794. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2795. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2796. var bez = new Array();
  2797. var equation = function (t, val0, val1, val2, val3) {
  2798. 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;
  2799. return res;
  2800. };
  2801. for (var i = 0; i <= nbPoints; i++) {
  2802. 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)));
  2803. }
  2804. return new Curve3(bez);
  2805. };
  2806. /**
  2807. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2808. * @param p1 (Vector3) the origin point of the Hermite Spline
  2809. * @param t1 (Vector3) the tangent vector at the origin point
  2810. * @param p2 (Vector3) the end point of the Hermite Spline
  2811. * @param t2 (Vector3) the tangent vector at the end point
  2812. * @param nbPoints (integer) the wanted number of points in the curve
  2813. */
  2814. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2815. var hermite = new Array();
  2816. var step = 1 / nbPoints;
  2817. for (var i = 0; i <= nbPoints; i++) {
  2818. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2819. }
  2820. return new Curve3(hermite);
  2821. };
  2822. /**
  2823. * Returns the Curve3 stored array of successive Vector3
  2824. */
  2825. Curve3.prototype.getPoints = function () {
  2826. return this._points;
  2827. };
  2828. /**
  2829. * Returns the computed length (float) of the curve.
  2830. */
  2831. Curve3.prototype.length = function () {
  2832. return this._length;
  2833. };
  2834. /**
  2835. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2836. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2837. * curveA and curveB keep unchanged.
  2838. */
  2839. Curve3.prototype.continue = function (curve) {
  2840. var lastPoint = this._points[this._points.length - 1];
  2841. var continuedPoints = this._points.slice();
  2842. var curvePoints = curve.getPoints();
  2843. for (var i = 1; i < curvePoints.length; i++) {
  2844. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2845. }
  2846. var continuedCurve = new Curve3(continuedPoints);
  2847. return continuedCurve;
  2848. };
  2849. Curve3.prototype._computeLength = function (path) {
  2850. var l = 0;
  2851. for (var i = 1; i < path.length; i++) {
  2852. l += (path[i].subtract(path[i - 1])).length();
  2853. }
  2854. return l;
  2855. };
  2856. return Curve3;
  2857. })();
  2858. BABYLON.Curve3 = Curve3;
  2859. // SphericalHarmonics
  2860. var SphericalHarmonics = (function () {
  2861. function SphericalHarmonics() {
  2862. this.L00 = Vector3.Zero();
  2863. this.L1_1 = Vector3.Zero();
  2864. this.L10 = Vector3.Zero();
  2865. this.L11 = Vector3.Zero();
  2866. this.L2_2 = Vector3.Zero();
  2867. this.L2_1 = Vector3.Zero();
  2868. this.L20 = Vector3.Zero();
  2869. this.L21 = Vector3.Zero();
  2870. this.L22 = Vector3.Zero();
  2871. }
  2872. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2873. var colorVector = new Vector3(color.r, color.g, color.b);
  2874. var c = colorVector.scale(deltaSolidAngle);
  2875. this.L00 = this.L00.add(c.scale(0.282095));
  2876. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2877. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2878. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2879. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2880. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2881. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2882. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2883. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2884. };
  2885. SphericalHarmonics.prototype.scale = function (scale) {
  2886. this.L00 = this.L00.scale(scale);
  2887. this.L1_1 = this.L1_1.scale(scale);
  2888. this.L10 = this.L10.scale(scale);
  2889. this.L11 = this.L11.scale(scale);
  2890. this.L2_2 = this.L2_2.scale(scale);
  2891. this.L2_1 = this.L2_1.scale(scale);
  2892. this.L20 = this.L20.scale(scale);
  2893. this.L21 = this.L21.scale(scale);
  2894. this.L22 = this.L22.scale(scale);
  2895. };
  2896. return SphericalHarmonics;
  2897. })();
  2898. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2899. // SphericalPolynomial
  2900. var SphericalPolynomial = (function () {
  2901. function SphericalPolynomial() {
  2902. this.x = Vector3.Zero();
  2903. this.y = Vector3.Zero();
  2904. this.z = Vector3.Zero();
  2905. this.xx = Vector3.Zero();
  2906. this.yy = Vector3.Zero();
  2907. this.zz = Vector3.Zero();
  2908. this.xy = Vector3.Zero();
  2909. this.yz = Vector3.Zero();
  2910. this.zx = Vector3.Zero();
  2911. }
  2912. SphericalPolynomial.prototype.addAmbient = function (color) {
  2913. var colorVector = new Vector3(color.r, color.g, color.b);
  2914. this.xx = this.xx.add(colorVector);
  2915. this.yy = this.yy.add(colorVector);
  2916. this.zz = this.zz.add(colorVector);
  2917. };
  2918. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2919. var result = new SphericalPolynomial();
  2920. result.x = harmonics.L11.scale(1.02333);
  2921. result.y = harmonics.L1_1.scale(1.02333);
  2922. result.z = harmonics.L10.scale(1.02333);
  2923. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2924. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2925. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2926. result.yz = harmonics.L2_1.scale(0.858086);
  2927. result.zx = harmonics.L21.scale(0.858086);
  2928. result.xy = harmonics.L2_2.scale(0.858086);
  2929. return result;
  2930. };
  2931. return SphericalPolynomial;
  2932. })();
  2933. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2934. // Vertex formats
  2935. var PositionNormalVertex = (function () {
  2936. function PositionNormalVertex(position, normal) {
  2937. if (position === void 0) { position = Vector3.Zero(); }
  2938. if (normal === void 0) { normal = Vector3.Up(); }
  2939. this.position = position;
  2940. this.normal = normal;
  2941. }
  2942. PositionNormalVertex.prototype.clone = function () {
  2943. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2944. };
  2945. return PositionNormalVertex;
  2946. })();
  2947. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2948. var PositionNormalTextureVertex = (function () {
  2949. function PositionNormalTextureVertex(position, normal, uv) {
  2950. if (position === void 0) { position = Vector3.Zero(); }
  2951. if (normal === void 0) { normal = Vector3.Up(); }
  2952. if (uv === void 0) { uv = Vector2.Zero(); }
  2953. this.position = position;
  2954. this.normal = normal;
  2955. this.uv = uv;
  2956. }
  2957. PositionNormalTextureVertex.prototype.clone = function () {
  2958. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2959. };
  2960. return PositionNormalTextureVertex;
  2961. })();
  2962. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2963. // Temporary pre-allocated objects for engine internal use
  2964. // usage in any internal function :
  2965. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2966. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2967. var Tmp = (function () {
  2968. function Tmp() {
  2969. }
  2970. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2971. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2972. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2973. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2974. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2975. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2976. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2977. Matrix.Zero(), Matrix.Zero(),
  2978. Matrix.Zero(), Matrix.Zero(),
  2979. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2980. return Tmp;
  2981. })();
  2982. BABYLON.Tmp = Tmp;
  2983. })(BABYLON || (BABYLON = {}));
  2984. var BABYLON;
  2985. (function (BABYLON) {
  2986. function generateSerializableMember(type, sourceName) {
  2987. return function (target, propertyKey) {
  2988. if (!target.__serializableMembers) {
  2989. target.__serializableMembers = {};
  2990. }
  2991. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2992. };
  2993. }
  2994. function serialize(sourceName) {
  2995. return generateSerializableMember(0, sourceName); // value member
  2996. }
  2997. BABYLON.serialize = serialize;
  2998. function serializeAsTexture(sourceName) {
  2999. return generateSerializableMember(1, sourceName); // texture member
  3000. }
  3001. BABYLON.serializeAsTexture = serializeAsTexture;
  3002. function serializeAsColor3(sourceName) {
  3003. return generateSerializableMember(2, sourceName); // color3 member
  3004. }
  3005. BABYLON.serializeAsColor3 = serializeAsColor3;
  3006. function serializeAsFresnelParameters(sourceName) {
  3007. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3008. }
  3009. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3010. function serializeAsVector2(sourceName) {
  3011. return generateSerializableMember(4, sourceName); // vector2 member
  3012. }
  3013. BABYLON.serializeAsVector2 = serializeAsVector2;
  3014. function serializeAsVector3(sourceName) {
  3015. return generateSerializableMember(5, sourceName); // vector3 member
  3016. }
  3017. BABYLON.serializeAsVector3 = serializeAsVector3;
  3018. function serializeAsMeshReference(sourceName) {
  3019. return generateSerializableMember(6, sourceName); // mesh reference member
  3020. }
  3021. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3022. var SerializationHelper = (function () {
  3023. function SerializationHelper() {
  3024. }
  3025. SerializationHelper.Serialize = function (entity, serializationObject) {
  3026. if (!serializationObject) {
  3027. serializationObject = {};
  3028. }
  3029. // Tags
  3030. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3031. // Properties
  3032. for (var property in entity.__serializableMembers) {
  3033. var propertyDescriptor = entity.__serializableMembers[property];
  3034. var targetPropertyName = propertyDescriptor.sourceName || property;
  3035. var propertyType = propertyDescriptor.type;
  3036. var sourceProperty = entity[property];
  3037. if (sourceProperty !== undefined && sourceProperty !== null) {
  3038. switch (propertyType) {
  3039. case 0:
  3040. serializationObject[targetPropertyName] = sourceProperty;
  3041. break;
  3042. case 1:
  3043. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3044. break;
  3045. case 2:
  3046. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3047. break;
  3048. case 3:
  3049. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3050. break;
  3051. case 4:
  3052. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3053. break;
  3054. case 5:
  3055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3056. break;
  3057. case 6:
  3058. serializationObject[targetPropertyName] = sourceProperty.id;
  3059. break;
  3060. }
  3061. }
  3062. }
  3063. return serializationObject;
  3064. };
  3065. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3066. var destination = creationFunction();
  3067. // Tags
  3068. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3069. // Properties
  3070. for (var property in destination.__serializableMembers) {
  3071. var propertyDescriptor = destination.__serializableMembers[property];
  3072. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3073. var propertyType = propertyDescriptor.type;
  3074. if (sourceProperty !== undefined && sourceProperty !== null) {
  3075. switch (propertyType) {
  3076. case 0:
  3077. destination[property] = sourceProperty;
  3078. break;
  3079. case 1:
  3080. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3081. break;
  3082. case 2:
  3083. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3084. break;
  3085. case 3:
  3086. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3087. break;
  3088. case 4:
  3089. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3090. break;
  3091. case 5:
  3092. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3093. break;
  3094. case 6:
  3095. destination[property] = scene.getLastMeshByID(sourceProperty);
  3096. break;
  3097. }
  3098. }
  3099. }
  3100. return destination;
  3101. };
  3102. SerializationHelper.Clone = function (creationFunction, source) {
  3103. var destination = creationFunction();
  3104. // Tags
  3105. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3106. // Properties
  3107. for (var property in destination.__serializableMembers) {
  3108. var propertyDescriptor = destination.__serializableMembers[property];
  3109. var sourceProperty = source[property];
  3110. var propertyType = propertyDescriptor.type;
  3111. if (sourceProperty !== undefined && sourceProperty !== null) {
  3112. switch (propertyType) {
  3113. case 0: // Value
  3114. case 6:
  3115. destination[property] = sourceProperty;
  3116. break;
  3117. case 1: // Texture
  3118. case 2: // Color3
  3119. case 3: // FresnelParameters
  3120. case 4: // Vector2
  3121. case 5:
  3122. destination[property] = sourceProperty.clone();
  3123. break;
  3124. }
  3125. }
  3126. }
  3127. return destination;
  3128. };
  3129. return SerializationHelper;
  3130. })();
  3131. BABYLON.SerializationHelper = SerializationHelper;
  3132. })(BABYLON || (BABYLON = {}));
  3133. var BABYLON;
  3134. (function (BABYLON) {
  3135. /**
  3136. * A class serves as a medium between the observable and its observers
  3137. */
  3138. var EventState = (function () {
  3139. /**
  3140. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3141. */
  3142. function EventState(skipNextObservers) {
  3143. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3144. this.skipNextObservers = skipNextObservers;
  3145. }
  3146. return EventState;
  3147. })();
  3148. BABYLON.EventState = EventState;
  3149. var Observer = (function () {
  3150. function Observer(callback, mask) {
  3151. this.callback = callback;
  3152. this.mask = mask;
  3153. }
  3154. return Observer;
  3155. })();
  3156. BABYLON.Observer = Observer;
  3157. var Observable = (function () {
  3158. function Observable() {
  3159. this._observers = new Array();
  3160. }
  3161. /**
  3162. * Create a new Observer with the specified callback
  3163. * @param callback the callback that will be executed for that Observer
  3164. * @param mash the mask used to filter observers
  3165. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3166. */
  3167. Observable.prototype.add = function (callback, mask, insertFirst) {
  3168. if (mask === void 0) { mask = -1; }
  3169. if (insertFirst === void 0) { insertFirst = false; }
  3170. if (!callback) {
  3171. return null;
  3172. }
  3173. var observer = new Observer(callback, mask);
  3174. if (insertFirst) {
  3175. this._observers.unshift(observer);
  3176. }
  3177. else {
  3178. this._observers.push(observer);
  3179. }
  3180. return observer;
  3181. };
  3182. /**
  3183. * Remove an Observer from the Observable object
  3184. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3185. */
  3186. Observable.prototype.remove = function (observer) {
  3187. var index = this._observers.indexOf(observer);
  3188. if (index !== -1) {
  3189. this._observers.splice(index, 1);
  3190. return true;
  3191. }
  3192. return false;
  3193. };
  3194. /**
  3195. * Remove a callback from the Observable object
  3196. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3197. */
  3198. Observable.prototype.removeCallback = function (callback) {
  3199. for (var index = 0; index < this._observers.length; index++) {
  3200. if (this._observers[index].callback === callback) {
  3201. this._observers.splice(index, 1);
  3202. return true;
  3203. }
  3204. }
  3205. return false;
  3206. };
  3207. /**
  3208. * Notify all Observers by calling their respective callback with the given data
  3209. * @param eventData
  3210. * @param mask
  3211. */
  3212. Observable.prototype.notifyObservers = function (eventData, mask) {
  3213. if (mask === void 0) { mask = -1; }
  3214. var state = new EventState();
  3215. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3216. var obs = _a[_i];
  3217. if (obs.mask & mask) {
  3218. obs.callback(eventData, state);
  3219. }
  3220. if (state.skipNextObservers) {
  3221. break;
  3222. }
  3223. }
  3224. };
  3225. /**
  3226. * return true is the Observable has at least one Observer registered
  3227. */
  3228. Observable.prototype.hasObservers = function () {
  3229. return this._observers.length > 0;
  3230. };
  3231. /**
  3232. * Clear the list of observers
  3233. */
  3234. Observable.prototype.clear = function () {
  3235. this._observers = new Array();
  3236. };
  3237. /**
  3238. * Clone the current observable
  3239. */
  3240. Observable.prototype.clone = function () {
  3241. var result = new Observable();
  3242. result._observers = this._observers.slice(0);
  3243. return result;
  3244. };
  3245. return Observable;
  3246. })();
  3247. BABYLON.Observable = Observable;
  3248. })(BABYLON || (BABYLON = {}));
  3249. var BABYLON;
  3250. (function (BABYLON) {
  3251. var Database = (function () {
  3252. function Database(urlToScene, callbackManifestChecked) {
  3253. // Handling various flavors of prefixed version of IndexedDB
  3254. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3255. this.callbackManifestChecked = callbackManifestChecked;
  3256. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3257. this.db = null;
  3258. this.enableSceneOffline = false;
  3259. this.enableTexturesOffline = false;
  3260. this.manifestVersionFound = 0;
  3261. this.mustUpdateRessources = false;
  3262. this.hasReachedQuota = false;
  3263. if (!Database.IDBStorageEnabled) {
  3264. this.callbackManifestChecked(true);
  3265. }
  3266. else {
  3267. this.checkManifestFile();
  3268. }
  3269. }
  3270. Database.prototype.checkManifestFile = function () {
  3271. var _this = this;
  3272. function noManifestFile() {
  3273. that.enableSceneOffline = false;
  3274. that.enableTexturesOffline = false;
  3275. that.callbackManifestChecked(false);
  3276. }
  3277. var that = this;
  3278. var timeStampUsed = false;
  3279. var manifestURL = this.currentSceneUrl + ".manifest";
  3280. var xhr = new XMLHttpRequest();
  3281. if (navigator.onLine) {
  3282. // Adding a timestamp to by-pass browsers' cache
  3283. timeStampUsed = true;
  3284. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3285. }
  3286. xhr.open("GET", manifestURL, true);
  3287. xhr.addEventListener("load", function () {
  3288. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3289. try {
  3290. var manifestFile = JSON.parse(xhr.response);
  3291. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3292. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3293. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3294. _this.manifestVersionFound = manifestFile.version;
  3295. }
  3296. if (_this.callbackManifestChecked) {
  3297. _this.callbackManifestChecked(true);
  3298. }
  3299. }
  3300. catch (ex) {
  3301. noManifestFile();
  3302. }
  3303. }
  3304. else {
  3305. noManifestFile();
  3306. }
  3307. }, false);
  3308. xhr.addEventListener("error", function (event) {
  3309. if (timeStampUsed) {
  3310. timeStampUsed = false;
  3311. // Let's retry without the timeStamp
  3312. // It could fail when coupled with HTML5 Offline API
  3313. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3314. xhr.open("GET", retryManifestURL, true);
  3315. xhr.send();
  3316. }
  3317. else {
  3318. noManifestFile();
  3319. }
  3320. }, false);
  3321. try {
  3322. xhr.send();
  3323. }
  3324. catch (ex) {
  3325. BABYLON.Tools.Error("Error on XHR send request.");
  3326. that.callbackManifestChecked(false);
  3327. }
  3328. };
  3329. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3330. var _this = this;
  3331. function handleError() {
  3332. that.isSupported = false;
  3333. if (errorCallback)
  3334. errorCallback();
  3335. }
  3336. var that = this;
  3337. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3338. // Your browser doesn't support IndexedDB
  3339. this.isSupported = false;
  3340. if (errorCallback)
  3341. errorCallback();
  3342. }
  3343. else {
  3344. // If the DB hasn't been opened or created yet
  3345. if (!this.db) {
  3346. this.hasReachedQuota = false;
  3347. this.isSupported = true;
  3348. var request = this.idbFactory.open("babylonjs", 1);
  3349. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3350. request.onerror = function (event) {
  3351. handleError();
  3352. };
  3353. // executes when a version change transaction cannot complete due to other active transactions
  3354. request.onblocked = function (event) {
  3355. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3356. handleError();
  3357. };
  3358. // DB has been opened successfully
  3359. request.onsuccess = function (event) {
  3360. _this.db = request.result;
  3361. successCallback();
  3362. };
  3363. // Initialization of the DB. Creating Scenes & Textures stores
  3364. request.onupgradeneeded = function (event) {
  3365. _this.db = (event.target).result;
  3366. try {
  3367. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3368. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3369. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3370. }
  3371. catch (ex) {
  3372. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3373. handleError();
  3374. }
  3375. };
  3376. }
  3377. else {
  3378. if (successCallback)
  3379. successCallback();
  3380. }
  3381. }
  3382. };
  3383. Database.prototype.loadImageFromDB = function (url, image) {
  3384. var _this = this;
  3385. var completeURL = Database.ReturnFullUrlLocation(url);
  3386. var saveAndLoadImage = function () {
  3387. if (!_this.hasReachedQuota && _this.db !== null) {
  3388. // the texture is not yet in the DB, let's try to save it
  3389. _this._saveImageIntoDBAsync(completeURL, image);
  3390. }
  3391. else {
  3392. image.src = url;
  3393. }
  3394. };
  3395. if (!this.mustUpdateRessources) {
  3396. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3397. }
  3398. else {
  3399. saveAndLoadImage();
  3400. }
  3401. };
  3402. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3403. if (this.isSupported && this.db !== null) {
  3404. var texture;
  3405. var transaction = this.db.transaction(["textures"]);
  3406. transaction.onabort = function (event) {
  3407. image.src = url;
  3408. };
  3409. transaction.oncomplete = function (event) {
  3410. var blobTextureURL;
  3411. if (texture) {
  3412. var URL = window.URL || window.webkitURL;
  3413. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3414. image.onerror = function () {
  3415. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3416. image.src = url;
  3417. };
  3418. image.src = blobTextureURL;
  3419. }
  3420. else {
  3421. notInDBCallback();
  3422. }
  3423. };
  3424. var getRequest = transaction.objectStore("textures").get(url);
  3425. getRequest.onsuccess = function (event) {
  3426. texture = (event.target).result;
  3427. };
  3428. getRequest.onerror = function (event) {
  3429. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3430. image.src = url;
  3431. };
  3432. }
  3433. else {
  3434. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3435. image.src = url;
  3436. }
  3437. };
  3438. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3439. var _this = this;
  3440. if (this.isSupported) {
  3441. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3442. var generateBlobUrl = function () {
  3443. var blobTextureURL;
  3444. if (blob) {
  3445. var URL = window.URL || window.webkitURL;
  3446. try {
  3447. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3448. }
  3449. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3450. catch (ex) {
  3451. blobTextureURL = URL.createObjectURL(blob);
  3452. }
  3453. }
  3454. image.src = blobTextureURL;
  3455. };
  3456. if (Database.IsUASupportingBlobStorage) {
  3457. var xhr = new XMLHttpRequest(), blob;
  3458. xhr.open("GET", url, true);
  3459. xhr.responseType = "blob";
  3460. xhr.addEventListener("load", function () {
  3461. if (xhr.status === 200) {
  3462. // Blob as response (XHR2)
  3463. blob = xhr.response;
  3464. var transaction = _this.db.transaction(["textures"], "readwrite");
  3465. // the transaction could abort because of a QuotaExceededError error
  3466. transaction.onabort = function (event) {
  3467. try {
  3468. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3469. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3470. this.hasReachedQuota = true;
  3471. }
  3472. }
  3473. catch (ex) { }
  3474. generateBlobUrl();
  3475. };
  3476. transaction.oncomplete = function (event) {
  3477. generateBlobUrl();
  3478. };
  3479. var newTexture = { textureUrl: url, data: blob };
  3480. try {
  3481. // Put the blob into the dabase
  3482. var addRequest = transaction.objectStore("textures").put(newTexture);
  3483. addRequest.onsuccess = function (event) {
  3484. };
  3485. addRequest.onerror = function (event) {
  3486. generateBlobUrl();
  3487. };
  3488. }
  3489. catch (ex) {
  3490. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3491. if (ex.code === 25) {
  3492. Database.IsUASupportingBlobStorage = false;
  3493. }
  3494. image.src = url;
  3495. }
  3496. }
  3497. else {
  3498. image.src = url;
  3499. }
  3500. }, false);
  3501. xhr.addEventListener("error", function (event) {
  3502. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3503. image.src = url;
  3504. }, false);
  3505. xhr.send();
  3506. }
  3507. else {
  3508. image.src = url;
  3509. }
  3510. }
  3511. else {
  3512. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3513. image.src = url;
  3514. }
  3515. };
  3516. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3517. var _this = this;
  3518. var updateVersion = function (event) {
  3519. // the version is not yet in the DB or we need to update it
  3520. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3521. };
  3522. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3523. };
  3524. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3525. var _this = this;
  3526. if (this.isSupported) {
  3527. var version;
  3528. try {
  3529. var transaction = this.db.transaction(["versions"]);
  3530. transaction.oncomplete = function (event) {
  3531. if (version) {
  3532. // If the version in the JSON file is > than the version in DB
  3533. if (_this.manifestVersionFound > version.data) {
  3534. _this.mustUpdateRessources = true;
  3535. updateInDBCallback();
  3536. }
  3537. else {
  3538. callback(version.data);
  3539. }
  3540. }
  3541. else {
  3542. _this.mustUpdateRessources = true;
  3543. updateInDBCallback();
  3544. }
  3545. };
  3546. transaction.onabort = function (event) {
  3547. callback(-1);
  3548. };
  3549. var getRequest = transaction.objectStore("versions").get(url);
  3550. getRequest.onsuccess = function (event) {
  3551. version = (event.target).result;
  3552. };
  3553. getRequest.onerror = function (event) {
  3554. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3555. callback(-1);
  3556. };
  3557. }
  3558. catch (ex) {
  3559. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3560. callback(-1);
  3561. }
  3562. }
  3563. else {
  3564. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3565. callback(-1);
  3566. }
  3567. };
  3568. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3569. var _this = this;
  3570. if (this.isSupported && !this.hasReachedQuota) {
  3571. try {
  3572. // Open a transaction to the database
  3573. var transaction = this.db.transaction(["versions"], "readwrite");
  3574. // the transaction could abort because of a QuotaExceededError error
  3575. transaction.onabort = function (event) {
  3576. try {
  3577. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3578. _this.hasReachedQuota = true;
  3579. }
  3580. }
  3581. catch (ex) { }
  3582. callback(-1);
  3583. };
  3584. transaction.oncomplete = function (event) {
  3585. callback(_this.manifestVersionFound);
  3586. };
  3587. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3588. // Put the scene into the database
  3589. var addRequest = transaction.objectStore("versions").put(newVersion);
  3590. addRequest.onsuccess = function (event) {
  3591. };
  3592. addRequest.onerror = function (event) {
  3593. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3594. };
  3595. }
  3596. catch (ex) {
  3597. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3598. callback(-1);
  3599. }
  3600. }
  3601. else {
  3602. callback(-1);
  3603. }
  3604. };
  3605. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3606. var _this = this;
  3607. var completeUrl = Database.ReturnFullUrlLocation(url);
  3608. var saveAndLoadFile = function (event) {
  3609. // the scene is not yet in the DB, let's try to save it
  3610. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3611. };
  3612. this._checkVersionFromDB(completeUrl, function (version) {
  3613. if (version !== -1) {
  3614. if (!_this.mustUpdateRessources) {
  3615. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3616. }
  3617. else {
  3618. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3619. }
  3620. }
  3621. else {
  3622. errorCallback();
  3623. }
  3624. });
  3625. };
  3626. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3627. if (this.isSupported) {
  3628. var targetStore;
  3629. if (url.indexOf(".babylon") !== -1) {
  3630. targetStore = "scenes";
  3631. }
  3632. else {
  3633. targetStore = "textures";
  3634. }
  3635. var file;
  3636. var transaction = this.db.transaction([targetStore]);
  3637. transaction.oncomplete = function (event) {
  3638. if (file) {
  3639. callback(file.data);
  3640. }
  3641. else {
  3642. notInDBCallback();
  3643. }
  3644. };
  3645. transaction.onabort = function (event) {
  3646. notInDBCallback();
  3647. };
  3648. var getRequest = transaction.objectStore(targetStore).get(url);
  3649. getRequest.onsuccess = function (event) {
  3650. file = (event.target).result;
  3651. };
  3652. getRequest.onerror = function (event) {
  3653. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3654. notInDBCallback();
  3655. };
  3656. }
  3657. else {
  3658. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3659. callback();
  3660. }
  3661. };
  3662. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3663. var _this = this;
  3664. if (this.isSupported) {
  3665. var targetStore;
  3666. if (url.indexOf(".babylon") !== -1) {
  3667. targetStore = "scenes";
  3668. }
  3669. else {
  3670. targetStore = "textures";
  3671. }
  3672. // Create XHR
  3673. var xhr = new XMLHttpRequest(), fileData;
  3674. xhr.open("GET", url, true);
  3675. if (useArrayBuffer) {
  3676. xhr.responseType = "arraybuffer";
  3677. }
  3678. xhr.onprogress = progressCallback;
  3679. xhr.addEventListener("load", function () {
  3680. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3681. // Blob as response (XHR2)
  3682. //fileData = xhr.responseText;
  3683. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3684. if (!_this.hasReachedQuota) {
  3685. // Open a transaction to the database
  3686. var transaction = _this.db.transaction([targetStore], "readwrite");
  3687. // the transaction could abort because of a QuotaExceededError error
  3688. transaction.onabort = function (event) {
  3689. try {
  3690. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3691. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3692. this.hasReachedQuota = true;
  3693. }
  3694. }
  3695. catch (ex) { }
  3696. callback(fileData);
  3697. };
  3698. transaction.oncomplete = function (event) {
  3699. callback(fileData);
  3700. };
  3701. var newFile;
  3702. if (targetStore === "scenes") {
  3703. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3704. }
  3705. else {
  3706. newFile = { textureUrl: url, data: fileData };
  3707. }
  3708. try {
  3709. // Put the scene into the database
  3710. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3711. addRequest.onsuccess = function (event) {
  3712. };
  3713. addRequest.onerror = function (event) {
  3714. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3715. };
  3716. }
  3717. catch (ex) {
  3718. callback(fileData);
  3719. }
  3720. }
  3721. else {
  3722. callback(fileData);
  3723. }
  3724. }
  3725. else {
  3726. callback();
  3727. }
  3728. }, false);
  3729. xhr.addEventListener("error", function (event) {
  3730. BABYLON.Tools.Error("error on XHR request.");
  3731. callback();
  3732. }, false);
  3733. xhr.send();
  3734. }
  3735. else {
  3736. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3737. callback();
  3738. }
  3739. };
  3740. Database.IsUASupportingBlobStorage = true;
  3741. Database.IDBStorageEnabled = true;
  3742. Database.parseURL = function (url) {
  3743. var a = document.createElement('a');
  3744. a.href = url;
  3745. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3746. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3747. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3748. return absLocation;
  3749. };
  3750. Database.ReturnFullUrlLocation = function (url) {
  3751. if (url.indexOf("http:/") === -1) {
  3752. return (Database.parseURL(window.location.href) + url);
  3753. }
  3754. else {
  3755. return url;
  3756. }
  3757. };
  3758. return Database;
  3759. })();
  3760. BABYLON.Database = Database;
  3761. })(BABYLON || (BABYLON = {}));
  3762. var BABYLON;
  3763. (function (BABYLON) {
  3764. var Internals;
  3765. (function (Internals) {
  3766. /*
  3767. * Based on jsTGALoader - Javascript loader for TGA file
  3768. * By Vincent Thibault
  3769. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3770. */
  3771. var TGATools = (function () {
  3772. function TGATools() {
  3773. }
  3774. TGATools.GetTGAHeader = function (data) {
  3775. var offset = 0;
  3776. var header = {
  3777. id_length: data[offset++],
  3778. colormap_type: data[offset++],
  3779. image_type: data[offset++],
  3780. colormap_index: data[offset++] | data[offset++] << 8,
  3781. colormap_length: data[offset++] | data[offset++] << 8,
  3782. colormap_size: data[offset++],
  3783. origin: [
  3784. data[offset++] | data[offset++] << 8,
  3785. data[offset++] | data[offset++] << 8
  3786. ],
  3787. width: data[offset++] | data[offset++] << 8,
  3788. height: data[offset++] | data[offset++] << 8,
  3789. pixel_size: data[offset++],
  3790. flags: data[offset++]
  3791. };
  3792. return header;
  3793. };
  3794. TGATools.UploadContent = function (gl, data) {
  3795. // Not enough data to contain header ?
  3796. if (data.length < 19) {
  3797. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3798. return;
  3799. }
  3800. // Read Header
  3801. var offset = 18;
  3802. var header = TGATools.GetTGAHeader(data);
  3803. // Assume it's a valid Targa file.
  3804. if (header.id_length + offset > data.length) {
  3805. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3806. return;
  3807. }
  3808. // Skip not needed data
  3809. offset += header.id_length;
  3810. var use_rle = false;
  3811. var use_pal = false;
  3812. var use_rgb = false;
  3813. var use_grey = false;
  3814. // Get some informations.
  3815. switch (header.image_type) {
  3816. case TGATools._TYPE_RLE_INDEXED:
  3817. use_rle = true;
  3818. case TGATools._TYPE_INDEXED:
  3819. use_pal = true;
  3820. break;
  3821. case TGATools._TYPE_RLE_RGB:
  3822. use_rle = true;
  3823. case TGATools._TYPE_RGB:
  3824. use_rgb = true;
  3825. break;
  3826. case TGATools._TYPE_RLE_GREY:
  3827. use_rle = true;
  3828. case TGATools._TYPE_GREY:
  3829. use_grey = true;
  3830. break;
  3831. }
  3832. var pixel_data;
  3833. var numAlphaBits = header.flags & 0xf;
  3834. var pixel_size = header.pixel_size >> 3;
  3835. var pixel_total = header.width * header.height * pixel_size;
  3836. // Read palettes
  3837. var palettes;
  3838. if (use_pal) {
  3839. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3840. }
  3841. // Read LRE
  3842. if (use_rle) {
  3843. pixel_data = new Uint8Array(pixel_total);
  3844. var c, count, i;
  3845. var localOffset = 0;
  3846. var pixels = new Uint8Array(pixel_size);
  3847. while (offset < pixel_total && localOffset < pixel_total) {
  3848. c = data[offset++];
  3849. count = (c & 0x7f) + 1;
  3850. // RLE pixels
  3851. if (c & 0x80) {
  3852. // Bind pixel tmp array
  3853. for (i = 0; i < pixel_size; ++i) {
  3854. pixels[i] = data[offset++];
  3855. }
  3856. // Copy pixel array
  3857. for (i = 0; i < count; ++i) {
  3858. pixel_data.set(pixels, localOffset + i * pixel_size);
  3859. }
  3860. localOffset += pixel_size * count;
  3861. }
  3862. else {
  3863. count *= pixel_size;
  3864. for (i = 0; i < count; ++i) {
  3865. pixel_data[localOffset + i] = data[offset++];
  3866. }
  3867. localOffset += count;
  3868. }
  3869. }
  3870. }
  3871. else {
  3872. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3873. }
  3874. // Load to texture
  3875. var x_start, y_start, x_step, y_step, y_end, x_end;
  3876. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3877. default:
  3878. case TGATools._ORIGIN_UL:
  3879. x_start = 0;
  3880. x_step = 1;
  3881. x_end = header.width;
  3882. y_start = 0;
  3883. y_step = 1;
  3884. y_end = header.height;
  3885. break;
  3886. case TGATools._ORIGIN_BL:
  3887. x_start = 0;
  3888. x_step = 1;
  3889. x_end = header.width;
  3890. y_start = header.height - 1;
  3891. y_step = -1;
  3892. y_end = -1;
  3893. break;
  3894. case TGATools._ORIGIN_UR:
  3895. x_start = header.width - 1;
  3896. x_step = -1;
  3897. x_end = -1;
  3898. y_start = 0;
  3899. y_step = 1;
  3900. y_end = header.height;
  3901. break;
  3902. case TGATools._ORIGIN_BR:
  3903. x_start = header.width - 1;
  3904. x_step = -1;
  3905. x_end = -1;
  3906. y_start = header.height - 1;
  3907. y_step = -1;
  3908. y_end = -1;
  3909. break;
  3910. }
  3911. // Load the specify method
  3912. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3913. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3914. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3915. };
  3916. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3917. var image = pixel_data, colormap = palettes;
  3918. var width = header.width, height = header.height;
  3919. var color, i = 0, x, y;
  3920. var imageData = new Uint8Array(width * height * 4);
  3921. for (y = y_start; y !== y_end; y += y_step) {
  3922. for (x = x_start; x !== x_end; x += x_step, i++) {
  3923. color = image[i];
  3924. imageData[(x + width * y) * 4 + 3] = 255;
  3925. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3926. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3927. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3928. }
  3929. }
  3930. return imageData;
  3931. };
  3932. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3933. var image = pixel_data;
  3934. var width = header.width, height = header.height;
  3935. var color, i = 0, x, y;
  3936. var imageData = new Uint8Array(width * height * 4);
  3937. for (y = y_start; y !== y_end; y += y_step) {
  3938. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3939. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3940. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3941. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3942. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3943. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3944. }
  3945. }
  3946. return imageData;
  3947. };
  3948. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3949. var image = pixel_data;
  3950. var width = header.width, height = header.height;
  3951. var i = 0, x, y;
  3952. var imageData = new Uint8Array(width * height * 4);
  3953. for (y = y_start; y !== y_end; y += y_step) {
  3954. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3955. imageData[(x + width * y) * 4 + 3] = 255;
  3956. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3957. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3958. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3959. }
  3960. }
  3961. return imageData;
  3962. };
  3963. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3964. var image = pixel_data;
  3965. var width = header.width, height = header.height;
  3966. var i = 0, x, y;
  3967. var imageData = new Uint8Array(width * height * 4);
  3968. for (y = y_start; y !== y_end; y += y_step) {
  3969. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3970. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3971. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3972. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3973. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3974. }
  3975. }
  3976. return imageData;
  3977. };
  3978. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3979. var image = pixel_data;
  3980. var width = header.width, height = header.height;
  3981. var color, i = 0, x, y;
  3982. var imageData = new Uint8Array(width * height * 4);
  3983. for (y = y_start; y !== y_end; y += y_step) {
  3984. for (x = x_start; x !== x_end; x += x_step, i++) {
  3985. color = image[i];
  3986. imageData[(x + width * y) * 4 + 0] = color;
  3987. imageData[(x + width * y) * 4 + 1] = color;
  3988. imageData[(x + width * y) * 4 + 2] = color;
  3989. imageData[(x + width * y) * 4 + 3] = 255;
  3990. }
  3991. }
  3992. return imageData;
  3993. };
  3994. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3995. var image = pixel_data;
  3996. var width = header.width, height = header.height;
  3997. var i = 0, x, y;
  3998. var imageData = new Uint8Array(width * height * 4);
  3999. for (y = y_start; y !== y_end; y += y_step) {
  4000. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4001. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4002. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4003. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4004. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4005. }
  4006. }
  4007. return imageData;
  4008. };
  4009. TGATools._TYPE_NO_DATA = 0;
  4010. TGATools._TYPE_INDEXED = 1;
  4011. TGATools._TYPE_RGB = 2;
  4012. TGATools._TYPE_GREY = 3;
  4013. TGATools._TYPE_RLE_INDEXED = 9;
  4014. TGATools._TYPE_RLE_RGB = 10;
  4015. TGATools._TYPE_RLE_GREY = 11;
  4016. TGATools._ORIGIN_MASK = 0x30;
  4017. TGATools._ORIGIN_SHIFT = 0x04;
  4018. TGATools._ORIGIN_BL = 0x00;
  4019. TGATools._ORIGIN_BR = 0x01;
  4020. TGATools._ORIGIN_UL = 0x02;
  4021. TGATools._ORIGIN_UR = 0x03;
  4022. return TGATools;
  4023. })();
  4024. Internals.TGATools = TGATools;
  4025. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4026. })(BABYLON || (BABYLON = {}));
  4027. var BABYLON;
  4028. (function (BABYLON) {
  4029. var SmartArray = (function () {
  4030. function SmartArray(capacity) {
  4031. this.length = 0;
  4032. this._duplicateId = 0;
  4033. this.data = new Array(capacity);
  4034. this._id = SmartArray._GlobalId++;
  4035. }
  4036. SmartArray.prototype.push = function (value) {
  4037. this.data[this.length++] = value;
  4038. if (this.length > this.data.length) {
  4039. this.data.length *= 2;
  4040. }
  4041. if (!value.__smartArrayFlags) {
  4042. value.__smartArrayFlags = {};
  4043. }
  4044. value.__smartArrayFlags[this._id] = this._duplicateId;
  4045. };
  4046. SmartArray.prototype.pushNoDuplicate = function (value) {
  4047. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4048. return;
  4049. }
  4050. this.push(value);
  4051. };
  4052. SmartArray.prototype.sort = function (compareFn) {
  4053. this.data.sort(compareFn);
  4054. };
  4055. SmartArray.prototype.reset = function () {
  4056. this.length = 0;
  4057. this._duplicateId++;
  4058. };
  4059. SmartArray.prototype.concat = function (array) {
  4060. if (array.length === 0) {
  4061. return;
  4062. }
  4063. if (this.length + array.length > this.data.length) {
  4064. this.data.length = (this.length + array.length) * 2;
  4065. }
  4066. for (var index = 0; index < array.length; index++) {
  4067. this.data[this.length++] = (array.data || array)[index];
  4068. }
  4069. };
  4070. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4071. if (array.length === 0) {
  4072. return;
  4073. }
  4074. if (this.length + array.length > this.data.length) {
  4075. this.data.length = (this.length + array.length) * 2;
  4076. }
  4077. for (var index = 0; index < array.length; index++) {
  4078. var item = (array.data || array)[index];
  4079. this.pushNoDuplicate(item);
  4080. }
  4081. };
  4082. SmartArray.prototype.indexOf = function (value) {
  4083. var position = this.data.indexOf(value);
  4084. if (position >= this.length) {
  4085. return -1;
  4086. }
  4087. return position;
  4088. };
  4089. // Statics
  4090. SmartArray._GlobalId = 0;
  4091. return SmartArray;
  4092. })();
  4093. BABYLON.SmartArray = SmartArray;
  4094. })(BABYLON || (BABYLON = {}));
  4095. var BABYLON;
  4096. (function (BABYLON) {
  4097. /**
  4098. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4099. * The underlying implemetation relies on an associative array to ensure the best performances.
  4100. * The value can be anything including 'null' but except 'undefined'
  4101. */
  4102. var StringDictionary = (function () {
  4103. function StringDictionary() {
  4104. this._count = 0;
  4105. this._data = {};
  4106. }
  4107. /**
  4108. * Get a value based from its key
  4109. * @param key the given key to get the matching value from
  4110. * @return the value if found, otherwise undefined is returned
  4111. */
  4112. StringDictionary.prototype.get = function (key) {
  4113. var val = this._data[key];
  4114. if (val !== undefined) {
  4115. return val;
  4116. }
  4117. return undefined;
  4118. };
  4119. /**
  4120. * Get a value from its key or add it if it doesn't exist.
  4121. * This method will ensure you that a given key/data will be present in the dictionary.
  4122. * @param key the given key to get the matchin value from
  4123. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4124. * The factory will only be invoked if there's no data for the given key.
  4125. * @return the value corresponding to the key.
  4126. */
  4127. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4128. var val = this.get(key);
  4129. if (val !== undefined) {
  4130. return val;
  4131. }
  4132. val = factory(key);
  4133. if (val) {
  4134. this.add(key, val);
  4135. }
  4136. return val;
  4137. };
  4138. /**
  4139. * Get a value from its key if present in the dictionary otherwise add it
  4140. * @param key the key to get the value from
  4141. * @param val if there's no such key/value pair in the dictionary add it with this value
  4142. * @return the value corresponding to the key
  4143. */
  4144. StringDictionary.prototype.getOrAdd = function (key, val) {
  4145. var val = this.get(key);
  4146. if (val !== undefined) {
  4147. return val;
  4148. }
  4149. this.add(key, val);
  4150. return val;
  4151. };
  4152. /**
  4153. * Check if there's a given key in the dictionary
  4154. * @param key the key to check for
  4155. * @return true if the key is present, false otherwise
  4156. */
  4157. StringDictionary.prototype.contains = function (key) {
  4158. return this._data[key] !== undefined;
  4159. };
  4160. /**
  4161. * Add a new key and its corresponding value
  4162. * @param key the key to add
  4163. * @param value the value corresponding to the key
  4164. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4165. */
  4166. StringDictionary.prototype.add = function (key, value) {
  4167. if (this._data[key] !== undefined) {
  4168. return false;
  4169. }
  4170. this._data[key] = value;
  4171. ++this._count;
  4172. return true;
  4173. };
  4174. /**
  4175. * Remove a key/value from the dictionary.
  4176. * @param key the key to remove
  4177. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4178. */
  4179. StringDictionary.prototype.remove = function (key) {
  4180. if (this.contains(key)) {
  4181. delete this._data[key];
  4182. --this._count;
  4183. return true;
  4184. }
  4185. return false;
  4186. };
  4187. /**
  4188. * Clear the whole content of the dictionary
  4189. */
  4190. StringDictionary.prototype.clear = function () {
  4191. this._data = {};
  4192. this._count = 0;
  4193. };
  4194. Object.defineProperty(StringDictionary.prototype, "count", {
  4195. get: function () {
  4196. return this._count;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. /**
  4202. * Execute a callback on each key/val of the dictionary.
  4203. * Note that you can remove any element in this dictionary in the callback implementation
  4204. * @param callback the callback to execute on a given key/value pair
  4205. */
  4206. StringDictionary.prototype.forEach = function (callback) {
  4207. for (var cur in this._data) {
  4208. var val = this._data[cur];
  4209. callback(cur, val);
  4210. }
  4211. };
  4212. /**
  4213. * Execute a callback on every occurence of the dictionary until it returns a valid TRes object.
  4214. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4215. * Note that you can remove any element in this dictionary in the callback implementation
  4216. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4217. */
  4218. StringDictionary.prototype.first = function (callback) {
  4219. for (var cur in this._data) {
  4220. var val = this._data[cur];
  4221. var res = callback(cur, val);
  4222. if (res) {
  4223. return res;
  4224. }
  4225. }
  4226. return null;
  4227. };
  4228. return StringDictionary;
  4229. })();
  4230. BABYLON.StringDictionary = StringDictionary;
  4231. })(BABYLON || (BABYLON = {}));
  4232. var BABYLON;
  4233. (function (BABYLON) {
  4234. // Screenshots
  4235. var screenshotCanvas;
  4236. var cloneValue = function (source, destinationObject) {
  4237. if (!source)
  4238. return null;
  4239. if (source instanceof BABYLON.Mesh) {
  4240. return null;
  4241. }
  4242. if (source instanceof BABYLON.SubMesh) {
  4243. return source.clone(destinationObject);
  4244. }
  4245. else if (source.clone) {
  4246. return source.clone();
  4247. }
  4248. return null;
  4249. };
  4250. var Tools = (function () {
  4251. function Tools() {
  4252. }
  4253. Tools.Instantiate = function (className) {
  4254. var arr = className.split(".");
  4255. var fn = (window || this);
  4256. for (var i = 0, len = arr.length; i < len; i++) {
  4257. fn = fn[arr[i]];
  4258. }
  4259. if (typeof fn !== "function") {
  4260. return null;
  4261. }
  4262. return fn;
  4263. };
  4264. Tools.SetImmediate = function (action) {
  4265. if (window.setImmediate) {
  4266. window.setImmediate(action);
  4267. }
  4268. else {
  4269. setTimeout(action, 1);
  4270. }
  4271. };
  4272. Tools.IsExponentOfTwo = function (value) {
  4273. var count = 1;
  4274. do {
  4275. count *= 2;
  4276. } while (count < value);
  4277. return count === value;
  4278. };
  4279. Tools.GetExponentOfTwo = function (value, max) {
  4280. var count = 1;
  4281. do {
  4282. count *= 2;
  4283. } while (count < value);
  4284. if (count > max)
  4285. count = max;
  4286. return count;
  4287. };
  4288. Tools.GetFilename = function (path) {
  4289. var index = path.lastIndexOf("/");
  4290. if (index < 0)
  4291. return path;
  4292. return path.substring(index + 1);
  4293. };
  4294. Tools.GetDOMTextContent = function (element) {
  4295. var result = "";
  4296. var child = element.firstChild;
  4297. while (child) {
  4298. if (child.nodeType === 3) {
  4299. result += child.textContent;
  4300. }
  4301. child = child.nextSibling;
  4302. }
  4303. return result;
  4304. };
  4305. Tools.ToDegrees = function (angle) {
  4306. return angle * 180 / Math.PI;
  4307. };
  4308. Tools.ToRadians = function (angle) {
  4309. return angle * Math.PI / 180;
  4310. };
  4311. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4312. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4313. var output = "";
  4314. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4315. var i = 0;
  4316. var bytes = new Uint8Array(buffer);
  4317. while (i < bytes.length) {
  4318. chr1 = bytes[i++];
  4319. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4320. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4321. enc1 = chr1 >> 2;
  4322. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4323. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4324. enc4 = chr3 & 63;
  4325. if (isNaN(chr2)) {
  4326. enc3 = enc4 = 64;
  4327. }
  4328. else if (isNaN(chr3)) {
  4329. enc4 = 64;
  4330. }
  4331. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4332. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4333. }
  4334. return "data:image/png;base64," + output;
  4335. };
  4336. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4337. if (bias === void 0) { bias = null; }
  4338. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4339. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4340. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4341. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4342. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4343. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4344. }
  4345. if (bias) {
  4346. minimum.x -= minimum.x * bias.x + bias.y;
  4347. minimum.y -= minimum.y * bias.x + bias.y;
  4348. minimum.z -= minimum.z * bias.x + bias.y;
  4349. maximum.x += maximum.x * bias.x + bias.y;
  4350. maximum.y += maximum.y * bias.x + bias.y;
  4351. maximum.z += maximum.z * bias.x + bias.y;
  4352. }
  4353. return {
  4354. minimum: minimum,
  4355. maximum: maximum
  4356. };
  4357. };
  4358. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4359. if (bias === void 0) { bias = null; }
  4360. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4361. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4362. for (var index = start; index < start + count; index++) {
  4363. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4364. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4365. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4366. }
  4367. if (bias) {
  4368. minimum.x -= minimum.x * bias.x + bias.y;
  4369. minimum.y -= minimum.y * bias.x + bias.y;
  4370. minimum.z -= minimum.z * bias.x + bias.y;
  4371. maximum.x += maximum.x * bias.x + bias.y;
  4372. maximum.y += maximum.y * bias.x + bias.y;
  4373. maximum.z += maximum.z * bias.x + bias.y;
  4374. }
  4375. return {
  4376. minimum: minimum,
  4377. maximum: maximum
  4378. };
  4379. };
  4380. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4381. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4382. return undefined;
  4383. return Array.isArray(obj) ? obj : [obj];
  4384. };
  4385. // Misc.
  4386. Tools.GetPointerPrefix = function () {
  4387. var eventPrefix = "pointer";
  4388. // Check if pointer events are supported
  4389. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4390. eventPrefix = "mouse";
  4391. }
  4392. return eventPrefix;
  4393. };
  4394. Tools.QueueNewFrame = function (func) {
  4395. if (window.requestAnimationFrame)
  4396. window.requestAnimationFrame(func);
  4397. else if (window.msRequestAnimationFrame)
  4398. window.msRequestAnimationFrame(func);
  4399. else if (window.webkitRequestAnimationFrame)
  4400. window.webkitRequestAnimationFrame(func);
  4401. else if (window.mozRequestAnimationFrame)
  4402. window.mozRequestAnimationFrame(func);
  4403. else if (window.oRequestAnimationFrame)
  4404. window.oRequestAnimationFrame(func);
  4405. else {
  4406. window.setTimeout(func, 16);
  4407. }
  4408. };
  4409. Tools.RequestFullscreen = function (element) {
  4410. if (element.requestFullscreen)
  4411. element.requestFullscreen();
  4412. else if (element.msRequestFullscreen)
  4413. element.msRequestFullscreen();
  4414. else if (element.webkitRequestFullscreen)
  4415. element.webkitRequestFullscreen();
  4416. else if (element.mozRequestFullScreen)
  4417. element.mozRequestFullScreen();
  4418. };
  4419. Tools.ExitFullscreen = function () {
  4420. if (document.exitFullscreen) {
  4421. document.exitFullscreen();
  4422. }
  4423. else if (document.mozCancelFullScreen) {
  4424. document.mozCancelFullScreen();
  4425. }
  4426. else if (document.webkitCancelFullScreen) {
  4427. document.webkitCancelFullScreen();
  4428. }
  4429. else if (document.msCancelFullScreen) {
  4430. document.msCancelFullScreen();
  4431. }
  4432. };
  4433. // External files
  4434. Tools.CleanUrl = function (url) {
  4435. url = url.replace(/#/mg, "%23");
  4436. return url;
  4437. };
  4438. Tools.LoadImage = function (url, onload, onerror, database) {
  4439. if (url instanceof ArrayBuffer) {
  4440. url = Tools.EncodeArrayBufferTobase64(url);
  4441. }
  4442. url = Tools.CleanUrl(url);
  4443. var img = new Image();
  4444. if (url.substr(0, 5) !== "data:") {
  4445. if (Tools.CorsBehavior) {
  4446. switch (typeof (Tools.CorsBehavior)) {
  4447. case "function":
  4448. var result = Tools.CorsBehavior(url);
  4449. if (result) {
  4450. img.crossOrigin = result;
  4451. }
  4452. break;
  4453. case "string":
  4454. default:
  4455. img.crossOrigin = Tools.CorsBehavior;
  4456. break;
  4457. }
  4458. }
  4459. }
  4460. img.onload = function () {
  4461. onload(img);
  4462. };
  4463. img.onerror = function (err) {
  4464. Tools.Error("Error while trying to load texture: " + url);
  4465. if (Tools.UseFallbackTexture) {
  4466. 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";
  4467. onload(img);
  4468. }
  4469. else {
  4470. onerror();
  4471. }
  4472. };
  4473. var noIndexedDB = function () {
  4474. img.src = url;
  4475. };
  4476. var loadFromIndexedDB = function () {
  4477. database.loadImageFromDB(url, img);
  4478. };
  4479. //ANY database to do!
  4480. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4481. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4482. }
  4483. else {
  4484. if (url.indexOf("file:") === -1) {
  4485. noIndexedDB();
  4486. }
  4487. else {
  4488. try {
  4489. var textureName = url.substring(5).toLowerCase();
  4490. var blobURL;
  4491. try {
  4492. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4493. }
  4494. catch (ex) {
  4495. // Chrome doesn't support oneTimeOnly parameter
  4496. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4497. }
  4498. img.src = blobURL;
  4499. }
  4500. catch (e) {
  4501. img.src = null;
  4502. }
  4503. }
  4504. }
  4505. return img;
  4506. };
  4507. //ANY
  4508. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4509. url = Tools.CleanUrl(url);
  4510. var noIndexedDB = function () {
  4511. var request = new XMLHttpRequest();
  4512. var loadUrl = Tools.BaseUrl + url;
  4513. request.open('GET', loadUrl, true);
  4514. if (useArrayBuffer) {
  4515. request.responseType = "arraybuffer";
  4516. }
  4517. request.onprogress = progressCallBack;
  4518. request.onreadystatechange = function () {
  4519. if (request.readyState === 4) {
  4520. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4521. callback(!useArrayBuffer ? request.responseText : request.response);
  4522. }
  4523. else {
  4524. if (onError) {
  4525. onError();
  4526. }
  4527. else {
  4528. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4529. }
  4530. }
  4531. }
  4532. };
  4533. request.send(null);
  4534. };
  4535. var loadFromIndexedDB = function () {
  4536. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4537. };
  4538. if (url.indexOf("file:") !== -1) {
  4539. var fileName = url.substring(5).toLowerCase();
  4540. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4541. }
  4542. else {
  4543. // Caching all files
  4544. if (database && database.enableSceneOffline) {
  4545. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4546. }
  4547. else {
  4548. noIndexedDB();
  4549. }
  4550. }
  4551. };
  4552. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4553. var reader = new FileReader();
  4554. reader.onload = function (e) {
  4555. //target doesn't have result from ts 1.3
  4556. callback(e.target['result']);
  4557. };
  4558. reader.onprogress = progressCallback;
  4559. reader.readAsDataURL(fileToLoad);
  4560. };
  4561. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4562. var reader = new FileReader();
  4563. reader.onerror = function (e) {
  4564. Tools.Log("Error while reading file: " + fileToLoad.name);
  4565. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4566. };
  4567. reader.onload = function (e) {
  4568. //target doesn't have result from ts 1.3
  4569. callback(e.target['result']);
  4570. };
  4571. reader.onprogress = progressCallBack;
  4572. if (!useArrayBuffer) {
  4573. // Asynchronous read
  4574. reader.readAsText(fileToLoad);
  4575. }
  4576. else {
  4577. reader.readAsArrayBuffer(fileToLoad);
  4578. }
  4579. };
  4580. //returns a downloadable url to a file content.
  4581. Tools.FileAsURL = function (content) {
  4582. var fileBlob = new Blob([content]);
  4583. var url = window.URL || window.webkitURL;
  4584. var link = url.createObjectURL(fileBlob);
  4585. return link;
  4586. };
  4587. // Misc.
  4588. Tools.Format = function (value, decimals) {
  4589. if (decimals === void 0) { decimals = 2; }
  4590. return value.toFixed(decimals);
  4591. };
  4592. Tools.CheckExtends = function (v, min, max) {
  4593. if (v.x < min.x)
  4594. min.x = v.x;
  4595. if (v.y < min.y)
  4596. min.y = v.y;
  4597. if (v.z < min.z)
  4598. min.z = v.z;
  4599. if (v.x > max.x)
  4600. max.x = v.x;
  4601. if (v.y > max.y)
  4602. max.y = v.y;
  4603. if (v.z > max.z)
  4604. max.z = v.z;
  4605. };
  4606. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4607. for (var prop in source) {
  4608. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4609. continue;
  4610. }
  4611. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4612. continue;
  4613. }
  4614. var sourceValue = source[prop];
  4615. var typeOfSourceValue = typeof sourceValue;
  4616. if (typeOfSourceValue === "function") {
  4617. continue;
  4618. }
  4619. if (typeOfSourceValue === "object") {
  4620. if (sourceValue instanceof Array) {
  4621. destination[prop] = [];
  4622. if (sourceValue.length > 0) {
  4623. if (typeof sourceValue[0] == "object") {
  4624. for (var index = 0; index < sourceValue.length; index++) {
  4625. var clonedValue = cloneValue(sourceValue[index], destination);
  4626. if (destination[prop].indexOf(clonedValue) === -1) {
  4627. destination[prop].push(clonedValue);
  4628. }
  4629. }
  4630. }
  4631. else {
  4632. destination[prop] = sourceValue.slice(0);
  4633. }
  4634. }
  4635. }
  4636. else {
  4637. destination[prop] = cloneValue(sourceValue, destination);
  4638. }
  4639. }
  4640. else {
  4641. destination[prop] = sourceValue;
  4642. }
  4643. }
  4644. };
  4645. Tools.IsEmpty = function (obj) {
  4646. for (var i in obj) {
  4647. return false;
  4648. }
  4649. return true;
  4650. };
  4651. Tools.RegisterTopRootEvents = function (events) {
  4652. for (var index = 0; index < events.length; index++) {
  4653. var event = events[index];
  4654. window.addEventListener(event.name, event.handler, false);
  4655. try {
  4656. if (window.parent) {
  4657. window.parent.addEventListener(event.name, event.handler, false);
  4658. }
  4659. }
  4660. catch (e) {
  4661. }
  4662. }
  4663. };
  4664. Tools.UnregisterTopRootEvents = function (events) {
  4665. for (var index = 0; index < events.length; index++) {
  4666. var event = events[index];
  4667. window.removeEventListener(event.name, event.handler);
  4668. try {
  4669. if (window.parent) {
  4670. window.parent.removeEventListener(event.name, event.handler);
  4671. }
  4672. }
  4673. catch (e) {
  4674. }
  4675. }
  4676. };
  4677. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4678. // Read the contents of the framebuffer
  4679. var numberOfChannelsByLine = width * 4;
  4680. var halfHeight = height / 2;
  4681. //Reading datas from WebGL
  4682. var data = engine.readPixels(0, 0, width, height);
  4683. //To flip image on Y axis.
  4684. for (var i = 0; i < halfHeight; i++) {
  4685. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4686. var currentCell = j + i * numberOfChannelsByLine;
  4687. var targetLine = height - i - 1;
  4688. var targetCell = j + targetLine * numberOfChannelsByLine;
  4689. var temp = data[currentCell];
  4690. data[currentCell] = data[targetCell];
  4691. data[targetCell] = temp;
  4692. }
  4693. }
  4694. // Create a 2D canvas to store the result
  4695. if (!screenshotCanvas) {
  4696. screenshotCanvas = document.createElement('canvas');
  4697. }
  4698. screenshotCanvas.width = width;
  4699. screenshotCanvas.height = height;
  4700. var context = screenshotCanvas.getContext('2d');
  4701. // Copy the pixels to a 2D canvas
  4702. var imageData = context.createImageData(width, height);
  4703. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4704. var castData = imageData.data;
  4705. castData.set(data);
  4706. context.putImageData(imageData, 0, 0);
  4707. var base64Image = screenshotCanvas.toDataURL();
  4708. if (successCallback) {
  4709. successCallback(base64Image);
  4710. }
  4711. else {
  4712. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4713. if (("download" in document.createElement("a"))) {
  4714. var a = window.document.createElement("a");
  4715. a.href = base64Image;
  4716. var date = new Date();
  4717. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4718. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4719. window.document.body.appendChild(a);
  4720. a.addEventListener("click", function () {
  4721. a.parentElement.removeChild(a);
  4722. });
  4723. a.click();
  4724. }
  4725. else {
  4726. var newWindow = window.open("");
  4727. var img = newWindow.document.createElement("img");
  4728. img.src = base64Image;
  4729. newWindow.document.body.appendChild(img);
  4730. }
  4731. }
  4732. };
  4733. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4734. var width;
  4735. var height;
  4736. //If a precision value is specified
  4737. if (size.precision) {
  4738. width = Math.round(engine.getRenderWidth() * size.precision);
  4739. height = Math.round(width / engine.getAspectRatio(camera));
  4740. size = { width: width, height: height };
  4741. }
  4742. else if (size.width && size.height) {
  4743. width = size.width;
  4744. height = size.height;
  4745. }
  4746. else if (size.width && !size.height) {
  4747. width = size.width;
  4748. height = Math.round(width / engine.getAspectRatio(camera));
  4749. size = { width: width, height: height };
  4750. }
  4751. else if (size.height && !size.width) {
  4752. height = size.height;
  4753. width = Math.round(height * engine.getAspectRatio(camera));
  4754. size = { width: width, height: height };
  4755. }
  4756. else if (!isNaN(size)) {
  4757. height = size;
  4758. width = size;
  4759. }
  4760. else {
  4761. Tools.Error("Invalid 'size' parameter !");
  4762. return;
  4763. }
  4764. var scene = camera.getScene();
  4765. var previousCamera = null;
  4766. if (scene.activeCamera !== camera) {
  4767. previousCamera = scene.activeCamera;
  4768. scene.activeCamera = camera;
  4769. }
  4770. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4771. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4772. texture.renderList = scene.meshes;
  4773. texture.onAfterRender = function () {
  4774. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4775. };
  4776. scene.incrementRenderId();
  4777. texture.render(true);
  4778. texture.dispose();
  4779. if (previousCamera) {
  4780. scene.activeCamera = previousCamera;
  4781. }
  4782. camera.getProjectionMatrix(true); // Force cache refresh;
  4783. };
  4784. // XHR response validator for local file scenario
  4785. Tools.ValidateXHRData = function (xhr, dataType) {
  4786. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4787. if (dataType === void 0) { dataType = 7; }
  4788. try {
  4789. if (dataType & 1) {
  4790. if (xhr.responseText && xhr.responseText.length > 0) {
  4791. return true;
  4792. }
  4793. else if (dataType === 1) {
  4794. return false;
  4795. }
  4796. }
  4797. if (dataType & 2) {
  4798. // Check header width and height since there is no "TGA" magic number
  4799. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4800. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4801. return true;
  4802. }
  4803. else if (dataType === 2) {
  4804. return false;
  4805. }
  4806. }
  4807. if (dataType & 4) {
  4808. // Check for the "DDS" magic number
  4809. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4810. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4811. return true;
  4812. }
  4813. else {
  4814. return false;
  4815. }
  4816. }
  4817. }
  4818. catch (e) {
  4819. }
  4820. return false;
  4821. };
  4822. Tools.getClassName = function (obj) {
  4823. var funcNameRegex = /function (.{1,})\(/;
  4824. var results = (funcNameRegex).exec((obj).constructor.toString());
  4825. return (results && results.length > 1) ? results[1] : "";
  4826. };
  4827. Object.defineProperty(Tools, "NoneLogLevel", {
  4828. get: function () {
  4829. return Tools._NoneLogLevel;
  4830. },
  4831. enumerable: true,
  4832. configurable: true
  4833. });
  4834. Object.defineProperty(Tools, "MessageLogLevel", {
  4835. get: function () {
  4836. return Tools._MessageLogLevel;
  4837. },
  4838. enumerable: true,
  4839. configurable: true
  4840. });
  4841. Object.defineProperty(Tools, "WarningLogLevel", {
  4842. get: function () {
  4843. return Tools._WarningLogLevel;
  4844. },
  4845. enumerable: true,
  4846. configurable: true
  4847. });
  4848. Object.defineProperty(Tools, "ErrorLogLevel", {
  4849. get: function () {
  4850. return Tools._ErrorLogLevel;
  4851. },
  4852. enumerable: true,
  4853. configurable: true
  4854. });
  4855. Object.defineProperty(Tools, "AllLogLevel", {
  4856. get: function () {
  4857. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4858. },
  4859. enumerable: true,
  4860. configurable: true
  4861. });
  4862. Tools._AddLogEntry = function (entry) {
  4863. Tools._LogCache = entry + Tools._LogCache;
  4864. if (Tools.OnNewCacheEntry) {
  4865. Tools.OnNewCacheEntry(entry);
  4866. }
  4867. };
  4868. Tools._FormatMessage = function (message) {
  4869. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4870. var date = new Date();
  4871. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4872. };
  4873. Tools._LogDisabled = function (message) {
  4874. // nothing to do
  4875. };
  4876. Tools._LogEnabled = function (message) {
  4877. var formattedMessage = Tools._FormatMessage(message);
  4878. console.log("BJS - " + formattedMessage);
  4879. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4880. Tools._AddLogEntry(entry);
  4881. };
  4882. Tools._WarnDisabled = function (message) {
  4883. // nothing to do
  4884. };
  4885. Tools._WarnEnabled = function (message) {
  4886. var formattedMessage = Tools._FormatMessage(message);
  4887. console.warn("BJS - " + formattedMessage);
  4888. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4889. Tools._AddLogEntry(entry);
  4890. };
  4891. Tools._ErrorDisabled = function (message) {
  4892. // nothing to do
  4893. };
  4894. Tools._ErrorEnabled = function (message) {
  4895. Tools.errorsCount++;
  4896. var formattedMessage = Tools._FormatMessage(message);
  4897. console.error("BJS - " + formattedMessage);
  4898. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4899. Tools._AddLogEntry(entry);
  4900. };
  4901. Object.defineProperty(Tools, "LogCache", {
  4902. get: function () {
  4903. return Tools._LogCache;
  4904. },
  4905. enumerable: true,
  4906. configurable: true
  4907. });
  4908. Tools.ClearLogCache = function () {
  4909. Tools._LogCache = "";
  4910. Tools.errorsCount = 0;
  4911. };
  4912. Object.defineProperty(Tools, "LogLevels", {
  4913. set: function (level) {
  4914. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4915. Tools.Log = Tools._LogEnabled;
  4916. }
  4917. else {
  4918. Tools.Log = Tools._LogDisabled;
  4919. }
  4920. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4921. Tools.Warn = Tools._WarnEnabled;
  4922. }
  4923. else {
  4924. Tools.Warn = Tools._WarnDisabled;
  4925. }
  4926. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4927. Tools.Error = Tools._ErrorEnabled;
  4928. }
  4929. else {
  4930. Tools.Error = Tools._ErrorDisabled;
  4931. }
  4932. },
  4933. enumerable: true,
  4934. configurable: true
  4935. });
  4936. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4937. get: function () {
  4938. return Tools._PerformanceNoneLogLevel;
  4939. },
  4940. enumerable: true,
  4941. configurable: true
  4942. });
  4943. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4944. get: function () {
  4945. return Tools._PerformanceUserMarkLogLevel;
  4946. },
  4947. enumerable: true,
  4948. configurable: true
  4949. });
  4950. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4951. get: function () {
  4952. return Tools._PerformanceConsoleLogLevel;
  4953. },
  4954. enumerable: true,
  4955. configurable: true
  4956. });
  4957. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4958. set: function (level) {
  4959. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4960. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4961. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4962. return;
  4963. }
  4964. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4965. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4966. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4967. return;
  4968. }
  4969. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4970. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4971. },
  4972. enumerable: true,
  4973. configurable: true
  4974. });
  4975. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4976. };
  4977. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4978. };
  4979. Tools._StartUserMark = function (counterName, condition) {
  4980. if (condition === void 0) { condition = true; }
  4981. if (!condition || !Tools._performance.mark) {
  4982. return;
  4983. }
  4984. Tools._performance.mark(counterName + "-Begin");
  4985. };
  4986. Tools._EndUserMark = function (counterName, condition) {
  4987. if (condition === void 0) { condition = true; }
  4988. if (!condition || !Tools._performance.mark) {
  4989. return;
  4990. }
  4991. Tools._performance.mark(counterName + "-End");
  4992. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4993. };
  4994. Tools._StartPerformanceConsole = function (counterName, condition) {
  4995. if (condition === void 0) { condition = true; }
  4996. if (!condition) {
  4997. return;
  4998. }
  4999. Tools._StartUserMark(counterName, condition);
  5000. if (console.time) {
  5001. console.time(counterName);
  5002. }
  5003. };
  5004. Tools._EndPerformanceConsole = function (counterName, condition) {
  5005. if (condition === void 0) { condition = true; }
  5006. if (!condition) {
  5007. return;
  5008. }
  5009. Tools._EndUserMark(counterName, condition);
  5010. if (console.time) {
  5011. console.timeEnd(counterName);
  5012. }
  5013. };
  5014. Object.defineProperty(Tools, "Now", {
  5015. get: function () {
  5016. if (window.performance && window.performance.now) {
  5017. return window.performance.now();
  5018. }
  5019. return new Date().getTime();
  5020. },
  5021. enumerable: true,
  5022. configurable: true
  5023. });
  5024. Tools.BaseUrl = "";
  5025. Tools.CorsBehavior = "anonymous";
  5026. Tools.UseFallbackTexture = true;
  5027. // Logs
  5028. Tools._NoneLogLevel = 0;
  5029. Tools._MessageLogLevel = 1;
  5030. Tools._WarningLogLevel = 2;
  5031. Tools._ErrorLogLevel = 4;
  5032. Tools._LogCache = "";
  5033. Tools.errorsCount = 0;
  5034. Tools.Log = Tools._LogEnabled;
  5035. Tools.Warn = Tools._WarnEnabled;
  5036. Tools.Error = Tools._ErrorEnabled;
  5037. // Performances
  5038. Tools._PerformanceNoneLogLevel = 0;
  5039. Tools._PerformanceUserMarkLogLevel = 1;
  5040. Tools._PerformanceConsoleLogLevel = 2;
  5041. Tools._performance = window.performance;
  5042. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5043. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5044. return Tools;
  5045. })();
  5046. BABYLON.Tools = Tools;
  5047. /**
  5048. * An implementation of a loop for asynchronous functions.
  5049. */
  5050. var AsyncLoop = (function () {
  5051. /**
  5052. * Constroctor.
  5053. * @param iterations the number of iterations.
  5054. * @param _fn the function to run each iteration
  5055. * @param _successCallback the callback that will be called upon succesful execution
  5056. * @param offset starting offset.
  5057. */
  5058. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5059. if (offset === void 0) { offset = 0; }
  5060. this.iterations = iterations;
  5061. this._fn = _fn;
  5062. this._successCallback = _successCallback;
  5063. this.index = offset - 1;
  5064. this._done = false;
  5065. }
  5066. /**
  5067. * Execute the next iteration. Must be called after the last iteration was finished.
  5068. */
  5069. AsyncLoop.prototype.executeNext = function () {
  5070. if (!this._done) {
  5071. if (this.index + 1 < this.iterations) {
  5072. ++this.index;
  5073. this._fn(this);
  5074. }
  5075. else {
  5076. this.breakLoop();
  5077. }
  5078. }
  5079. };
  5080. /**
  5081. * Break the loop and run the success callback.
  5082. */
  5083. AsyncLoop.prototype.breakLoop = function () {
  5084. this._done = true;
  5085. this._successCallback();
  5086. };
  5087. /**
  5088. * Helper function
  5089. */
  5090. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5091. if (offset === void 0) { offset = 0; }
  5092. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5093. loop.executeNext();
  5094. return loop;
  5095. };
  5096. /**
  5097. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5098. * @param iterations total number of iterations
  5099. * @param syncedIterations number of synchronous iterations in each async iteration.
  5100. * @param fn the function to call each iteration.
  5101. * @param callback a success call back that will be called when iterating stops.
  5102. * @param breakFunction a break condition (optional)
  5103. * @param timeout timeout settings for the setTimeout function. default - 0.
  5104. * @constructor
  5105. */
  5106. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5107. if (timeout === void 0) { timeout = 0; }
  5108. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5109. if (breakFunction && breakFunction())
  5110. loop.breakLoop();
  5111. else {
  5112. setTimeout(function () {
  5113. for (var i = 0; i < syncedIterations; ++i) {
  5114. var iteration = (loop.index * syncedIterations) + i;
  5115. if (iteration >= iterations)
  5116. break;
  5117. fn(iteration);
  5118. if (breakFunction && breakFunction()) {
  5119. loop.breakLoop();
  5120. break;
  5121. }
  5122. }
  5123. loop.executeNext();
  5124. }, timeout);
  5125. }
  5126. }, callback);
  5127. };
  5128. return AsyncLoop;
  5129. })();
  5130. BABYLON.AsyncLoop = AsyncLoop;
  5131. })(BABYLON || (BABYLON = {}));
  5132. var BABYLON;
  5133. (function (BABYLON) {
  5134. var Internals;
  5135. (function (Internals) {
  5136. var _AlphaState = (function () {
  5137. function _AlphaState() {
  5138. this._isAlphaBlendDirty = false;
  5139. this._isBlendFunctionParametersDirty = false;
  5140. this._alphaBlend = false;
  5141. this._blendFunctionParameters = new Array(4);
  5142. }
  5143. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5144. get: function () {
  5145. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5146. },
  5147. enumerable: true,
  5148. configurable: true
  5149. });
  5150. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5151. get: function () {
  5152. return this._alphaBlend;
  5153. },
  5154. set: function (value) {
  5155. if (this._alphaBlend === value) {
  5156. return;
  5157. }
  5158. this._alphaBlend = value;
  5159. this._isAlphaBlendDirty = true;
  5160. },
  5161. enumerable: true,
  5162. configurable: true
  5163. });
  5164. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5165. if (this._blendFunctionParameters[0] === value0 &&
  5166. this._blendFunctionParameters[1] === value1 &&
  5167. this._blendFunctionParameters[2] === value2 &&
  5168. this._blendFunctionParameters[3] === value3) {
  5169. return;
  5170. }
  5171. this._blendFunctionParameters[0] = value0;
  5172. this._blendFunctionParameters[1] = value1;
  5173. this._blendFunctionParameters[2] = value2;
  5174. this._blendFunctionParameters[3] = value3;
  5175. this._isBlendFunctionParametersDirty = true;
  5176. };
  5177. _AlphaState.prototype.reset = function () {
  5178. this._alphaBlend = false;
  5179. this._blendFunctionParameters[0] = null;
  5180. this._blendFunctionParameters[1] = null;
  5181. this._blendFunctionParameters[2] = null;
  5182. this._blendFunctionParameters[3] = null;
  5183. this._isAlphaBlendDirty = true;
  5184. this._isBlendFunctionParametersDirty = false;
  5185. };
  5186. _AlphaState.prototype.apply = function (gl) {
  5187. if (!this.isDirty) {
  5188. return;
  5189. }
  5190. // Alpha blend
  5191. if (this._isAlphaBlendDirty) {
  5192. if (this._alphaBlend) {
  5193. gl.enable(gl.BLEND);
  5194. }
  5195. else {
  5196. gl.disable(gl.BLEND);
  5197. }
  5198. this._isAlphaBlendDirty = false;
  5199. }
  5200. // Alpha function
  5201. if (this._isBlendFunctionParametersDirty) {
  5202. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5203. this._isBlendFunctionParametersDirty = false;
  5204. }
  5205. };
  5206. return _AlphaState;
  5207. })();
  5208. Internals._AlphaState = _AlphaState;
  5209. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5210. })(BABYLON || (BABYLON = {}));
  5211. var BABYLON;
  5212. (function (BABYLON) {
  5213. var Internals;
  5214. (function (Internals) {
  5215. var _DepthCullingState = (function () {
  5216. function _DepthCullingState() {
  5217. this._isDepthTestDirty = false;
  5218. this._isDepthMaskDirty = false;
  5219. this._isDepthFuncDirty = false;
  5220. this._isCullFaceDirty = false;
  5221. this._isCullDirty = false;
  5222. this._isZOffsetDirty = false;
  5223. }
  5224. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5225. get: function () {
  5226. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5227. },
  5228. enumerable: true,
  5229. configurable: true
  5230. });
  5231. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5232. get: function () {
  5233. return this._zOffset;
  5234. },
  5235. set: function (value) {
  5236. if (this._zOffset === value) {
  5237. return;
  5238. }
  5239. this._zOffset = value;
  5240. this._isZOffsetDirty = true;
  5241. },
  5242. enumerable: true,
  5243. configurable: true
  5244. });
  5245. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5246. get: function () {
  5247. return this._cullFace;
  5248. },
  5249. set: function (value) {
  5250. if (this._cullFace === value) {
  5251. return;
  5252. }
  5253. this._cullFace = value;
  5254. this._isCullFaceDirty = true;
  5255. },
  5256. enumerable: true,
  5257. configurable: true
  5258. });
  5259. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5260. get: function () {
  5261. return this._cull;
  5262. },
  5263. set: function (value) {
  5264. if (this._cull === value) {
  5265. return;
  5266. }
  5267. this._cull = value;
  5268. this._isCullDirty = true;
  5269. },
  5270. enumerable: true,
  5271. configurable: true
  5272. });
  5273. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5274. get: function () {
  5275. return this._depthFunc;
  5276. },
  5277. set: function (value) {
  5278. if (this._depthFunc === value) {
  5279. return;
  5280. }
  5281. this._depthFunc = value;
  5282. this._isDepthFuncDirty = true;
  5283. },
  5284. enumerable: true,
  5285. configurable: true
  5286. });
  5287. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5288. get: function () {
  5289. return this._depthMask;
  5290. },
  5291. set: function (value) {
  5292. if (this._depthMask === value) {
  5293. return;
  5294. }
  5295. this._depthMask = value;
  5296. this._isDepthMaskDirty = true;
  5297. },
  5298. enumerable: true,
  5299. configurable: true
  5300. });
  5301. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5302. get: function () {
  5303. return this._depthTest;
  5304. },
  5305. set: function (value) {
  5306. if (this._depthTest === value) {
  5307. return;
  5308. }
  5309. this._depthTest = value;
  5310. this._isDepthTestDirty = true;
  5311. },
  5312. enumerable: true,
  5313. configurable: true
  5314. });
  5315. _DepthCullingState.prototype.reset = function () {
  5316. this._depthMask = true;
  5317. this._depthTest = true;
  5318. this._depthFunc = null;
  5319. this._cull = null;
  5320. this._cullFace = null;
  5321. this._zOffset = 0;
  5322. this._isDepthTestDirty = true;
  5323. this._isDepthMaskDirty = true;
  5324. this._isDepthFuncDirty = false;
  5325. this._isCullFaceDirty = false;
  5326. this._isCullDirty = false;
  5327. this._isZOffsetDirty = false;
  5328. };
  5329. _DepthCullingState.prototype.apply = function (gl) {
  5330. if (!this.isDirty) {
  5331. return;
  5332. }
  5333. // Cull
  5334. if (this._isCullDirty) {
  5335. if (this.cull) {
  5336. gl.enable(gl.CULL_FACE);
  5337. }
  5338. else {
  5339. gl.disable(gl.CULL_FACE);
  5340. }
  5341. this._isCullDirty = false;
  5342. }
  5343. // Cull face
  5344. if (this._isCullFaceDirty) {
  5345. gl.cullFace(this.cullFace);
  5346. this._isCullFaceDirty = false;
  5347. }
  5348. // Depth mask
  5349. if (this._isDepthMaskDirty) {
  5350. gl.depthMask(this.depthMask);
  5351. this._isDepthMaskDirty = false;
  5352. }
  5353. // Depth test
  5354. if (this._isDepthTestDirty) {
  5355. if (this.depthTest) {
  5356. gl.enable(gl.DEPTH_TEST);
  5357. }
  5358. else {
  5359. gl.disable(gl.DEPTH_TEST);
  5360. }
  5361. this._isDepthTestDirty = false;
  5362. }
  5363. // Depth func
  5364. if (this._isDepthFuncDirty) {
  5365. gl.depthFunc(this.depthFunc);
  5366. this._isDepthFuncDirty = false;
  5367. }
  5368. // zOffset
  5369. if (this._isZOffsetDirty) {
  5370. if (this.zOffset) {
  5371. gl.enable(gl.POLYGON_OFFSET_FILL);
  5372. gl.polygonOffset(this.zOffset, 0);
  5373. }
  5374. else {
  5375. gl.disable(gl.POLYGON_OFFSET_FILL);
  5376. }
  5377. this._isZOffsetDirty = false;
  5378. }
  5379. };
  5380. return _DepthCullingState;
  5381. })();
  5382. Internals._DepthCullingState = _DepthCullingState;
  5383. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5384. })(BABYLON || (BABYLON = {}));
  5385. var BABYLON;
  5386. (function (BABYLON) {
  5387. var compileShader = function (gl, source, type, defines) {
  5388. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5389. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5390. gl.compileShader(shader);
  5391. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5392. throw new Error(gl.getShaderInfoLog(shader));
  5393. }
  5394. return shader;
  5395. };
  5396. var getWebGLTextureType = function (gl, type) {
  5397. var textureType = gl.UNSIGNED_BYTE;
  5398. if (type === Engine.TEXTURETYPE_FLOAT)
  5399. textureType = gl.FLOAT;
  5400. return textureType;
  5401. };
  5402. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5403. var magFilter = gl.NEAREST;
  5404. var minFilter = gl.NEAREST;
  5405. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5406. magFilter = gl.LINEAR;
  5407. if (generateMipMaps) {
  5408. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5409. }
  5410. else {
  5411. minFilter = gl.LINEAR;
  5412. }
  5413. }
  5414. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5415. magFilter = gl.LINEAR;
  5416. if (generateMipMaps) {
  5417. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5418. }
  5419. else {
  5420. minFilter = gl.LINEAR;
  5421. }
  5422. }
  5423. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5424. magFilter = gl.NEAREST;
  5425. if (generateMipMaps) {
  5426. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5427. }
  5428. else {
  5429. minFilter = gl.NEAREST;
  5430. }
  5431. }
  5432. return {
  5433. min: minFilter,
  5434. mag: magFilter
  5435. };
  5436. };
  5437. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5439. var engine = scene.getEngine();
  5440. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5441. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5442. gl.bindTexture(gl.TEXTURE_2D, texture);
  5443. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5444. texture._baseWidth = width;
  5445. texture._baseHeight = height;
  5446. texture._width = potWidth;
  5447. texture._height = potHeight;
  5448. texture.isReady = true;
  5449. processFunction(potWidth, potHeight);
  5450. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5453. if (!noMipmap && !isCompressed) {
  5454. gl.generateMipmap(gl.TEXTURE_2D);
  5455. }
  5456. gl.bindTexture(gl.TEXTURE_2D, null);
  5457. engine.resetTextureCache();
  5458. scene._removePendingData(texture);
  5459. if (onLoad) {
  5460. onLoad();
  5461. }
  5462. };
  5463. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5464. var img;
  5465. var onload = function () {
  5466. loadedImages[index] = img;
  5467. loadedImages._internalCount++;
  5468. scene._removePendingData(img);
  5469. if (loadedImages._internalCount === 6) {
  5470. onfinish(loadedImages);
  5471. }
  5472. };
  5473. var onerror = function () {
  5474. scene._removePendingData(img);
  5475. };
  5476. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5477. scene._addPendingData(img);
  5478. };
  5479. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5480. var loadedImages = [];
  5481. loadedImages._internalCount = 0;
  5482. for (var index = 0; index < 6; index++) {
  5483. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5484. }
  5485. };
  5486. var EngineCapabilities = (function () {
  5487. function EngineCapabilities() {
  5488. }
  5489. return EngineCapabilities;
  5490. })();
  5491. BABYLON.EngineCapabilities = EngineCapabilities;
  5492. /**
  5493. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5494. */
  5495. var Engine = (function () {
  5496. /**
  5497. * @constructor
  5498. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5499. * @param {boolean} [antialias] - enable antialias
  5500. * @param options - further options to be sent to the getContext function
  5501. */
  5502. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5503. var _this = this;
  5504. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5505. // Public members
  5506. this.isFullscreen = false;
  5507. this.isPointerLock = false;
  5508. this.cullBackFaces = true;
  5509. this.renderEvenInBackground = true;
  5510. // To enable/disable IDB support and avoid XHR on .manifest
  5511. this.enableOfflineSupport = true;
  5512. this.scenes = new Array();
  5513. this._windowIsBackground = false;
  5514. this._webGLVersion = "1.0";
  5515. this._drawCalls = 0;
  5516. this._renderingQueueLaunched = false;
  5517. this._activeRenderLoops = [];
  5518. // FPS
  5519. this.fpsRange = 60;
  5520. this.previousFramesDuration = [];
  5521. this.fps = 60;
  5522. this.deltaTime = 0;
  5523. // States
  5524. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5525. this._alphaState = new BABYLON.Internals._AlphaState();
  5526. this._alphaMode = Engine.ALPHA_DISABLE;
  5527. // Cache
  5528. this._loadedTexturesCache = new Array();
  5529. this._maxTextureChannels = 16;
  5530. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5531. this._compiledEffects = {};
  5532. this._uintIndicesCurrentlySet = false;
  5533. this._renderingCanvas = canvas;
  5534. options = options || {};
  5535. options.antialias = antialias;
  5536. if (options.preserveDrawingBuffer === undefined) {
  5537. options.preserveDrawingBuffer = false;
  5538. }
  5539. // GL
  5540. //try {
  5541. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5542. // if (this._gl) {
  5543. // this._webGLVersion = "2.0";
  5544. // }
  5545. //} catch (e) {
  5546. // // Do nothing
  5547. //}
  5548. if (!this._gl) {
  5549. try {
  5550. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5551. }
  5552. catch (e) {
  5553. throw new Error("WebGL not supported");
  5554. }
  5555. }
  5556. if (!this._gl) {
  5557. throw new Error("WebGL not supported");
  5558. }
  5559. this._onBlur = function () {
  5560. _this._windowIsBackground = true;
  5561. };
  5562. this._onFocus = function () {
  5563. _this._windowIsBackground = false;
  5564. };
  5565. window.addEventListener("blur", this._onBlur);
  5566. window.addEventListener("focus", this._onFocus);
  5567. // Viewport
  5568. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5569. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5570. this.resize();
  5571. // Caps
  5572. this._caps = new EngineCapabilities();
  5573. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5574. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5575. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5576. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5577. // Infos
  5578. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5579. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5580. if (rendererInfo != null) {
  5581. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5582. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5583. }
  5584. if (!this._glVendor) {
  5585. this._glVendor = "Unknown vendor";
  5586. }
  5587. if (!this._glRenderer) {
  5588. this._glRenderer = "Unknown renderer";
  5589. }
  5590. // Extensions
  5591. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5592. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5593. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5594. 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');
  5595. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5596. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5597. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5598. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5599. this._caps.highPrecisionShaderSupported = true;
  5600. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5601. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5602. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5603. if (this._gl.getShaderPrecisionFormat) {
  5604. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5605. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5606. }
  5607. // Depth buffer
  5608. this.setDepthBuffer(true);
  5609. this.setDepthFunctionToLessOrEqual();
  5610. this.setDepthWrite(true);
  5611. // Fullscreen
  5612. this._onFullscreenChange = function () {
  5613. if (document.fullscreen !== undefined) {
  5614. _this.isFullscreen = document.fullscreen;
  5615. }
  5616. else if (document.mozFullScreen !== undefined) {
  5617. _this.isFullscreen = document.mozFullScreen;
  5618. }
  5619. else if (document.webkitIsFullScreen !== undefined) {
  5620. _this.isFullscreen = document.webkitIsFullScreen;
  5621. }
  5622. else if (document.msIsFullScreen !== undefined) {
  5623. _this.isFullscreen = document.msIsFullScreen;
  5624. }
  5625. // Pointer lock
  5626. if (_this.isFullscreen && _this._pointerLockRequested) {
  5627. canvas.requestPointerLock = canvas.requestPointerLock ||
  5628. canvas.msRequestPointerLock ||
  5629. canvas.mozRequestPointerLock ||
  5630. canvas.webkitRequestPointerLock;
  5631. if (canvas.requestPointerLock) {
  5632. canvas.requestPointerLock();
  5633. }
  5634. }
  5635. };
  5636. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5637. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5638. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5639. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5640. // Pointer lock
  5641. this._onPointerLockChange = function () {
  5642. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5643. document.webkitPointerLockElement === canvas ||
  5644. document.msPointerLockElement === canvas ||
  5645. document.pointerLockElement === canvas);
  5646. };
  5647. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5648. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5649. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5650. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5651. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5652. Engine.audioEngine = new BABYLON.AudioEngine();
  5653. }
  5654. //default loading screen
  5655. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5656. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5657. }
  5658. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5659. get: function () {
  5660. return Engine._ALPHA_DISABLE;
  5661. },
  5662. enumerable: true,
  5663. configurable: true
  5664. });
  5665. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5666. get: function () {
  5667. return Engine._ALPHA_ONEONE;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. Object.defineProperty(Engine, "ALPHA_ADD", {
  5673. get: function () {
  5674. return Engine._ALPHA_ADD;
  5675. },
  5676. enumerable: true,
  5677. configurable: true
  5678. });
  5679. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5680. get: function () {
  5681. return Engine._ALPHA_COMBINE;
  5682. },
  5683. enumerable: true,
  5684. configurable: true
  5685. });
  5686. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5687. get: function () {
  5688. return Engine._ALPHA_SUBTRACT;
  5689. },
  5690. enumerable: true,
  5691. configurable: true
  5692. });
  5693. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5694. get: function () {
  5695. return Engine._ALPHA_MULTIPLY;
  5696. },
  5697. enumerable: true,
  5698. configurable: true
  5699. });
  5700. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5701. get: function () {
  5702. return Engine._ALPHA_MAXIMIZED;
  5703. },
  5704. enumerable: true,
  5705. configurable: true
  5706. });
  5707. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5708. get: function () {
  5709. return Engine._DELAYLOADSTATE_NONE;
  5710. },
  5711. enumerable: true,
  5712. configurable: true
  5713. });
  5714. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5715. get: function () {
  5716. return Engine._DELAYLOADSTATE_LOADED;
  5717. },
  5718. enumerable: true,
  5719. configurable: true
  5720. });
  5721. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5722. get: function () {
  5723. return Engine._DELAYLOADSTATE_LOADING;
  5724. },
  5725. enumerable: true,
  5726. configurable: true
  5727. });
  5728. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5729. get: function () {
  5730. return Engine._DELAYLOADSTATE_NOTLOADED;
  5731. },
  5732. enumerable: true,
  5733. configurable: true
  5734. });
  5735. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5736. get: function () {
  5737. return Engine._TEXTUREFORMAT_ALPHA;
  5738. },
  5739. enumerable: true,
  5740. configurable: true
  5741. });
  5742. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5743. get: function () {
  5744. return Engine._TEXTUREFORMAT_LUMINANCE;
  5745. },
  5746. enumerable: true,
  5747. configurable: true
  5748. });
  5749. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5750. get: function () {
  5751. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5752. },
  5753. enumerable: true,
  5754. configurable: true
  5755. });
  5756. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5757. get: function () {
  5758. return Engine._TEXTUREFORMAT_RGB;
  5759. },
  5760. enumerable: true,
  5761. configurable: true
  5762. });
  5763. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5764. get: function () {
  5765. return Engine._TEXTUREFORMAT_RGBA;
  5766. },
  5767. enumerable: true,
  5768. configurable: true
  5769. });
  5770. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5771. get: function () {
  5772. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5773. },
  5774. enumerable: true,
  5775. configurable: true
  5776. });
  5777. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5778. get: function () {
  5779. return Engine._TEXTURETYPE_FLOAT;
  5780. },
  5781. enumerable: true,
  5782. configurable: true
  5783. });
  5784. Object.defineProperty(Engine, "Version", {
  5785. get: function () {
  5786. return "2.4.0-alpha";
  5787. },
  5788. enumerable: true,
  5789. configurable: true
  5790. });
  5791. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5792. get: function () {
  5793. return this._webGLVersion;
  5794. },
  5795. enumerable: true,
  5796. configurable: true
  5797. });
  5798. Engine.prototype._prepareWorkingCanvas = function () {
  5799. if (this._workingCanvas) {
  5800. return;
  5801. }
  5802. this._workingCanvas = document.createElement("canvas");
  5803. this._workingContext = this._workingCanvas.getContext("2d");
  5804. };
  5805. Engine.prototype.resetTextureCache = function () {
  5806. for (var index = 0; index < this._maxTextureChannels; index++) {
  5807. this._activeTexturesCache[index] = null;
  5808. }
  5809. };
  5810. Engine.prototype.getGlInfo = function () {
  5811. return {
  5812. vendor: this._glVendor,
  5813. renderer: this._glRenderer,
  5814. version: this._glVersion
  5815. };
  5816. };
  5817. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5818. if (useScreen === void 0) { useScreen = false; }
  5819. var viewport = camera.viewport;
  5820. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5821. };
  5822. Engine.prototype.getRenderWidth = function (useScreen) {
  5823. if (useScreen === void 0) { useScreen = false; }
  5824. if (!useScreen && this._currentRenderTarget) {
  5825. return this._currentRenderTarget._width;
  5826. }
  5827. return this._renderingCanvas.width;
  5828. };
  5829. Engine.prototype.getRenderHeight = function (useScreen) {
  5830. if (useScreen === void 0) { useScreen = false; }
  5831. if (!useScreen && this._currentRenderTarget) {
  5832. return this._currentRenderTarget._height;
  5833. }
  5834. return this._renderingCanvas.height;
  5835. };
  5836. Engine.prototype.getRenderingCanvas = function () {
  5837. return this._renderingCanvas;
  5838. };
  5839. Engine.prototype.getRenderingCanvasClientRect = function () {
  5840. return this._renderingCanvas.getBoundingClientRect();
  5841. };
  5842. Engine.prototype.setHardwareScalingLevel = function (level) {
  5843. this._hardwareScalingLevel = level;
  5844. this.resize();
  5845. };
  5846. Engine.prototype.getHardwareScalingLevel = function () {
  5847. return this._hardwareScalingLevel;
  5848. };
  5849. Engine.prototype.getLoadedTexturesCache = function () {
  5850. return this._loadedTexturesCache;
  5851. };
  5852. Engine.prototype.getCaps = function () {
  5853. return this._caps;
  5854. };
  5855. Object.defineProperty(Engine.prototype, "drawCalls", {
  5856. get: function () {
  5857. return this._drawCalls;
  5858. },
  5859. enumerable: true,
  5860. configurable: true
  5861. });
  5862. // Methods
  5863. Engine.prototype.resetDrawCalls = function () {
  5864. this._drawCalls = 0;
  5865. };
  5866. Engine.prototype.setDepthFunctionToGreater = function () {
  5867. this._depthCullingState.depthFunc = this._gl.GREATER;
  5868. };
  5869. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5870. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5871. };
  5872. Engine.prototype.setDepthFunctionToLess = function () {
  5873. this._depthCullingState.depthFunc = this._gl.LESS;
  5874. };
  5875. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5876. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5877. };
  5878. /**
  5879. * stop executing a render loop function and remove it from the execution array
  5880. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5881. */
  5882. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5883. if (!renderFunction) {
  5884. this._activeRenderLoops = [];
  5885. return;
  5886. }
  5887. var index = this._activeRenderLoops.indexOf(renderFunction);
  5888. if (index >= 0) {
  5889. this._activeRenderLoops.splice(index, 1);
  5890. }
  5891. };
  5892. Engine.prototype._renderLoop = function () {
  5893. var shouldRender = true;
  5894. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5895. shouldRender = false;
  5896. }
  5897. if (shouldRender) {
  5898. // Start new frame
  5899. this.beginFrame();
  5900. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5901. var renderFunction = this._activeRenderLoops[index];
  5902. renderFunction();
  5903. }
  5904. // Present
  5905. this.endFrame();
  5906. }
  5907. if (this._activeRenderLoops.length > 0) {
  5908. // Register new frame
  5909. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5910. }
  5911. else {
  5912. this._renderingQueueLaunched = false;
  5913. }
  5914. };
  5915. /**
  5916. * Register and execute a render loop. The engine can have more than one render function.
  5917. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5918. * @example
  5919. * engine.runRenderLoop(function () {
  5920. * scene.render()
  5921. * })
  5922. */
  5923. Engine.prototype.runRenderLoop = function (renderFunction) {
  5924. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5925. return;
  5926. }
  5927. this._activeRenderLoops.push(renderFunction);
  5928. if (!this._renderingQueueLaunched) {
  5929. this._renderingQueueLaunched = true;
  5930. this._bindedRenderFunction = this._renderLoop.bind(this);
  5931. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5932. }
  5933. };
  5934. /**
  5935. * Toggle full screen mode.
  5936. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5937. */
  5938. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5939. if (this.isFullscreen) {
  5940. BABYLON.Tools.ExitFullscreen();
  5941. }
  5942. else {
  5943. this._pointerLockRequested = requestPointerLock;
  5944. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5945. }
  5946. };
  5947. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5948. this.applyStates();
  5949. if (backBuffer) {
  5950. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5951. }
  5952. if (depthStencil && this._depthCullingState.depthMask) {
  5953. this._gl.clearDepth(1.0);
  5954. }
  5955. var mode = 0;
  5956. if (backBuffer) {
  5957. mode |= this._gl.COLOR_BUFFER_BIT;
  5958. }
  5959. if (depthStencil && this._depthCullingState.depthMask) {
  5960. mode |= this._gl.DEPTH_BUFFER_BIT;
  5961. }
  5962. this._gl.clear(mode);
  5963. };
  5964. /**
  5965. * Set the WebGL's viewport
  5966. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5967. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5968. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5969. */
  5970. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5971. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5972. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5973. var x = viewport.x || 0;
  5974. var y = viewport.y || 0;
  5975. this._cachedViewport = viewport;
  5976. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5977. };
  5978. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5979. this._cachedViewport = null;
  5980. this._gl.viewport(x, y, width, height);
  5981. };
  5982. Engine.prototype.beginFrame = function () {
  5983. this._measureFps();
  5984. };
  5985. Engine.prototype.endFrame = function () {
  5986. //this.flushFramebuffer();
  5987. };
  5988. /**
  5989. * resize the view according to the canvas' size.
  5990. * @example
  5991. * window.addEventListener("resize", function () {
  5992. * engine.resize();
  5993. * });
  5994. */
  5995. Engine.prototype.resize = function () {
  5996. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5997. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5998. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5999. for (var index = 0; index < this.scenes.length; index++) {
  6000. var scene = this.scenes[index];
  6001. if (scene.debugLayer.isVisible()) {
  6002. scene.debugLayer._syncPositions();
  6003. }
  6004. }
  6005. };
  6006. /**
  6007. * force a specific size of the canvas
  6008. * @param {number} width - the new canvas' width
  6009. * @param {number} height - the new canvas' height
  6010. */
  6011. Engine.prototype.setSize = function (width, height) {
  6012. this._renderingCanvas.width = width;
  6013. this._renderingCanvas.height = height;
  6014. for (var index = 0; index < this.scenes.length; index++) {
  6015. var scene = this.scenes[index];
  6016. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6017. var cam = scene.cameras[camIndex];
  6018. cam._currentRenderId = 0;
  6019. }
  6020. }
  6021. };
  6022. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6023. this._currentRenderTarget = texture;
  6024. var gl = this._gl;
  6025. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  6026. if (texture.isCube) {
  6027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6028. }
  6029. else {
  6030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6031. }
  6032. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6033. this.wipeCaches();
  6034. };
  6035. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6036. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6037. this._currentRenderTarget = null;
  6038. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6039. var gl = this._gl;
  6040. gl.bindTexture(gl.TEXTURE_2D, texture);
  6041. gl.generateMipmap(gl.TEXTURE_2D);
  6042. gl.bindTexture(gl.TEXTURE_2D, null);
  6043. }
  6044. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6045. };
  6046. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6047. if (texture.generateMipMaps) {
  6048. var gl = this._gl;
  6049. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6050. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6051. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6052. }
  6053. };
  6054. Engine.prototype.flushFramebuffer = function () {
  6055. this._gl.flush();
  6056. };
  6057. Engine.prototype.restoreDefaultFramebuffer = function () {
  6058. this._currentRenderTarget = null;
  6059. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6060. this.setViewport(this._cachedViewport);
  6061. this.wipeCaches();
  6062. };
  6063. // VBOs
  6064. Engine.prototype._resetVertexBufferBinding = function () {
  6065. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  6066. this._cachedVertexBuffers = null;
  6067. };
  6068. Engine.prototype.createVertexBuffer = function (vertices) {
  6069. var vbo = this._gl.createBuffer();
  6070. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6071. if (vertices instanceof Float32Array) {
  6072. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6073. }
  6074. else {
  6075. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6076. }
  6077. this._resetVertexBufferBinding();
  6078. vbo.references = 1;
  6079. return vbo;
  6080. };
  6081. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6082. var vbo = this._gl.createBuffer();
  6083. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6084. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6085. this._resetVertexBufferBinding();
  6086. vbo.references = 1;
  6087. return vbo;
  6088. };
  6089. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6090. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6091. if (offset === undefined) {
  6092. offset = 0;
  6093. }
  6094. if (vertices instanceof Float32Array) {
  6095. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6096. }
  6097. else {
  6098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6099. }
  6100. this._resetVertexBufferBinding();
  6101. };
  6102. Engine.prototype._resetIndexBufferBinding = function () {
  6103. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6104. this._cachedIndexBuffer = null;
  6105. };
  6106. Engine.prototype.createIndexBuffer = function (indices) {
  6107. var vbo = this._gl.createBuffer();
  6108. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6109. // Check for 32 bits indices
  6110. var arrayBuffer;
  6111. var need32Bits = false;
  6112. if (this._caps.uintIndices) {
  6113. for (var index = 0; index < indices.length; index++) {
  6114. if (indices[index] > 65535) {
  6115. need32Bits = true;
  6116. break;
  6117. }
  6118. }
  6119. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6120. }
  6121. else {
  6122. arrayBuffer = new Uint16Array(indices);
  6123. }
  6124. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6125. this._resetIndexBufferBinding();
  6126. vbo.references = 1;
  6127. vbo.is32Bits = need32Bits;
  6128. return vbo;
  6129. };
  6130. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6131. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6132. this._cachedVertexBuffers = vertexBuffer;
  6133. this._cachedEffectForVertexBuffers = effect;
  6134. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6135. var offset = 0;
  6136. for (var index = 0; index < vertexDeclaration.length; index++) {
  6137. var order = effect.getAttributeLocation(index);
  6138. if (order >= 0) {
  6139. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6140. }
  6141. offset += vertexDeclaration[index] * 4;
  6142. }
  6143. }
  6144. if (this._cachedIndexBuffer !== indexBuffer) {
  6145. this._cachedIndexBuffer = indexBuffer;
  6146. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6147. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6148. }
  6149. };
  6150. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6151. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6152. this._cachedVertexBuffers = vertexBuffers;
  6153. this._cachedEffectForVertexBuffers = effect;
  6154. var attributes = effect.getAttributesNames();
  6155. for (var index = 0; index < attributes.length; index++) {
  6156. var order = effect.getAttributeLocation(index);
  6157. if (order >= 0) {
  6158. var vertexBuffer = vertexBuffers[attributes[index]];
  6159. if (!vertexBuffer) {
  6160. continue;
  6161. }
  6162. var stride = vertexBuffer.getStrideSize();
  6163. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6164. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6165. }
  6166. }
  6167. }
  6168. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6169. this._cachedIndexBuffer = indexBuffer;
  6170. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6171. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6172. }
  6173. };
  6174. Engine.prototype._releaseBuffer = function (buffer) {
  6175. buffer.references--;
  6176. if (buffer.references === 0) {
  6177. this._gl.deleteBuffer(buffer);
  6178. return true;
  6179. }
  6180. return false;
  6181. };
  6182. Engine.prototype.createInstancesBuffer = function (capacity) {
  6183. var buffer = this._gl.createBuffer();
  6184. buffer.capacity = capacity;
  6185. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6186. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6187. return buffer;
  6188. };
  6189. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6190. this._gl.deleteBuffer(buffer);
  6191. };
  6192. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6193. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6194. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6195. for (var index = 0; index < 4; index++) {
  6196. var offsetLocation = offsetLocations[index];
  6197. this._gl.enableVertexAttribArray(offsetLocation);
  6198. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6199. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6200. }
  6201. };
  6202. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6203. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6204. for (var index = 0; index < 4; index++) {
  6205. var offsetLocation = offsetLocations[index];
  6206. this._gl.disableVertexAttribArray(offsetLocation);
  6207. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6208. }
  6209. };
  6210. Engine.prototype.applyStates = function () {
  6211. this._depthCullingState.apply(this._gl);
  6212. this._alphaState.apply(this._gl);
  6213. };
  6214. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6215. // Apply states
  6216. this.applyStates();
  6217. this._drawCalls++;
  6218. // Render
  6219. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6220. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6221. if (instancesCount) {
  6222. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6223. return;
  6224. }
  6225. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6226. };
  6227. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6228. // Apply states
  6229. this.applyStates();
  6230. this._drawCalls++;
  6231. if (instancesCount) {
  6232. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6233. return;
  6234. }
  6235. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6236. };
  6237. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6238. // Apply states
  6239. this.applyStates();
  6240. this._drawCalls++;
  6241. if (instancesCount) {
  6242. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6243. return;
  6244. }
  6245. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6246. };
  6247. // Shaders
  6248. Engine.prototype._releaseEffect = function (effect) {
  6249. if (this._compiledEffects[effect._key]) {
  6250. delete this._compiledEffects[effect._key];
  6251. if (effect.getProgram()) {
  6252. this._gl.deleteProgram(effect.getProgram());
  6253. }
  6254. }
  6255. };
  6256. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6257. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6258. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6259. var name = vertex + "+" + fragment + "@" + defines;
  6260. if (this._compiledEffects[name]) {
  6261. return this._compiledEffects[name];
  6262. }
  6263. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6264. effect._key = name;
  6265. this._compiledEffects[name] = effect;
  6266. return effect;
  6267. };
  6268. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6269. if (uniformsNames === void 0) { uniformsNames = []; }
  6270. if (samplers === void 0) { samplers = []; }
  6271. if (defines === void 0) { defines = ""; }
  6272. return this.createEffect({
  6273. vertex: "particles",
  6274. fragmentElement: fragmentName
  6275. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6276. };
  6277. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6278. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6279. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6280. var shaderProgram = this._gl.createProgram();
  6281. this._gl.attachShader(shaderProgram, vertexShader);
  6282. this._gl.attachShader(shaderProgram, fragmentShader);
  6283. this._gl.linkProgram(shaderProgram);
  6284. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6285. if (!linked) {
  6286. var error = this._gl.getProgramInfoLog(shaderProgram);
  6287. if (error) {
  6288. throw new Error(error);
  6289. }
  6290. }
  6291. this._gl.deleteShader(vertexShader);
  6292. this._gl.deleteShader(fragmentShader);
  6293. return shaderProgram;
  6294. };
  6295. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6296. var results = [];
  6297. for (var index = 0; index < uniformsNames.length; index++) {
  6298. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6299. }
  6300. return results;
  6301. };
  6302. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6303. var results = [];
  6304. for (var index = 0; index < attributesNames.length; index++) {
  6305. try {
  6306. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6307. }
  6308. catch (e) {
  6309. results.push(-1);
  6310. }
  6311. }
  6312. return results;
  6313. };
  6314. Engine.prototype.enableEffect = function (effect) {
  6315. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6316. if (effect && effect.onBind) {
  6317. effect.onBind(effect);
  6318. }
  6319. return;
  6320. }
  6321. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6322. // Use program
  6323. this._gl.useProgram(effect.getProgram());
  6324. for (var i in this._vertexAttribArrays) {
  6325. //make sure this is a number)
  6326. var iAsNumber = +i;
  6327. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6328. continue;
  6329. }
  6330. this._vertexAttribArrays[iAsNumber] = false;
  6331. this._gl.disableVertexAttribArray(iAsNumber);
  6332. }
  6333. var attributesCount = effect.getAttributesCount();
  6334. for (var index = 0; index < attributesCount; index++) {
  6335. // Attributes
  6336. var order = effect.getAttributeLocation(index);
  6337. if (order >= 0) {
  6338. this._vertexAttribArrays[order] = true;
  6339. this._gl.enableVertexAttribArray(order);
  6340. }
  6341. }
  6342. this._currentEffect = effect;
  6343. if (effect.onBind) {
  6344. effect.onBind(effect);
  6345. }
  6346. };
  6347. Engine.prototype.setArray = function (uniform, array) {
  6348. if (!uniform)
  6349. return;
  6350. this._gl.uniform1fv(uniform, array);
  6351. };
  6352. Engine.prototype.setArray2 = function (uniform, array) {
  6353. if (!uniform || array.length % 2 !== 0)
  6354. return;
  6355. this._gl.uniform2fv(uniform, array);
  6356. };
  6357. Engine.prototype.setArray3 = function (uniform, array) {
  6358. if (!uniform || array.length % 3 !== 0)
  6359. return;
  6360. this._gl.uniform3fv(uniform, array);
  6361. };
  6362. Engine.prototype.setArray4 = function (uniform, array) {
  6363. if (!uniform || array.length % 4 !== 0)
  6364. return;
  6365. this._gl.uniform4fv(uniform, array);
  6366. };
  6367. Engine.prototype.setMatrices = function (uniform, matrices) {
  6368. if (!uniform)
  6369. return;
  6370. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6371. };
  6372. Engine.prototype.setMatrix = function (uniform, matrix) {
  6373. if (!uniform)
  6374. return;
  6375. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6376. };
  6377. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6378. if (!uniform)
  6379. return;
  6380. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6381. };
  6382. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6383. if (!uniform)
  6384. return;
  6385. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6386. };
  6387. Engine.prototype.setFloat = function (uniform, value) {
  6388. if (!uniform)
  6389. return;
  6390. this._gl.uniform1f(uniform, value);
  6391. };
  6392. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6393. if (!uniform)
  6394. return;
  6395. this._gl.uniform2f(uniform, x, y);
  6396. };
  6397. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6398. if (!uniform)
  6399. return;
  6400. this._gl.uniform3f(uniform, x, y, z);
  6401. };
  6402. Engine.prototype.setBool = function (uniform, bool) {
  6403. if (!uniform)
  6404. return;
  6405. this._gl.uniform1i(uniform, bool);
  6406. };
  6407. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6408. if (!uniform)
  6409. return;
  6410. this._gl.uniform4f(uniform, x, y, z, w);
  6411. };
  6412. Engine.prototype.setColor3 = function (uniform, color3) {
  6413. if (!uniform)
  6414. return;
  6415. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6416. };
  6417. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6418. if (!uniform)
  6419. return;
  6420. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6421. };
  6422. // States
  6423. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6424. if (zOffset === void 0) { zOffset = 0; }
  6425. if (reverseSide === void 0) { reverseSide = false; }
  6426. // Culling
  6427. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6428. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6429. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6430. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6431. if (culling) {
  6432. this._depthCullingState.cullFace = cullFace;
  6433. this._depthCullingState.cull = true;
  6434. }
  6435. else {
  6436. this._depthCullingState.cull = false;
  6437. }
  6438. }
  6439. // Z offset
  6440. this._depthCullingState.zOffset = zOffset;
  6441. };
  6442. Engine.prototype.setDepthBuffer = function (enable) {
  6443. this._depthCullingState.depthTest = enable;
  6444. };
  6445. Engine.prototype.getDepthWrite = function () {
  6446. return this._depthCullingState.depthMask;
  6447. };
  6448. Engine.prototype.setDepthWrite = function (enable) {
  6449. this._depthCullingState.depthMask = enable;
  6450. };
  6451. Engine.prototype.setColorWrite = function (enable) {
  6452. this._gl.colorMask(enable, enable, enable, enable);
  6453. };
  6454. Engine.prototype.setAlphaMode = function (mode) {
  6455. if (this._alphaMode === mode) {
  6456. return;
  6457. }
  6458. switch (mode) {
  6459. case Engine.ALPHA_DISABLE:
  6460. this.setDepthWrite(true);
  6461. this._alphaState.alphaBlend = false;
  6462. break;
  6463. case Engine.ALPHA_COMBINE:
  6464. this.setDepthWrite(false);
  6465. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6466. this._alphaState.alphaBlend = true;
  6467. break;
  6468. case Engine.ALPHA_ONEONE:
  6469. this.setDepthWrite(false);
  6470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6471. this._alphaState.alphaBlend = true;
  6472. break;
  6473. case Engine.ALPHA_ADD:
  6474. this.setDepthWrite(false);
  6475. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6476. this._alphaState.alphaBlend = true;
  6477. break;
  6478. case Engine.ALPHA_SUBTRACT:
  6479. this.setDepthWrite(false);
  6480. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6481. this._alphaState.alphaBlend = true;
  6482. break;
  6483. case Engine.ALPHA_MULTIPLY:
  6484. this.setDepthWrite(false);
  6485. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6486. this._alphaState.alphaBlend = true;
  6487. break;
  6488. case Engine.ALPHA_MAXIMIZED:
  6489. this.setDepthWrite(false);
  6490. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6491. this._alphaState.alphaBlend = true;
  6492. break;
  6493. }
  6494. this._alphaMode = mode;
  6495. };
  6496. Engine.prototype.getAlphaMode = function () {
  6497. return this._alphaMode;
  6498. };
  6499. Engine.prototype.setAlphaTesting = function (enable) {
  6500. this._alphaTest = enable;
  6501. };
  6502. Engine.prototype.getAlphaTesting = function () {
  6503. return this._alphaTest;
  6504. };
  6505. // Textures
  6506. Engine.prototype.wipeCaches = function () {
  6507. this.resetTextureCache();
  6508. this._currentEffect = null;
  6509. this._depthCullingState.reset();
  6510. this._alphaState.reset();
  6511. this._cachedVertexBuffers = null;
  6512. this._cachedIndexBuffer = null;
  6513. this._cachedEffectForVertexBuffers = null;
  6514. };
  6515. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6516. var gl = this._gl;
  6517. gl.bindTexture(gl.TEXTURE_2D, texture);
  6518. var magFilter = gl.NEAREST;
  6519. var minFilter = gl.NEAREST;
  6520. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6521. magFilter = gl.LINEAR;
  6522. minFilter = gl.LINEAR;
  6523. }
  6524. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6525. magFilter = gl.LINEAR;
  6526. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6527. }
  6528. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6530. gl.bindTexture(gl.TEXTURE_2D, null);
  6531. texture.samplingMode = samplingMode;
  6532. };
  6533. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6534. var _this = this;
  6535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6536. if (onLoad === void 0) { onLoad = null; }
  6537. if (onError === void 0) { onError = null; }
  6538. if (buffer === void 0) { buffer = null; }
  6539. var texture = this._gl.createTexture();
  6540. var extension;
  6541. var fromData = false;
  6542. if (url.substr(0, 5) === "data:") {
  6543. fromData = true;
  6544. }
  6545. if (!fromData)
  6546. extension = url.substr(url.length - 4, 4).toLowerCase();
  6547. else {
  6548. var oldUrl = url;
  6549. fromData = oldUrl.split(':');
  6550. url = oldUrl;
  6551. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6552. }
  6553. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6554. var isTGA = (extension === ".tga");
  6555. scene._addPendingData(texture);
  6556. texture.url = url;
  6557. texture.noMipmap = noMipmap;
  6558. texture.references = 1;
  6559. texture.samplingMode = samplingMode;
  6560. this._loadedTexturesCache.push(texture);
  6561. var onerror = function () {
  6562. scene._removePendingData(texture);
  6563. if (onError) {
  6564. onError();
  6565. }
  6566. };
  6567. var callback;
  6568. if (isTGA) {
  6569. callback = function (arrayBuffer) {
  6570. var data = new Uint8Array(arrayBuffer);
  6571. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6572. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6573. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6574. }, onLoad, samplingMode);
  6575. };
  6576. if (!(fromData instanceof Array))
  6577. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6578. callback(arrayBuffer);
  6579. }, onerror, scene.database, true);
  6580. else
  6581. callback(buffer);
  6582. }
  6583. else if (isDDS) {
  6584. callback = function (data) {
  6585. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6586. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6587. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6588. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6589. }, onLoad, samplingMode);
  6590. };
  6591. if (!(fromData instanceof Array))
  6592. BABYLON.Tools.LoadFile(url, function (data) {
  6593. callback(data);
  6594. }, onerror, scene.database, true);
  6595. else
  6596. callback(buffer);
  6597. }
  6598. else {
  6599. var onload = function (img) {
  6600. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6601. var isPot = (img.width === potWidth && img.height === potHeight);
  6602. if (!isPot) {
  6603. _this._prepareWorkingCanvas();
  6604. _this._workingCanvas.width = potWidth;
  6605. _this._workingCanvas.height = potHeight;
  6606. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6607. _this._workingContext.imageSmoothingEnabled = false;
  6608. _this._workingContext.mozImageSmoothingEnabled = false;
  6609. _this._workingContext.oImageSmoothingEnabled = false;
  6610. _this._workingContext.webkitImageSmoothingEnabled = false;
  6611. _this._workingContext.msImageSmoothingEnabled = false;
  6612. }
  6613. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6614. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6615. _this._workingContext.imageSmoothingEnabled = true;
  6616. _this._workingContext.mozImageSmoothingEnabled = true;
  6617. _this._workingContext.oImageSmoothingEnabled = true;
  6618. _this._workingContext.webkitImageSmoothingEnabled = true;
  6619. _this._workingContext.msImageSmoothingEnabled = true;
  6620. }
  6621. }
  6622. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6623. }, onLoad, samplingMode);
  6624. };
  6625. if (!(fromData instanceof Array))
  6626. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6627. else
  6628. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6629. }
  6630. return texture;
  6631. };
  6632. Engine.prototype._getInternalFormat = function (format) {
  6633. var internalFormat = this._gl.RGBA;
  6634. switch (format) {
  6635. case Engine.TEXTUREFORMAT_ALPHA:
  6636. internalFormat = this._gl.ALPHA;
  6637. break;
  6638. case Engine.TEXTUREFORMAT_LUMINANCE:
  6639. internalFormat = this._gl.LUMINANCE;
  6640. break;
  6641. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6642. internalFormat = this._gl.LUMINANCE_ALPHA;
  6643. break;
  6644. case Engine.TEXTUREFORMAT_RGB:
  6645. internalFormat = this._gl.RGB;
  6646. break;
  6647. case Engine.TEXTUREFORMAT_RGBA:
  6648. internalFormat = this._gl.RGBA;
  6649. break;
  6650. }
  6651. return internalFormat;
  6652. };
  6653. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6654. if (compression === void 0) { compression = null; }
  6655. var internalFormat = this._getInternalFormat(format);
  6656. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6657. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6658. if (compression) {
  6659. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6660. }
  6661. else {
  6662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6663. }
  6664. if (texture.generateMipMaps) {
  6665. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6666. }
  6667. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6668. this.resetTextureCache();
  6669. texture.isReady = true;
  6670. };
  6671. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6672. if (compression === void 0) { compression = null; }
  6673. var texture = this._gl.createTexture();
  6674. texture._baseWidth = width;
  6675. texture._baseHeight = height;
  6676. texture._width = width;
  6677. texture._height = height;
  6678. texture.references = 1;
  6679. this.updateRawTexture(texture, data, format, invertY, compression);
  6680. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6681. // Filters
  6682. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6683. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6684. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6685. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6686. texture.samplingMode = samplingMode;
  6687. this._loadedTexturesCache.push(texture);
  6688. return texture;
  6689. };
  6690. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6691. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6692. var texture = this._gl.createTexture();
  6693. texture._baseWidth = width;
  6694. texture._baseHeight = height;
  6695. if (forceExponantOfTwo) {
  6696. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6697. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6698. }
  6699. this.resetTextureCache();
  6700. texture._width = width;
  6701. texture._height = height;
  6702. texture.isReady = false;
  6703. texture.generateMipMaps = generateMipMaps;
  6704. texture.references = 1;
  6705. texture.samplingMode = samplingMode;
  6706. this.updateTextureSamplingMode(samplingMode, texture);
  6707. this._loadedTexturesCache.push(texture);
  6708. return texture;
  6709. };
  6710. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6711. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6712. if (texture.isCube) {
  6713. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6714. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6715. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6716. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6717. }
  6718. else {
  6719. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6720. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6721. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6722. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6723. }
  6724. };
  6725. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6726. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6727. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6728. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6729. if (texture.generateMipMaps) {
  6730. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6731. }
  6732. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6733. this.resetTextureCache();
  6734. texture.isReady = true;
  6735. };
  6736. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6737. if (texture._isDisabled) {
  6738. return;
  6739. }
  6740. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6741. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6742. try {
  6743. // Testing video texture support
  6744. if (this._videoTextureSupported === undefined) {
  6745. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6746. if (this._gl.getError() !== 0) {
  6747. this._videoTextureSupported = false;
  6748. }
  6749. else {
  6750. this._videoTextureSupported = true;
  6751. }
  6752. }
  6753. // Copy video through the current working canvas if video texture is not supported
  6754. if (!this._videoTextureSupported) {
  6755. if (!texture._workingCanvas) {
  6756. texture._workingCanvas = document.createElement("canvas");
  6757. texture._workingContext = texture._workingCanvas.getContext("2d");
  6758. texture._workingCanvas.width = texture._width;
  6759. texture._workingCanvas.height = texture._height;
  6760. }
  6761. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6762. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6763. }
  6764. else {
  6765. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6766. }
  6767. if (texture.generateMipMaps) {
  6768. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6769. }
  6770. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6771. this.resetTextureCache();
  6772. texture.isReady = true;
  6773. }
  6774. catch (ex) {
  6775. // Something unexpected
  6776. // Let's disable the texture
  6777. texture._isDisabled = true;
  6778. }
  6779. };
  6780. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6781. // old version had a "generateMipMaps" arg instead of options.
  6782. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6783. // in the same way, generateDepthBuffer is defaulted to true
  6784. var generateMipMaps = false;
  6785. var generateDepthBuffer = true;
  6786. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6787. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6788. if (options !== undefined) {
  6789. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6790. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6791. type = options.type === undefined ? type : options.type;
  6792. if (options.samplingMode !== undefined) {
  6793. samplingMode = options.samplingMode;
  6794. }
  6795. if (type === Engine.TEXTURETYPE_FLOAT) {
  6796. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6797. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6798. }
  6799. }
  6800. var gl = this._gl;
  6801. var texture = gl.createTexture();
  6802. gl.bindTexture(gl.TEXTURE_2D, texture);
  6803. var width = size.width || size;
  6804. var height = size.height || size;
  6805. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6806. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6807. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6808. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6809. }
  6810. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6814. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6815. var depthBuffer;
  6816. // Create the depth buffer
  6817. if (generateDepthBuffer) {
  6818. depthBuffer = gl.createRenderbuffer();
  6819. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6820. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6821. }
  6822. // Create the framebuffer
  6823. var framebuffer = gl.createFramebuffer();
  6824. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6825. if (generateDepthBuffer) {
  6826. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6827. }
  6828. if (generateMipMaps) {
  6829. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6830. }
  6831. // Unbind
  6832. gl.bindTexture(gl.TEXTURE_2D, null);
  6833. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6834. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6835. texture._framebuffer = framebuffer;
  6836. if (generateDepthBuffer) {
  6837. texture._depthBuffer = depthBuffer;
  6838. }
  6839. texture._width = width;
  6840. texture._height = height;
  6841. texture.isReady = true;
  6842. texture.generateMipMaps = generateMipMaps;
  6843. texture.references = 1;
  6844. texture.samplingMode = samplingMode;
  6845. this.resetTextureCache();
  6846. this._loadedTexturesCache.push(texture);
  6847. return texture;
  6848. };
  6849. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6850. var gl = this._gl;
  6851. var texture = gl.createTexture();
  6852. var generateMipMaps = true;
  6853. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6854. if (options !== undefined) {
  6855. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6856. if (options.samplingMode !== undefined) {
  6857. samplingMode = options.samplingMode;
  6858. }
  6859. }
  6860. texture.isCube = true;
  6861. texture.references = 1;
  6862. texture.generateMipMaps = generateMipMaps;
  6863. texture.references = 1;
  6864. texture.samplingMode = samplingMode;
  6865. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6866. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6867. for (var face = 0; face < 6; face++) {
  6868. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6869. }
  6870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6874. // Create the depth buffer
  6875. var depthBuffer = gl.createRenderbuffer();
  6876. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6877. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6878. // Create the framebuffer
  6879. var framebuffer = gl.createFramebuffer();
  6880. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6881. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6882. // Mipmaps
  6883. if (texture.generateMipMaps) {
  6884. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6885. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6886. }
  6887. // Unbind
  6888. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6889. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6890. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6891. texture._framebuffer = framebuffer;
  6892. texture._depthBuffer = depthBuffer;
  6893. this.resetTextureCache();
  6894. texture._width = size;
  6895. texture._height = size;
  6896. texture.isReady = true;
  6897. return texture;
  6898. };
  6899. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6900. var _this = this;
  6901. var gl = this._gl;
  6902. var texture = gl.createTexture();
  6903. texture.isCube = true;
  6904. texture.url = rootUrl;
  6905. texture.references = 1;
  6906. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6907. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6908. if (isDDS) {
  6909. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6910. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6911. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6912. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6913. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6914. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6915. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6916. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6917. }
  6918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6922. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6923. _this.resetTextureCache();
  6924. texture._width = info.width;
  6925. texture._height = info.height;
  6926. texture.isReady = true;
  6927. }, null, null, true);
  6928. }
  6929. else {
  6930. cascadeLoad(rootUrl, scene, function (imgs) {
  6931. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6932. var height = width;
  6933. _this._prepareWorkingCanvas();
  6934. _this._workingCanvas.width = width;
  6935. _this._workingCanvas.height = height;
  6936. var faces = [
  6937. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6938. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6939. ];
  6940. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6941. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6942. for (var index = 0; index < faces.length; index++) {
  6943. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6944. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6945. }
  6946. if (!noMipmap) {
  6947. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6948. }
  6949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6953. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6954. _this.resetTextureCache();
  6955. texture._width = width;
  6956. texture._height = height;
  6957. texture.isReady = true;
  6958. }, files);
  6959. }
  6960. return texture;
  6961. };
  6962. Engine.prototype.updateTextureSize = function (texture, width, height) {
  6963. texture._width = width;
  6964. texture._height = height;
  6965. };
  6966. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6967. var _this = this;
  6968. var gl = this._gl;
  6969. var texture = gl.createTexture();
  6970. scene._addPendingData(texture);
  6971. texture.isCube = true;
  6972. texture.references = 1;
  6973. texture.url = url;
  6974. var internalFormat = this._getInternalFormat(format);
  6975. var textureType = gl.UNSIGNED_BYTE;
  6976. if (type === Engine.TEXTURETYPE_FLOAT) {
  6977. textureType = gl.FLOAT;
  6978. }
  6979. var width = size;
  6980. var height = width;
  6981. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6982. texture._width = width;
  6983. texture._height = height;
  6984. var onerror = function () {
  6985. scene._removePendingData(texture);
  6986. };
  6987. var internalCallback = function (data) {
  6988. var rgbeDataArrays = callback(data);
  6989. var facesIndex = [
  6990. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6991. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6992. ];
  6993. width = texture._width;
  6994. height = texture._height;
  6995. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6996. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6997. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6998. if (!noMipmap && isPot) {
  6999. if (mipmmapGenerator) {
  7000. var arrayTemp = [];
  7001. // Data are known to be in +X +Y +Z -X -Y -Z
  7002. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7003. arrayTemp.push(rgbeDataArrays[0]); // +X
  7004. arrayTemp.push(rgbeDataArrays[3]); // -X
  7005. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7006. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7007. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7008. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7009. var mipData = mipmmapGenerator(arrayTemp);
  7010. for (var level = 0; level < mipData.length; level++) {
  7011. var mipSize = width >> level;
  7012. // mipData is order in +X -X +Y -Y +Z -Z
  7013. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7014. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7015. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7016. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7017. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7018. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7019. }
  7020. }
  7021. else {
  7022. // Data are known to be in +X +Y +Z -X -Y -Z
  7023. for (var index = 0; index < facesIndex.length; index++) {
  7024. var faceData = rgbeDataArrays[index];
  7025. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7026. }
  7027. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7028. }
  7029. }
  7030. else {
  7031. noMipmap = true;
  7032. }
  7033. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7034. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7036. }
  7037. else {
  7038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7039. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7040. }
  7041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7043. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7044. texture.isReady = true;
  7045. _this.resetTextureCache();
  7046. scene._removePendingData(texture);
  7047. };
  7048. BABYLON.Tools.LoadFile(url, function (data) {
  7049. internalCallback(data);
  7050. }, onerror, scene.database, true);
  7051. return texture;
  7052. };
  7053. ;
  7054. Engine.prototype._releaseTexture = function (texture) {
  7055. var gl = this._gl;
  7056. if (texture._framebuffer) {
  7057. gl.deleteFramebuffer(texture._framebuffer);
  7058. }
  7059. if (texture._depthBuffer) {
  7060. gl.deleteRenderbuffer(texture._depthBuffer);
  7061. }
  7062. gl.deleteTexture(texture);
  7063. // Unbind channels
  7064. this.unbindAllTextures();
  7065. var index = this._loadedTexturesCache.indexOf(texture);
  7066. if (index !== -1) {
  7067. this._loadedTexturesCache.splice(index, 1);
  7068. }
  7069. };
  7070. Engine.prototype.bindSamplers = function (effect) {
  7071. this._gl.useProgram(effect.getProgram());
  7072. var samplers = effect.getSamplers();
  7073. for (var index = 0; index < samplers.length; index++) {
  7074. var uniform = effect.getUniform(samplers[index]);
  7075. this._gl.uniform1i(uniform, index);
  7076. }
  7077. this._currentEffect = null;
  7078. };
  7079. Engine.prototype._bindTexture = function (channel, texture) {
  7080. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7081. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7082. this._activeTexturesCache[channel] = null;
  7083. };
  7084. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7085. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7086. };
  7087. Engine.prototype.unbindAllTextures = function () {
  7088. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7089. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7090. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7091. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7092. this._activeTexturesCache[channel] = null;
  7093. }
  7094. };
  7095. Engine.prototype.setTexture = function (channel, texture) {
  7096. if (channel < 0) {
  7097. return;
  7098. }
  7099. // Not ready?
  7100. if (!texture || !texture.isReady()) {
  7101. if (this._activeTexturesCache[channel] != null) {
  7102. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7103. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7104. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7105. this._activeTexturesCache[channel] = null;
  7106. }
  7107. return;
  7108. }
  7109. // Video
  7110. var alreadyActivated = false;
  7111. if (texture instanceof BABYLON.VideoTexture) {
  7112. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7113. alreadyActivated = true;
  7114. texture.update();
  7115. }
  7116. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7117. texture.delayLoad();
  7118. return;
  7119. }
  7120. if (this._activeTexturesCache[channel] === texture) {
  7121. return;
  7122. }
  7123. this._activeTexturesCache[channel] = texture;
  7124. var internalTexture = texture.getInternalTexture();
  7125. if (!alreadyActivated) {
  7126. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7127. }
  7128. if (internalTexture.isCube) {
  7129. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7130. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7131. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7132. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7133. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7134. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7135. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7136. }
  7137. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7138. }
  7139. else {
  7140. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7141. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7142. internalTexture._cachedWrapU = texture.wrapU;
  7143. switch (texture.wrapU) {
  7144. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7145. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7146. break;
  7147. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7148. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7149. break;
  7150. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7151. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7152. break;
  7153. }
  7154. }
  7155. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7156. internalTexture._cachedWrapV = texture.wrapV;
  7157. switch (texture.wrapV) {
  7158. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7159. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7160. break;
  7161. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7162. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7163. break;
  7164. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7165. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7166. break;
  7167. }
  7168. }
  7169. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7170. }
  7171. };
  7172. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7173. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7174. var value = texture.anisotropicFilteringLevel;
  7175. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7176. value = 1;
  7177. }
  7178. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7179. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7180. texture._cachedAnisotropicFilteringLevel = value;
  7181. }
  7182. };
  7183. Engine.prototype.readPixels = function (x, y, width, height) {
  7184. var data = new Uint8Array(height * width * 4);
  7185. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7186. return data;
  7187. };
  7188. Engine.prototype.releaseInternalTexture = function (texture) {
  7189. if (!texture) {
  7190. return;
  7191. }
  7192. texture.references--;
  7193. // Final reference ?
  7194. if (texture.references === 0) {
  7195. var texturesCache = this.getLoadedTexturesCache();
  7196. var index = texturesCache.indexOf(texture);
  7197. if (index > -1) {
  7198. texturesCache.splice(index, 1);
  7199. }
  7200. this._releaseTexture(texture);
  7201. }
  7202. };
  7203. // Dispose
  7204. Engine.prototype.dispose = function () {
  7205. this.hideLoadingUI();
  7206. this.stopRenderLoop();
  7207. // Release scenes
  7208. while (this.scenes.length) {
  7209. this.scenes[0].dispose();
  7210. }
  7211. // Release audio engine
  7212. Engine.audioEngine.dispose();
  7213. // Release effects
  7214. for (var name in this._compiledEffects) {
  7215. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7216. }
  7217. // Unbind
  7218. for (var i in this._vertexAttribArrays) {
  7219. //making sure this is a string
  7220. var iAsNumber = +i;
  7221. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7222. continue;
  7223. }
  7224. this._gl.disableVertexAttribArray(iAsNumber);
  7225. }
  7226. this._gl = null;
  7227. // Events
  7228. window.removeEventListener("blur", this._onBlur);
  7229. window.removeEventListener("focus", this._onFocus);
  7230. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7231. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7232. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7233. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7234. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7235. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7236. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7237. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7238. };
  7239. // Loading screen
  7240. Engine.prototype.displayLoadingUI = function () {
  7241. this._loadingScreen.displayLoadingUI();
  7242. };
  7243. Engine.prototype.hideLoadingUI = function () {
  7244. this._loadingScreen.hideLoadingUI();
  7245. };
  7246. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7247. get: function () {
  7248. return this._loadingScreen;
  7249. },
  7250. set: function (loadingScreen) {
  7251. this._loadingScreen = loadingScreen;
  7252. },
  7253. enumerable: true,
  7254. configurable: true
  7255. });
  7256. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7257. set: function (text) {
  7258. this._loadingScreen.loadingUIText = text;
  7259. },
  7260. enumerable: true,
  7261. configurable: true
  7262. });
  7263. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7264. set: function (color) {
  7265. this._loadingScreen.loadingUIBackgroundColor = color;
  7266. },
  7267. enumerable: true,
  7268. configurable: true
  7269. });
  7270. // FPS
  7271. Engine.prototype.getFps = function () {
  7272. return this.fps;
  7273. };
  7274. Engine.prototype.getDeltaTime = function () {
  7275. return this.deltaTime;
  7276. };
  7277. Engine.prototype._measureFps = function () {
  7278. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7279. var length = this.previousFramesDuration.length;
  7280. if (length >= 2) {
  7281. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7282. }
  7283. if (length >= this.fpsRange) {
  7284. if (length > this.fpsRange) {
  7285. this.previousFramesDuration.splice(0, 1);
  7286. length = this.previousFramesDuration.length;
  7287. }
  7288. var sum = 0;
  7289. for (var id = 0; id < length - 1; id++) {
  7290. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7291. }
  7292. this.fps = 1000.0 / (sum / (length - 1));
  7293. }
  7294. };
  7295. // Statics
  7296. Engine.isSupported = function () {
  7297. try {
  7298. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7299. if (navigator.isCocoonJS) {
  7300. return true;
  7301. }
  7302. var tempcanvas = document.createElement("canvas");
  7303. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7304. return gl != null && !!window.WebGLRenderingContext;
  7305. }
  7306. catch (e) {
  7307. return false;
  7308. }
  7309. };
  7310. // Const statics
  7311. Engine._ALPHA_DISABLE = 0;
  7312. Engine._ALPHA_ADD = 1;
  7313. Engine._ALPHA_COMBINE = 2;
  7314. Engine._ALPHA_SUBTRACT = 3;
  7315. Engine._ALPHA_MULTIPLY = 4;
  7316. Engine._ALPHA_MAXIMIZED = 5;
  7317. Engine._ALPHA_ONEONE = 6;
  7318. Engine._DELAYLOADSTATE_NONE = 0;
  7319. Engine._DELAYLOADSTATE_LOADED = 1;
  7320. Engine._DELAYLOADSTATE_LOADING = 2;
  7321. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7322. Engine._TEXTUREFORMAT_ALPHA = 0;
  7323. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7324. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7325. Engine._TEXTUREFORMAT_RGB = 4;
  7326. Engine._TEXTUREFORMAT_RGBA = 5;
  7327. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7328. Engine._TEXTURETYPE_FLOAT = 1;
  7329. // Updatable statics so stick with vars here
  7330. Engine.CollisionsEpsilon = 0.001;
  7331. Engine.CodeRepository = "src/";
  7332. Engine.ShadersRepository = "src/Shaders/";
  7333. return Engine;
  7334. })();
  7335. BABYLON.Engine = Engine;
  7336. })(BABYLON || (BABYLON = {}));
  7337. var BABYLON;
  7338. (function (BABYLON) {
  7339. /**
  7340. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7341. */
  7342. var Node = (function () {
  7343. /**
  7344. * @constructor
  7345. * @param {string} name - the name and id to be given to this node
  7346. * @param {BABYLON.Scene} the scene this node will be added to
  7347. */
  7348. function Node(name, scene) {
  7349. this.state = "";
  7350. this.animations = new Array();
  7351. this._ranges = {};
  7352. this._childrenFlag = -1;
  7353. this._isEnabled = true;
  7354. this._isReady = true;
  7355. this._currentRenderId = -1;
  7356. this._parentRenderId = -1;
  7357. this.name = name;
  7358. this.id = name;
  7359. this._scene = scene;
  7360. this._initCache();
  7361. }
  7362. Object.defineProperty(Node.prototype, "parent", {
  7363. get: function () {
  7364. return this._parentNode;
  7365. },
  7366. set: function (parent) {
  7367. if (this._parentNode === parent) {
  7368. return;
  7369. }
  7370. if (this._parentNode) {
  7371. var index = this._parentNode._children.indexOf(this);
  7372. if (index !== -1) {
  7373. this._parentNode._children.splice(index, 1);
  7374. }
  7375. }
  7376. this._parentNode = parent;
  7377. if (this._parentNode) {
  7378. if (!this._parentNode._children) {
  7379. this._parentNode._children = new Array();
  7380. }
  7381. this._parentNode._children.push(this);
  7382. }
  7383. },
  7384. enumerable: true,
  7385. configurable: true
  7386. });
  7387. Node.prototype.getScene = function () {
  7388. return this._scene;
  7389. };
  7390. Node.prototype.getEngine = function () {
  7391. return this._scene.getEngine();
  7392. };
  7393. // override it in derived class
  7394. Node.prototype.getWorldMatrix = function () {
  7395. return BABYLON.Matrix.Identity();
  7396. };
  7397. // override it in derived class if you add new variables to the cache
  7398. // and call the parent class method
  7399. Node.prototype._initCache = function () {
  7400. this._cache = {};
  7401. this._cache.parent = undefined;
  7402. };
  7403. Node.prototype.updateCache = function (force) {
  7404. if (!force && this.isSynchronized())
  7405. return;
  7406. this._cache.parent = this.parent;
  7407. this._updateCache();
  7408. };
  7409. // override it in derived class if you add new variables to the cache
  7410. // and call the parent class method if !ignoreParentClass
  7411. Node.prototype._updateCache = function (ignoreParentClass) {
  7412. };
  7413. // override it in derived class if you add new variables to the cache
  7414. Node.prototype._isSynchronized = function () {
  7415. return true;
  7416. };
  7417. Node.prototype._markSyncedWithParent = function () {
  7418. this._parentRenderId = this.parent._currentRenderId;
  7419. };
  7420. Node.prototype.isSynchronizedWithParent = function () {
  7421. if (!this.parent) {
  7422. return true;
  7423. }
  7424. if (this._parentRenderId !== this.parent._currentRenderId) {
  7425. return false;
  7426. }
  7427. return this.parent.isSynchronized();
  7428. };
  7429. Node.prototype.isSynchronized = function (updateCache) {
  7430. var check = this.hasNewParent();
  7431. check = check || !this.isSynchronizedWithParent();
  7432. check = check || !this._isSynchronized();
  7433. if (updateCache)
  7434. this.updateCache(true);
  7435. return !check;
  7436. };
  7437. Node.prototype.hasNewParent = function (update) {
  7438. if (this._cache.parent === this.parent)
  7439. return false;
  7440. if (update)
  7441. this._cache.parent = this.parent;
  7442. return true;
  7443. };
  7444. /**
  7445. * Is this node ready to be used/rendered
  7446. * @return {boolean} is it ready
  7447. */
  7448. Node.prototype.isReady = function () {
  7449. return this._isReady;
  7450. };
  7451. /**
  7452. * Is this node enabled.
  7453. * If the node has a parent and is enabled, the parent will be inspected as well.
  7454. * @return {boolean} whether this node (and its parent) is enabled.
  7455. * @see setEnabled
  7456. */
  7457. Node.prototype.isEnabled = function () {
  7458. if (!this._isEnabled) {
  7459. return false;
  7460. }
  7461. if (this.parent) {
  7462. return this.parent.isEnabled();
  7463. }
  7464. return true;
  7465. };
  7466. /**
  7467. * Set the enabled state of this node.
  7468. * @param {boolean} value - the new enabled state
  7469. * @see isEnabled
  7470. */
  7471. Node.prototype.setEnabled = function (value) {
  7472. this._isEnabled = value;
  7473. };
  7474. /**
  7475. * Is this node a descendant of the given node.
  7476. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7477. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7478. * @see parent
  7479. */
  7480. Node.prototype.isDescendantOf = function (ancestor) {
  7481. if (this.parent) {
  7482. if (this.parent === ancestor) {
  7483. return true;
  7484. }
  7485. return this.parent.isDescendantOf(ancestor);
  7486. }
  7487. return false;
  7488. };
  7489. /**
  7490. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7491. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7492. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7493. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7494. */
  7495. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7496. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7497. if (!this._children) {
  7498. return;
  7499. }
  7500. for (var index = 0; index < this._children.length; index++) {
  7501. var item = this._children[index];
  7502. if (!predicate || predicate(item)) {
  7503. results.push(item);
  7504. }
  7505. if (!directDescendantsOnly) {
  7506. item._getDescendants(results, false, predicate);
  7507. }
  7508. }
  7509. };
  7510. /**
  7511. * Will return all nodes that have this node as ascendant.
  7512. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7513. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7514. * @return {BABYLON.Node[]} all children nodes of all types.
  7515. */
  7516. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7517. var results = [];
  7518. this._getDescendants(results, directDescendantsOnly, predicate);
  7519. return results;
  7520. };
  7521. /**
  7522. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7523. * @Deprecated, legacy support.
  7524. * use getDecendants instead.
  7525. */
  7526. Node.prototype.getChildren = function (predicate) {
  7527. return this.getDescendants(true, predicate);
  7528. };
  7529. /**
  7530. * Get all child-meshes of this node.
  7531. */
  7532. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7533. var results = [];
  7534. this._getDescendants(results, directDecendantsOnly, function (node) {
  7535. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7536. });
  7537. return results;
  7538. };
  7539. Node.prototype._setReady = function (state) {
  7540. if (state === this._isReady) {
  7541. return;
  7542. }
  7543. if (!state) {
  7544. this._isReady = false;
  7545. return;
  7546. }
  7547. this._isReady = true;
  7548. if (this.onReady) {
  7549. this.onReady(this);
  7550. }
  7551. };
  7552. Node.prototype.getAnimationByName = function (name) {
  7553. for (var i = 0; i < this.animations.length; i++) {
  7554. var animation = this.animations[i];
  7555. if (animation.name === name) {
  7556. return animation;
  7557. }
  7558. }
  7559. return null;
  7560. };
  7561. Node.prototype.createAnimationRange = function (name, from, to) {
  7562. // check name not already in use
  7563. if (!this._ranges[name]) {
  7564. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7565. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7566. if (this.animations[i]) {
  7567. this.animations[i].createRange(name, from, to);
  7568. }
  7569. }
  7570. }
  7571. };
  7572. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7573. if (deleteFrames === void 0) { deleteFrames = true; }
  7574. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7575. if (this.animations[i]) {
  7576. this.animations[i].deleteRange(name, deleteFrames);
  7577. }
  7578. }
  7579. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7580. };
  7581. Node.prototype.getAnimationRange = function (name) {
  7582. return this._ranges[name];
  7583. };
  7584. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7585. var range = this.getAnimationRange(name);
  7586. if (!range) {
  7587. return null;
  7588. }
  7589. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7590. };
  7591. Node.prototype.serializeAnimationRanges = function () {
  7592. var serializationRanges = [];
  7593. for (var name in this._ranges) {
  7594. var range = {};
  7595. range.name = name;
  7596. range.from = this._ranges[name].from;
  7597. range.to = this._ranges[name].to;
  7598. serializationRanges.push(range);
  7599. }
  7600. return serializationRanges;
  7601. };
  7602. Node.prototype.dispose = function () {
  7603. this.parent = null;
  7604. };
  7605. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7606. if (parsedNode.ranges) {
  7607. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7608. var data = parsedNode.ranges[index];
  7609. node.createAnimationRange(data.name, data.from, data.to);
  7610. }
  7611. }
  7612. };
  7613. __decorate([
  7614. BABYLON.serialize()
  7615. ], Node.prototype, "name", void 0);
  7616. __decorate([
  7617. BABYLON.serialize()
  7618. ], Node.prototype, "id", void 0);
  7619. __decorate([
  7620. BABYLON.serialize()
  7621. ], Node.prototype, "uniqueId", void 0);
  7622. __decorate([
  7623. BABYLON.serialize()
  7624. ], Node.prototype, "state", void 0);
  7625. return Node;
  7626. })();
  7627. BABYLON.Node = Node;
  7628. })(BABYLON || (BABYLON = {}));
  7629. var BABYLON;
  7630. (function (BABYLON) {
  7631. var FilesInput = (function () {
  7632. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7633. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7634. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7635. this._engine = p_engine;
  7636. this._canvas = p_canvas;
  7637. this._currentScene = p_scene;
  7638. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7639. this._progressCallback = p_progressCallback;
  7640. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7641. this._textureLoadingCallback = p_textureLoadingCallback;
  7642. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7643. }
  7644. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7645. var _this = this;
  7646. if (p_elementToMonitor) {
  7647. this._elementToMonitor = p_elementToMonitor;
  7648. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7649. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7650. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7651. }
  7652. };
  7653. FilesInput.prototype.renderFunction = function () {
  7654. if (this._additionnalRenderLoopLogicCallback) {
  7655. this._additionnalRenderLoopLogicCallback();
  7656. }
  7657. if (this._currentScene) {
  7658. if (this._textureLoadingCallback) {
  7659. var remaining = this._currentScene.getWaitingItemsCount();
  7660. if (remaining > 0) {
  7661. this._textureLoadingCallback(remaining);
  7662. }
  7663. }
  7664. this._currentScene.render();
  7665. }
  7666. };
  7667. FilesInput.prototype.drag = function (e) {
  7668. e.stopPropagation();
  7669. e.preventDefault();
  7670. };
  7671. FilesInput.prototype.drop = function (eventDrop) {
  7672. eventDrop.stopPropagation();
  7673. eventDrop.preventDefault();
  7674. this.loadFiles(eventDrop);
  7675. };
  7676. FilesInput.prototype.loadFiles = function (event) {
  7677. if (this._startingProcessingFilesCallback)
  7678. this._startingProcessingFilesCallback();
  7679. // Handling data transfer via drag'n'drop
  7680. if (event && event.dataTransfer && event.dataTransfer.files) {
  7681. this._filesToLoad = event.dataTransfer.files;
  7682. }
  7683. // Handling files from input files
  7684. if (event && event.target && event.target.files) {
  7685. this._filesToLoad = event.target.files;
  7686. }
  7687. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7688. for (var i = 0; i < this._filesToLoad.length; i++) {
  7689. switch (this._filesToLoad[i].type) {
  7690. case "image/jpeg":
  7691. case "image/png":
  7692. case "image/bmp":
  7693. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7694. break;
  7695. case "image/targa":
  7696. case "image/vnd.ms-dds":
  7697. case "audio/wav":
  7698. case "audio/x-wav":
  7699. case "audio/mp3":
  7700. case "audio/mpeg":
  7701. case "audio/mpeg3":
  7702. case "audio/x-mpeg-3":
  7703. case "audio/ogg":
  7704. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7705. break;
  7706. default:
  7707. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7708. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7709. }
  7710. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7711. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7712. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7713. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7714. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7715. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7716. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7717. this._sceneFileToLoad = this._filesToLoad[i];
  7718. }
  7719. break;
  7720. }
  7721. }
  7722. this.reload();
  7723. }
  7724. };
  7725. FilesInput.prototype.reload = function () {
  7726. var _this = this;
  7727. var that = this;
  7728. // If a ".babylon" file has been provided
  7729. if (this._sceneFileToLoad) {
  7730. if (this._currentScene) {
  7731. if (BABYLON.Tools.errorsCount > 0) {
  7732. BABYLON.Tools.ClearLogCache();
  7733. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7734. }
  7735. this._engine.stopRenderLoop();
  7736. this._currentScene.dispose();
  7737. }
  7738. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7739. that._currentScene = newScene;
  7740. // Wait for textures and shaders to be ready
  7741. that._currentScene.executeWhenReady(function () {
  7742. // Attach camera to canvas inputs
  7743. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7744. that._currentScene.createDefaultCameraOrLight();
  7745. }
  7746. that._currentScene.activeCamera.attachControl(that._canvas);
  7747. if (that._sceneLoadedCallback) {
  7748. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7749. }
  7750. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7751. });
  7752. }, function (progress) {
  7753. if (_this._progressCallback) {
  7754. _this._progressCallback(progress);
  7755. }
  7756. });
  7757. }
  7758. else {
  7759. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7760. }
  7761. };
  7762. FilesInput.FilesTextures = new Array();
  7763. FilesInput.FilesToLoad = new Array();
  7764. return FilesInput;
  7765. })();
  7766. BABYLON.FilesInput = FilesInput;
  7767. })(BABYLON || (BABYLON = {}));
  7768. var BABYLON;
  7769. (function (BABYLON) {
  7770. var IntersectionInfo = (function () {
  7771. function IntersectionInfo(bu, bv, distance) {
  7772. this.bu = bu;
  7773. this.bv = bv;
  7774. this.distance = distance;
  7775. this.faceId = 0;
  7776. this.subMeshId = 0;
  7777. }
  7778. return IntersectionInfo;
  7779. })();
  7780. BABYLON.IntersectionInfo = IntersectionInfo;
  7781. var PickingInfo = (function () {
  7782. function PickingInfo() {
  7783. this.hit = false;
  7784. this.distance = 0;
  7785. this.pickedPoint = null;
  7786. this.pickedMesh = null;
  7787. this.bu = 0;
  7788. this.bv = 0;
  7789. this.faceId = -1;
  7790. this.subMeshId = 0;
  7791. this.pickedSprite = null;
  7792. }
  7793. // Methods
  7794. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7795. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7796. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7797. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7798. return null;
  7799. }
  7800. var indices = this.pickedMesh.getIndices();
  7801. var result;
  7802. if (useVerticesNormals) {
  7803. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7804. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7805. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7806. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7807. normal0 = normal0.scale(this.bu);
  7808. normal1 = normal1.scale(this.bv);
  7809. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7810. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7811. }
  7812. else {
  7813. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7814. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7815. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7816. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7817. var p1p2 = vertex1.subtract(vertex2);
  7818. var p3p2 = vertex3.subtract(vertex2);
  7819. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7820. }
  7821. if (useWorldCoordinates) {
  7822. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7823. }
  7824. return BABYLON.Vector3.Normalize(result);
  7825. };
  7826. PickingInfo.prototype.getTextureCoordinates = function () {
  7827. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7828. return null;
  7829. }
  7830. var indices = this.pickedMesh.getIndices();
  7831. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7832. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7833. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7834. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7835. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7836. uv1 = uv1.scale(this.bu);
  7837. uv2 = uv2.scale(this.bv);
  7838. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7839. };
  7840. return PickingInfo;
  7841. })();
  7842. BABYLON.PickingInfo = PickingInfo;
  7843. })(BABYLON || (BABYLON = {}));
  7844. var BABYLON;
  7845. (function (BABYLON) {
  7846. var BoundingSphere = (function () {
  7847. function BoundingSphere(minimum, maximum) {
  7848. this.minimum = minimum;
  7849. this.maximum = maximum;
  7850. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7851. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7852. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7853. this.radius = distance * 0.5;
  7854. this.centerWorld = BABYLON.Vector3.Zero();
  7855. this._update(BABYLON.Matrix.Identity());
  7856. }
  7857. // Methods
  7858. BoundingSphere.prototype._update = function (world) {
  7859. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7860. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7861. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7862. };
  7863. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7864. for (var i = 0; i < 6; i++) {
  7865. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7866. return false;
  7867. }
  7868. return true;
  7869. };
  7870. BoundingSphere.prototype.intersectsPoint = function (point) {
  7871. var x = this.centerWorld.x - point.x;
  7872. var y = this.centerWorld.y - point.y;
  7873. var z = this.centerWorld.z - point.z;
  7874. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7875. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7876. return false;
  7877. return true;
  7878. };
  7879. // Statics
  7880. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7881. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7882. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7883. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7884. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7885. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7886. return false;
  7887. return true;
  7888. };
  7889. return BoundingSphere;
  7890. })();
  7891. BABYLON.BoundingSphere = BoundingSphere;
  7892. })(BABYLON || (BABYLON = {}));
  7893. var BABYLON;
  7894. (function (BABYLON) {
  7895. var BoundingBox = (function () {
  7896. function BoundingBox(minimum, maximum) {
  7897. this.minimum = minimum;
  7898. this.maximum = maximum;
  7899. this.vectors = new Array();
  7900. this.vectorsWorld = new Array();
  7901. // Bounding vectors
  7902. this.vectors.push(this.minimum.clone());
  7903. this.vectors.push(this.maximum.clone());
  7904. this.vectors.push(this.minimum.clone());
  7905. this.vectors[2].x = this.maximum.x;
  7906. this.vectors.push(this.minimum.clone());
  7907. this.vectors[3].y = this.maximum.y;
  7908. this.vectors.push(this.minimum.clone());
  7909. this.vectors[4].z = this.maximum.z;
  7910. this.vectors.push(this.maximum.clone());
  7911. this.vectors[5].z = this.minimum.z;
  7912. this.vectors.push(this.maximum.clone());
  7913. this.vectors[6].x = this.minimum.x;
  7914. this.vectors.push(this.maximum.clone());
  7915. this.vectors[7].y = this.minimum.y;
  7916. // OBB
  7917. this.center = this.maximum.add(this.minimum).scale(0.5);
  7918. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7919. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7920. // World
  7921. for (var index = 0; index < this.vectors.length; index++) {
  7922. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7923. }
  7924. this.minimumWorld = BABYLON.Vector3.Zero();
  7925. this.maximumWorld = BABYLON.Vector3.Zero();
  7926. this._update(BABYLON.Matrix.Identity());
  7927. }
  7928. // Methods
  7929. BoundingBox.prototype.getWorldMatrix = function () {
  7930. return this._worldMatrix;
  7931. };
  7932. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7933. this._worldMatrix.copyFrom(matrix);
  7934. return this;
  7935. };
  7936. BoundingBox.prototype._update = function (world) {
  7937. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7938. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7939. for (var index = 0; index < this.vectors.length; index++) {
  7940. var v = this.vectorsWorld[index];
  7941. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7942. if (v.x < this.minimumWorld.x)
  7943. this.minimumWorld.x = v.x;
  7944. if (v.y < this.minimumWorld.y)
  7945. this.minimumWorld.y = v.y;
  7946. if (v.z < this.minimumWorld.z)
  7947. this.minimumWorld.z = v.z;
  7948. if (v.x > this.maximumWorld.x)
  7949. this.maximumWorld.x = v.x;
  7950. if (v.y > this.maximumWorld.y)
  7951. this.maximumWorld.y = v.y;
  7952. if (v.z > this.maximumWorld.z)
  7953. this.maximumWorld.z = v.z;
  7954. }
  7955. // OBB
  7956. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7957. this.center.scaleInPlace(0.5);
  7958. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7959. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7960. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7961. this._worldMatrix = world;
  7962. };
  7963. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7964. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7965. };
  7966. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7967. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7968. };
  7969. BoundingBox.prototype.intersectsPoint = function (point) {
  7970. var delta = -BABYLON.Epsilon;
  7971. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7972. return false;
  7973. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7974. return false;
  7975. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7976. return false;
  7977. return true;
  7978. };
  7979. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7980. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7981. };
  7982. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7983. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7984. return false;
  7985. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7986. return false;
  7987. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7988. return false;
  7989. return true;
  7990. };
  7991. // Statics
  7992. BoundingBox.Intersects = function (box0, box1) {
  7993. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7994. return false;
  7995. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7996. return false;
  7997. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7998. return false;
  7999. return true;
  8000. };
  8001. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8002. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8003. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8004. return (num <= (sphereRadius * sphereRadius));
  8005. };
  8006. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8007. for (var p = 0; p < 6; p++) {
  8008. for (var i = 0; i < 8; i++) {
  8009. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8010. return false;
  8011. }
  8012. }
  8013. }
  8014. return true;
  8015. };
  8016. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8017. for (var p = 0; p < 6; p++) {
  8018. var inCount = 8;
  8019. for (var i = 0; i < 8; i++) {
  8020. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8021. --inCount;
  8022. }
  8023. else {
  8024. break;
  8025. }
  8026. }
  8027. if (inCount === 0)
  8028. return false;
  8029. }
  8030. return true;
  8031. };
  8032. return BoundingBox;
  8033. })();
  8034. BABYLON.BoundingBox = BoundingBox;
  8035. })(BABYLON || (BABYLON = {}));
  8036. var BABYLON;
  8037. (function (BABYLON) {
  8038. var computeBoxExtents = function (axis, box) {
  8039. var p = BABYLON.Vector3.Dot(box.center, axis);
  8040. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8041. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8042. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8043. var r = r0 + r1 + r2;
  8044. return {
  8045. min: p - r,
  8046. max: p + r
  8047. };
  8048. };
  8049. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8050. var axisOverlap = function (axis, box0, box1) {
  8051. var result0 = computeBoxExtents(axis, box0);
  8052. var result1 = computeBoxExtents(axis, box1);
  8053. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8054. };
  8055. var BoundingInfo = (function () {
  8056. function BoundingInfo(minimum, maximum) {
  8057. this.minimum = minimum;
  8058. this.maximum = maximum;
  8059. this._isLocked = false;
  8060. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8061. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8062. }
  8063. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8064. get: function () {
  8065. return this._isLocked;
  8066. },
  8067. set: function (value) {
  8068. this._isLocked = value;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. // Methods
  8074. BoundingInfo.prototype.update = function (world) {
  8075. if (this._isLocked) {
  8076. return;
  8077. }
  8078. this.boundingBox._update(world);
  8079. this.boundingSphere._update(world);
  8080. };
  8081. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8082. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8083. return false;
  8084. return this.boundingBox.isInFrustum(frustumPlanes);
  8085. };
  8086. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8087. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8088. };
  8089. BoundingInfo.prototype._checkCollision = function (collider) {
  8090. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8091. };
  8092. BoundingInfo.prototype.intersectsPoint = function (point) {
  8093. if (!this.boundingSphere.centerWorld) {
  8094. return false;
  8095. }
  8096. if (!this.boundingSphere.intersectsPoint(point)) {
  8097. return false;
  8098. }
  8099. if (!this.boundingBox.intersectsPoint(point)) {
  8100. return false;
  8101. }
  8102. return true;
  8103. };
  8104. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8105. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8106. return false;
  8107. }
  8108. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8109. return false;
  8110. }
  8111. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8112. return false;
  8113. }
  8114. if (!precise) {
  8115. return true;
  8116. }
  8117. var box0 = this.boundingBox;
  8118. var box1 = boundingInfo.boundingBox;
  8119. if (!axisOverlap(box0.directions[0], box0, box1))
  8120. return false;
  8121. if (!axisOverlap(box0.directions[1], box0, box1))
  8122. return false;
  8123. if (!axisOverlap(box0.directions[2], box0, box1))
  8124. return false;
  8125. if (!axisOverlap(box1.directions[0], box0, box1))
  8126. return false;
  8127. if (!axisOverlap(box1.directions[1], box0, box1))
  8128. return false;
  8129. if (!axisOverlap(box1.directions[2], box0, box1))
  8130. return false;
  8131. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8132. return false;
  8133. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8134. return false;
  8135. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8136. return false;
  8137. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8138. return false;
  8139. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8140. return false;
  8141. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8142. return false;
  8143. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8144. return false;
  8145. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8146. return false;
  8147. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8148. return false;
  8149. return true;
  8150. };
  8151. return BoundingInfo;
  8152. })();
  8153. BABYLON.BoundingInfo = BoundingInfo;
  8154. })(BABYLON || (BABYLON = {}));
  8155. var BABYLON;
  8156. (function (BABYLON) {
  8157. var Ray = (function () {
  8158. function Ray(origin, direction, length) {
  8159. if (length === void 0) { length = Number.MAX_VALUE; }
  8160. this.origin = origin;
  8161. this.direction = direction;
  8162. this.length = length;
  8163. }
  8164. // Methods
  8165. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8166. var d = 0.0;
  8167. var maxValue = Number.MAX_VALUE;
  8168. var inv;
  8169. var min;
  8170. var max;
  8171. var temp;
  8172. if (Math.abs(this.direction.x) < 0.0000001) {
  8173. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8174. return false;
  8175. }
  8176. }
  8177. else {
  8178. inv = 1.0 / this.direction.x;
  8179. min = (minimum.x - this.origin.x) * inv;
  8180. max = (maximum.x - this.origin.x) * inv;
  8181. if (max === -Infinity) {
  8182. max = Infinity;
  8183. }
  8184. if (min > max) {
  8185. temp = min;
  8186. min = max;
  8187. max = temp;
  8188. }
  8189. d = Math.max(min, d);
  8190. maxValue = Math.min(max, maxValue);
  8191. if (d > maxValue) {
  8192. return false;
  8193. }
  8194. }
  8195. if (Math.abs(this.direction.y) < 0.0000001) {
  8196. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8197. return false;
  8198. }
  8199. }
  8200. else {
  8201. inv = 1.0 / this.direction.y;
  8202. min = (minimum.y - this.origin.y) * inv;
  8203. max = (maximum.y - this.origin.y) * inv;
  8204. if (max === -Infinity) {
  8205. max = Infinity;
  8206. }
  8207. if (min > max) {
  8208. temp = min;
  8209. min = max;
  8210. max = temp;
  8211. }
  8212. d = Math.max(min, d);
  8213. maxValue = Math.min(max, maxValue);
  8214. if (d > maxValue) {
  8215. return false;
  8216. }
  8217. }
  8218. if (Math.abs(this.direction.z) < 0.0000001) {
  8219. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8220. return false;
  8221. }
  8222. }
  8223. else {
  8224. inv = 1.0 / this.direction.z;
  8225. min = (minimum.z - this.origin.z) * inv;
  8226. max = (maximum.z - this.origin.z) * inv;
  8227. if (max === -Infinity) {
  8228. max = Infinity;
  8229. }
  8230. if (min > max) {
  8231. temp = min;
  8232. min = max;
  8233. max = temp;
  8234. }
  8235. d = Math.max(min, d);
  8236. maxValue = Math.min(max, maxValue);
  8237. if (d > maxValue) {
  8238. return false;
  8239. }
  8240. }
  8241. return true;
  8242. };
  8243. Ray.prototype.intersectsBox = function (box) {
  8244. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8245. };
  8246. Ray.prototype.intersectsSphere = function (sphere) {
  8247. var x = sphere.center.x - this.origin.x;
  8248. var y = sphere.center.y - this.origin.y;
  8249. var z = sphere.center.z - this.origin.z;
  8250. var pyth = (x * x) + (y * y) + (z * z);
  8251. var rr = sphere.radius * sphere.radius;
  8252. if (pyth <= rr) {
  8253. return true;
  8254. }
  8255. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8256. if (dot < 0.0) {
  8257. return false;
  8258. }
  8259. var temp = pyth - (dot * dot);
  8260. return temp <= rr;
  8261. };
  8262. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8263. if (!this._edge1) {
  8264. this._edge1 = BABYLON.Vector3.Zero();
  8265. this._edge2 = BABYLON.Vector3.Zero();
  8266. this._pvec = BABYLON.Vector3.Zero();
  8267. this._tvec = BABYLON.Vector3.Zero();
  8268. this._qvec = BABYLON.Vector3.Zero();
  8269. }
  8270. vertex1.subtractToRef(vertex0, this._edge1);
  8271. vertex2.subtractToRef(vertex0, this._edge2);
  8272. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8273. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8274. if (det === 0) {
  8275. return null;
  8276. }
  8277. var invdet = 1 / det;
  8278. this.origin.subtractToRef(vertex0, this._tvec);
  8279. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8280. if (bu < 0 || bu > 1.0) {
  8281. return null;
  8282. }
  8283. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8284. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8285. if (bv < 0 || bu + bv > 1.0) {
  8286. return null;
  8287. }
  8288. //check if the distance is longer than the predefined length.
  8289. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8290. if (distance > this.length) {
  8291. return null;
  8292. }
  8293. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8294. };
  8295. Ray.prototype.intersectsPlane = function (plane) {
  8296. var distance;
  8297. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8298. if (Math.abs(result1) < 9.99999997475243E-07) {
  8299. return null;
  8300. }
  8301. else {
  8302. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8303. distance = (-plane.d - result2) / result1;
  8304. if (distance < 0.0) {
  8305. if (distance < -9.99999997475243E-07) {
  8306. return null;
  8307. }
  8308. else {
  8309. return 0;
  8310. }
  8311. }
  8312. return distance;
  8313. }
  8314. };
  8315. /**
  8316. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8317. * @param sega the first point of the segment to test the intersection against
  8318. * @param segb the second point of the segment to test the intersection against
  8319. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8320. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8321. */
  8322. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8323. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8324. var u = segb.subtract(sega);
  8325. var v = rsegb.subtract(this.origin);
  8326. var w = sega.subtract(this.origin);
  8327. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8328. var b = BABYLON.Vector3.Dot(u, v);
  8329. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8330. var d = BABYLON.Vector3.Dot(u, w);
  8331. var e = BABYLON.Vector3.Dot(v, w);
  8332. var D = a * c - b * b; // always >= 0
  8333. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8334. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8335. // compute the line parameters of the two closest points
  8336. if (D < Ray.smallnum) {
  8337. sN = 0.0; // force using point P0 on segment S1
  8338. sD = 1.0; // to prevent possible division by 0.0 later
  8339. tN = e;
  8340. tD = c;
  8341. }
  8342. else {
  8343. sN = (b * e - c * d);
  8344. tN = (a * e - b * d);
  8345. if (sN < 0.0) {
  8346. sN = 0.0;
  8347. tN = e;
  8348. tD = c;
  8349. }
  8350. else if (sN > sD) {
  8351. sN = sD;
  8352. tN = e + b;
  8353. tD = c;
  8354. }
  8355. }
  8356. if (tN < 0.0) {
  8357. tN = 0.0;
  8358. // recompute sc for this edge
  8359. if (-d < 0.0) {
  8360. sN = 0.0;
  8361. }
  8362. else if (-d > a)
  8363. sN = sD;
  8364. else {
  8365. sN = -d;
  8366. sD = a;
  8367. }
  8368. }
  8369. else if (tN > tD) {
  8370. tN = tD;
  8371. // recompute sc for this edge
  8372. if ((-d + b) < 0.0) {
  8373. sN = 0;
  8374. }
  8375. else if ((-d + b) > a) {
  8376. sN = sD;
  8377. }
  8378. else {
  8379. sN = (-d + b);
  8380. sD = a;
  8381. }
  8382. }
  8383. // finally do the division to get sc and tc
  8384. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8385. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8386. // get the difference of the two closest points
  8387. var qtc = v.multiplyByFloats(tc, tc, tc);
  8388. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8389. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8390. if (isIntersected) {
  8391. return qtc.length();
  8392. }
  8393. return -1;
  8394. };
  8395. // Statics
  8396. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8397. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8398. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8399. var direction = end.subtract(start);
  8400. direction.normalize();
  8401. return new Ray(start, direction);
  8402. };
  8403. /**
  8404. * 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
  8405. * transformed to the given world matrix.
  8406. * @param origin The origin point
  8407. * @param end The end point
  8408. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8409. */
  8410. Ray.CreateNewFromTo = function (origin, end, world) {
  8411. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8412. var direction = end.subtract(origin);
  8413. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8414. direction.normalize();
  8415. return Ray.Transform(new Ray(origin, direction, length), world);
  8416. };
  8417. Ray.Transform = function (ray, matrix) {
  8418. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8419. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8420. newDirection.normalize();
  8421. return new Ray(newOrigin, newDirection, ray.length);
  8422. };
  8423. Ray.smallnum = 0.00000001;
  8424. Ray.rayl = 10e8;
  8425. return Ray;
  8426. })();
  8427. BABYLON.Ray = Ray;
  8428. })(BABYLON || (BABYLON = {}));
  8429. var BABYLON;
  8430. (function (BABYLON) {
  8431. var AbstractMesh = (function (_super) {
  8432. __extends(AbstractMesh, _super);
  8433. // Constructor
  8434. function AbstractMesh(name, scene) {
  8435. var _this = this;
  8436. _super.call(this, name, scene);
  8437. // Events
  8438. /**
  8439. * An event triggered when this mesh collides with another one
  8440. * @type {BABYLON.Observable}
  8441. */
  8442. this.onCollideObservable = new BABYLON.Observable();
  8443. /**
  8444. * An event triggered when the collision's position changes
  8445. * @type {BABYLON.Observable}
  8446. */
  8447. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8448. /**
  8449. * An event triggered after the world matrix is updated
  8450. * @type {BABYLON.Observable}
  8451. */
  8452. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8453. // Properties
  8454. this.definedFacingForward = true; // orientation for POV movement & rotation
  8455. this.position = new BABYLON.Vector3(0, 0, 0);
  8456. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8457. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8458. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8459. this.visibility = 1.0;
  8460. this.alphaIndex = Number.MAX_VALUE;
  8461. this.infiniteDistance = false;
  8462. this.isVisible = true;
  8463. this.isPickable = true;
  8464. this.showBoundingBox = false;
  8465. this.showSubMeshesBoundingBox = false;
  8466. this.onDispose = null;
  8467. this.isBlocker = false;
  8468. this.renderingGroupId = 0;
  8469. this.receiveShadows = false;
  8470. this.renderOutline = false;
  8471. this.outlineColor = BABYLON.Color3.Red();
  8472. this.outlineWidth = 0.02;
  8473. this.renderOverlay = false;
  8474. this.overlayColor = BABYLON.Color3.Red();
  8475. this.overlayAlpha = 0.5;
  8476. this.hasVertexAlpha = false;
  8477. this.useVertexColors = true;
  8478. this.applyFog = true;
  8479. this.computeBonesUsingShaders = true;
  8480. this.scalingDeterminant = 1;
  8481. this.numBoneInfluencers = 4;
  8482. this.useOctreeForRenderingSelection = true;
  8483. this.useOctreeForPicking = true;
  8484. this.useOctreeForCollisions = true;
  8485. this.layerMask = 0x0FFFFFFF;
  8486. this.alwaysSelectAsActiveMesh = false;
  8487. // Collisions
  8488. this._checkCollisions = false;
  8489. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8490. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8491. this._collider = new BABYLON.Collider();
  8492. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8493. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8494. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8495. // Edges
  8496. this.edgesWidth = 1;
  8497. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8498. // Cache
  8499. this._localWorld = BABYLON.Matrix.Zero();
  8500. this._worldMatrix = BABYLON.Matrix.Zero();
  8501. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8502. this._absolutePosition = BABYLON.Vector3.Zero();
  8503. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8504. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8505. this._isDirty = false;
  8506. this._pivotMatrix = BABYLON.Matrix.Identity();
  8507. this._isDisposed = false;
  8508. this._renderId = 0;
  8509. this._intersectionsInProgress = new Array();
  8510. this._isWorldMatrixFrozen = false;
  8511. this._unIndexed = false;
  8512. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8513. if (collidedMesh === void 0) { collidedMesh = null; }
  8514. //TODO move this to the collision coordinator!
  8515. if (_this.getScene().workerCollisions)
  8516. newPosition.multiplyInPlace(_this._collider.radius);
  8517. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8518. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8519. _this.position.addInPlace(_this._diffPositionForCollisions);
  8520. }
  8521. if (collidedMesh) {
  8522. _this.onCollideObservable.notifyObservers(collidedMesh);
  8523. }
  8524. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8525. };
  8526. scene.addMesh(this);
  8527. }
  8528. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8529. get: function () {
  8530. return AbstractMesh._BILLBOARDMODE_NONE;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8536. get: function () {
  8537. return AbstractMesh._BILLBOARDMODE_X;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8543. get: function () {
  8544. return AbstractMesh._BILLBOARDMODE_Y;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8550. get: function () {
  8551. return AbstractMesh._BILLBOARDMODE_Z;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8557. get: function () {
  8558. return AbstractMesh._BILLBOARDMODE_ALL;
  8559. },
  8560. enumerable: true,
  8561. configurable: true
  8562. });
  8563. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8564. set: function (callback) {
  8565. if (this._onCollideObserver) {
  8566. this.onCollideObservable.remove(this._onCollideObserver);
  8567. }
  8568. this._onCollideObserver = this.onCollideObservable.add(callback);
  8569. },
  8570. enumerable: true,
  8571. configurable: true
  8572. });
  8573. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8574. set: function (callback) {
  8575. if (this._onCollisionPositionChangeObserver) {
  8576. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8577. }
  8578. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8579. },
  8580. enumerable: true,
  8581. configurable: true
  8582. });
  8583. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8584. get: function () {
  8585. return this._skeleton;
  8586. },
  8587. set: function (value) {
  8588. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8589. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8590. }
  8591. if (value && value.needInitialSkinMatrix) {
  8592. value._registerMeshWithPoseMatrix(this);
  8593. }
  8594. this._skeleton = value;
  8595. if (!this._skeleton) {
  8596. this._bonesTransformMatrices = null;
  8597. }
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. /**
  8603. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8604. */
  8605. AbstractMesh.prototype.toString = function (fullDetails) {
  8606. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8607. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8608. if (this._skeleton) {
  8609. ret += ", skeleton: " + this._skeleton.name;
  8610. }
  8611. if (fullDetails) {
  8612. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8613. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8614. }
  8615. return ret;
  8616. };
  8617. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8618. /**
  8619. * Getting the rotation object.
  8620. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8621. */
  8622. get: function () {
  8623. return this._rotation;
  8624. },
  8625. set: function (newRotation) {
  8626. this._rotation = newRotation;
  8627. },
  8628. enumerable: true,
  8629. configurable: true
  8630. });
  8631. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8632. get: function () {
  8633. return this._scaling;
  8634. },
  8635. set: function (newScaling) {
  8636. this._scaling = newScaling;
  8637. if (this.physicsImpostor) {
  8638. this.physicsImpostor.forceUpdate();
  8639. }
  8640. },
  8641. enumerable: true,
  8642. configurable: true
  8643. });
  8644. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8645. get: function () {
  8646. return this._rotationQuaternion;
  8647. },
  8648. set: function (quaternion) {
  8649. this._rotationQuaternion = quaternion;
  8650. //reset the rotation vector.
  8651. if (quaternion && this.rotation.length()) {
  8652. this.rotation.copyFromFloats(0, 0, 0);
  8653. }
  8654. },
  8655. enumerable: true,
  8656. configurable: true
  8657. });
  8658. // Methods
  8659. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8660. this._poseMatrix.copyFrom(matrix);
  8661. };
  8662. AbstractMesh.prototype.getPoseMatrix = function () {
  8663. return this._poseMatrix;
  8664. };
  8665. AbstractMesh.prototype.disableEdgesRendering = function () {
  8666. if (this._edgesRenderer !== undefined) {
  8667. this._edgesRenderer.dispose();
  8668. this._edgesRenderer = undefined;
  8669. }
  8670. };
  8671. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8672. if (epsilon === void 0) { epsilon = 0.95; }
  8673. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8674. this.disableEdgesRendering();
  8675. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8676. };
  8677. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8678. get: function () {
  8679. return false;
  8680. },
  8681. enumerable: true,
  8682. configurable: true
  8683. });
  8684. AbstractMesh.prototype.getLOD = function (camera) {
  8685. return this;
  8686. };
  8687. AbstractMesh.prototype.getTotalVertices = function () {
  8688. return 0;
  8689. };
  8690. AbstractMesh.prototype.getIndices = function () {
  8691. return null;
  8692. };
  8693. AbstractMesh.prototype.getVerticesData = function (kind) {
  8694. return null;
  8695. };
  8696. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8697. return false;
  8698. };
  8699. AbstractMesh.prototype.getBoundingInfo = function () {
  8700. if (this._masterMesh) {
  8701. return this._masterMesh.getBoundingInfo();
  8702. }
  8703. if (!this._boundingInfo) {
  8704. this._updateBoundingInfo();
  8705. }
  8706. return this._boundingInfo;
  8707. };
  8708. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8709. get: function () {
  8710. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8711. },
  8712. enumerable: true,
  8713. configurable: true
  8714. });
  8715. AbstractMesh.prototype._preActivate = function () {
  8716. };
  8717. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8718. };
  8719. AbstractMesh.prototype._activate = function (renderId) {
  8720. this._renderId = renderId;
  8721. };
  8722. AbstractMesh.prototype.getWorldMatrix = function () {
  8723. if (this._masterMesh) {
  8724. return this._masterMesh.getWorldMatrix();
  8725. }
  8726. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8727. this.computeWorldMatrix();
  8728. }
  8729. return this._worldMatrix;
  8730. };
  8731. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8732. get: function () {
  8733. return this._worldMatrix;
  8734. },
  8735. enumerable: true,
  8736. configurable: true
  8737. });
  8738. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8739. get: function () {
  8740. return this._absolutePosition;
  8741. },
  8742. enumerable: true,
  8743. configurable: true
  8744. });
  8745. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8746. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8747. this.computeWorldMatrix(true);
  8748. this._isWorldMatrixFrozen = true;
  8749. };
  8750. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8751. this._isWorldMatrixFrozen = false;
  8752. this.computeWorldMatrix(true);
  8753. };
  8754. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8755. get: function () {
  8756. return this._isWorldMatrixFrozen;
  8757. },
  8758. enumerable: true,
  8759. configurable: true
  8760. });
  8761. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8762. axis.normalize();
  8763. if (!this.rotationQuaternion) {
  8764. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8765. this.rotation = BABYLON.Vector3.Zero();
  8766. }
  8767. var rotationQuaternion;
  8768. if (!space || space === BABYLON.Space.LOCAL) {
  8769. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8770. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8771. }
  8772. else {
  8773. if (this.parent) {
  8774. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8775. invertParentWorldMatrix.invert();
  8776. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8777. }
  8778. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8779. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8780. }
  8781. };
  8782. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8783. var displacementVector = axis.scale(distance);
  8784. if (!space || space === BABYLON.Space.LOCAL) {
  8785. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8786. this.setPositionWithLocalVector(tempV3);
  8787. }
  8788. else {
  8789. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8790. }
  8791. };
  8792. AbstractMesh.prototype.getAbsolutePosition = function () {
  8793. this.computeWorldMatrix();
  8794. return this._absolutePosition;
  8795. };
  8796. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8797. if (!absolutePosition) {
  8798. return;
  8799. }
  8800. var absolutePositionX;
  8801. var absolutePositionY;
  8802. var absolutePositionZ;
  8803. if (absolutePosition.x === undefined) {
  8804. if (arguments.length < 3) {
  8805. return;
  8806. }
  8807. absolutePositionX = arguments[0];
  8808. absolutePositionY = arguments[1];
  8809. absolutePositionZ = arguments[2];
  8810. }
  8811. else {
  8812. absolutePositionX = absolutePosition.x;
  8813. absolutePositionY = absolutePosition.y;
  8814. absolutePositionZ = absolutePosition.z;
  8815. }
  8816. if (this.parent) {
  8817. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8818. invertParentWorldMatrix.invert();
  8819. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8820. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8821. }
  8822. else {
  8823. this.position.x = absolutePositionX;
  8824. this.position.y = absolutePositionY;
  8825. this.position.z = absolutePositionZ;
  8826. }
  8827. };
  8828. // ================================== Point of View Movement =================================
  8829. /**
  8830. * Perform relative position change from the point of view of behind the front of the mesh.
  8831. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8832. * Supports definition of mesh facing forward or backward.
  8833. * @param {number} amountRight
  8834. * @param {number} amountUp
  8835. * @param {number} amountForward
  8836. */
  8837. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8838. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8839. };
  8840. /**
  8841. * Calculate relative position change from the point of view of behind the front of the mesh.
  8842. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8843. * Supports definition of mesh facing forward or backward.
  8844. * @param {number} amountRight
  8845. * @param {number} amountUp
  8846. * @param {number} amountForward
  8847. */
  8848. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8849. var rotMatrix = new BABYLON.Matrix();
  8850. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8851. rotQuaternion.toRotationMatrix(rotMatrix);
  8852. var translationDelta = BABYLON.Vector3.Zero();
  8853. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8854. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8855. return translationDelta;
  8856. };
  8857. // ================================== Point of View Rotation =================================
  8858. /**
  8859. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8860. * Supports definition of mesh facing forward or backward.
  8861. * @param {number} flipBack
  8862. * @param {number} twirlClockwise
  8863. * @param {number} tiltRight
  8864. */
  8865. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8866. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8867. };
  8868. /**
  8869. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8870. * Supports definition of mesh facing forward or backward.
  8871. * @param {number} flipBack
  8872. * @param {number} twirlClockwise
  8873. * @param {number} tiltRight
  8874. */
  8875. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8876. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8877. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8878. };
  8879. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8880. this._pivotMatrix = matrix;
  8881. this._cache.pivotMatrixUpdated = true;
  8882. };
  8883. AbstractMesh.prototype.getPivotMatrix = function () {
  8884. return this._pivotMatrix;
  8885. };
  8886. AbstractMesh.prototype._isSynchronized = function () {
  8887. if (this._isDirty) {
  8888. return false;
  8889. }
  8890. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8891. return false;
  8892. if (this._cache.pivotMatrixUpdated) {
  8893. return false;
  8894. }
  8895. if (this.infiniteDistance) {
  8896. return false;
  8897. }
  8898. if (!this._cache.position.equals(this.position))
  8899. return false;
  8900. if (this.rotationQuaternion) {
  8901. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8902. return false;
  8903. }
  8904. else {
  8905. if (!this._cache.rotation.equals(this.rotation))
  8906. return false;
  8907. }
  8908. if (!this._cache.scaling.equals(this.scaling))
  8909. return false;
  8910. return true;
  8911. };
  8912. AbstractMesh.prototype._initCache = function () {
  8913. _super.prototype._initCache.call(this);
  8914. this._cache.localMatrixUpdated = false;
  8915. this._cache.position = BABYLON.Vector3.Zero();
  8916. this._cache.scaling = BABYLON.Vector3.Zero();
  8917. this._cache.rotation = BABYLON.Vector3.Zero();
  8918. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8919. this._cache.billboardMode = -1;
  8920. };
  8921. AbstractMesh.prototype.markAsDirty = function (property) {
  8922. if (property === "rotation") {
  8923. this.rotationQuaternion = null;
  8924. }
  8925. this._currentRenderId = Number.MAX_VALUE;
  8926. this._isDirty = true;
  8927. };
  8928. AbstractMesh.prototype._updateBoundingInfo = function () {
  8929. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8930. this._boundingInfo.update(this.worldMatrixFromCache);
  8931. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8932. };
  8933. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8934. if (!this.subMeshes) {
  8935. return;
  8936. }
  8937. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8938. var subMesh = this.subMeshes[subIndex];
  8939. if (!subMesh.IsGlobal) {
  8940. subMesh.updateBoundingInfo(matrix);
  8941. }
  8942. }
  8943. };
  8944. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8945. if (this._isWorldMatrixFrozen) {
  8946. return this._worldMatrix;
  8947. }
  8948. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8949. this._currentRenderId = this.getScene().getRenderId();
  8950. return this._worldMatrix;
  8951. }
  8952. this._cache.position.copyFrom(this.position);
  8953. this._cache.scaling.copyFrom(this.scaling);
  8954. this._cache.pivotMatrixUpdated = false;
  8955. this._cache.billboardMode = this.billboardMode;
  8956. this._currentRenderId = this.getScene().getRenderId();
  8957. this._isDirty = false;
  8958. // Scaling
  8959. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8960. // Rotation
  8961. //rotate, if quaternion is set and rotation was used
  8962. if (this.rotationQuaternion) {
  8963. var len = this.rotation.length();
  8964. if (len) {
  8965. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8966. this.rotation.copyFromFloats(0, 0, 0);
  8967. }
  8968. }
  8969. if (this.rotationQuaternion) {
  8970. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8971. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8972. }
  8973. else {
  8974. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8975. this._cache.rotation.copyFrom(this.rotation);
  8976. }
  8977. // Translation
  8978. if (this.infiniteDistance && !this.parent) {
  8979. var camera = this.getScene().activeCamera;
  8980. if (camera) {
  8981. var cameraWorldMatrix = camera.getWorldMatrix();
  8982. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8983. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8984. }
  8985. }
  8986. else {
  8987. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8988. }
  8989. // Composing transformations
  8990. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8991. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8992. // Billboarding
  8993. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8994. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8995. var localPosition = BABYLON.Tmp.Vector3[0];
  8996. if (this.parent && this.parent.getWorldMatrix) {
  8997. this._markSyncedWithParent();
  8998. var parentMatrix;
  8999. if (this._meshToBoneReferal) {
  9000. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9001. parentMatrix = BABYLON.Tmp.Matrix[6];
  9002. }
  9003. else {
  9004. parentMatrix = this.parent.getWorldMatrix();
  9005. }
  9006. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9007. localPosition = BABYLON.Tmp.Vector3[1];
  9008. }
  9009. var zero = this.getScene().activeCamera.globalPosition.clone();
  9010. if (this.parent && this.parent.position) {
  9011. localPosition.addInPlace(this.parent.position);
  9012. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9013. }
  9014. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9015. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9016. zero.x = localPosition.x + BABYLON.Epsilon;
  9017. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9018. zero.y = localPosition.y + BABYLON.Epsilon;
  9019. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9020. zero.z = localPosition.z + BABYLON.Epsilon;
  9021. }
  9022. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9023. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9024. BABYLON.Tmp.Matrix[3].invert();
  9025. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9026. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9027. }
  9028. // Local world
  9029. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9030. // Parent
  9031. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9032. this._markSyncedWithParent();
  9033. if (this._meshToBoneReferal) {
  9034. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9035. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9036. }
  9037. else {
  9038. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9039. }
  9040. }
  9041. else {
  9042. this._worldMatrix.copyFrom(this._localWorld);
  9043. }
  9044. // Bounding info
  9045. this._updateBoundingInfo();
  9046. // Absolute position
  9047. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9048. // Callbacks
  9049. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9050. if (!this._poseMatrix) {
  9051. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9052. }
  9053. return this._worldMatrix;
  9054. };
  9055. /**
  9056. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9057. * @param func: callback function to add
  9058. */
  9059. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9060. this.onAfterWorldMatrixUpdateObservable.add(func);
  9061. };
  9062. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9063. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9064. };
  9065. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9066. this.computeWorldMatrix();
  9067. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9068. };
  9069. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9070. this.computeWorldMatrix();
  9071. var invLocalWorldMatrix = this._localWorld.clone();
  9072. invLocalWorldMatrix.invert();
  9073. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9074. };
  9075. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9076. this.computeWorldMatrix(true);
  9077. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9078. };
  9079. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9080. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9081. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9082. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9083. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9084. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9085. /// <returns>Mesh oriented towards targetMesh</returns>
  9086. yawCor = yawCor || 0; // default to zero if undefined
  9087. pitchCor = pitchCor || 0;
  9088. rollCor = rollCor || 0;
  9089. var dv = targetPoint.subtract(this.position);
  9090. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9091. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9092. var pitch = Math.atan2(dv.y, len);
  9093. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9094. };
  9095. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9096. this._meshToBoneReferal = affectedMesh;
  9097. this.parent = bone;
  9098. if (bone.getWorldMatrix().determinant() < 0) {
  9099. this.scalingDeterminant *= -1;
  9100. }
  9101. };
  9102. AbstractMesh.prototype.detachFromBone = function () {
  9103. if (this.parent.getWorldMatrix().determinant() < 0) {
  9104. this.scalingDeterminant *= -1;
  9105. }
  9106. this._meshToBoneReferal = null;
  9107. this.parent = null;
  9108. };
  9109. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9110. return this._boundingInfo.isInFrustum(frustumPlanes);
  9111. };
  9112. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9113. if (!camera) {
  9114. camera = this.getScene().activeCamera;
  9115. }
  9116. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9117. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9118. return false;
  9119. }
  9120. return true;
  9121. };
  9122. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9123. if (!this._boundingInfo || !mesh._boundingInfo) {
  9124. return false;
  9125. }
  9126. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9127. };
  9128. AbstractMesh.prototype.intersectsPoint = function (point) {
  9129. if (!this._boundingInfo) {
  9130. return false;
  9131. }
  9132. return this._boundingInfo.intersectsPoint(point);
  9133. };
  9134. // Physics
  9135. /**
  9136. * @Deprecated. Use new PhysicsImpostor instead.
  9137. * */
  9138. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9139. //legacy support
  9140. if (impostor.impostor) {
  9141. options = impostor;
  9142. impostor = impostor.impostor;
  9143. }
  9144. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9145. return this.physicsImpostor.physicsBody;
  9146. };
  9147. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9148. return this.physicsImpostor;
  9149. };
  9150. /**
  9151. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9152. */
  9153. AbstractMesh.prototype.getPhysicsMass = function () {
  9154. return this.physicsImpostor.getParam("mass");
  9155. };
  9156. /**
  9157. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9158. */
  9159. AbstractMesh.prototype.getPhysicsFriction = function () {
  9160. return this.physicsImpostor.getParam("friction");
  9161. };
  9162. /**
  9163. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9164. */
  9165. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9166. return this.physicsImpostor.getParam("resitution");
  9167. };
  9168. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9169. if (!camera) {
  9170. camera = this.getScene().activeCamera;
  9171. }
  9172. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9173. };
  9174. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9175. if (!camera) {
  9176. camera = this.getScene().activeCamera;
  9177. }
  9178. return this.absolutePosition.subtract(camera.position).length();
  9179. };
  9180. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9181. if (!this.physicsImpostor) {
  9182. return;
  9183. }
  9184. this.physicsImpostor.applyImpulse(force, contactPoint);
  9185. };
  9186. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9187. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9188. return;
  9189. }
  9190. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9191. mainPivot: pivot1,
  9192. connectedPivot: pivot2,
  9193. nativeParams: options
  9194. });
  9195. };
  9196. /**
  9197. * @Deprecated
  9198. */
  9199. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9200. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9201. this.updatePhysicsBody();
  9202. };
  9203. /**
  9204. * @Deprecated
  9205. * Calling this function is not needed anymore.
  9206. * The physics engine takes care of transofmration automatically.
  9207. */
  9208. AbstractMesh.prototype.updatePhysicsBody = function () {
  9209. //Unneeded
  9210. };
  9211. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9212. // Collisions
  9213. get: function () {
  9214. return this._checkCollisions;
  9215. },
  9216. set: function (collisionEnabled) {
  9217. this._checkCollisions = collisionEnabled;
  9218. if (this.getScene().workerCollisions) {
  9219. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9220. }
  9221. },
  9222. enumerable: true,
  9223. configurable: true
  9224. });
  9225. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9226. var globalPosition = this.getAbsolutePosition();
  9227. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9228. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9229. this._collider.radius = this.ellipsoid;
  9230. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9231. };
  9232. // Submeshes octree
  9233. /**
  9234. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9235. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9236. */
  9237. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9238. if (maxCapacity === void 0) { maxCapacity = 64; }
  9239. if (maxDepth === void 0) { maxDepth = 2; }
  9240. if (!this._submeshesOctree) {
  9241. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9242. }
  9243. this.computeWorldMatrix(true);
  9244. // Update octree
  9245. var bbox = this.getBoundingInfo().boundingBox;
  9246. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9247. return this._submeshesOctree;
  9248. };
  9249. // Collisions
  9250. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9251. this._generatePointsArray();
  9252. // Transformation
  9253. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9254. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9255. subMesh._lastColliderWorldVertices = [];
  9256. subMesh._trianglePlanes = [];
  9257. var start = subMesh.verticesStart;
  9258. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9259. for (var i = start; i < end; i++) {
  9260. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9261. }
  9262. }
  9263. // Collide
  9264. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9265. if (collider.collisionFound) {
  9266. collider.collidedMesh = this;
  9267. }
  9268. };
  9269. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9270. var subMeshes;
  9271. var len;
  9272. // Octrees
  9273. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9274. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9275. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9276. len = intersections.length;
  9277. subMeshes = intersections.data;
  9278. }
  9279. else {
  9280. subMeshes = this.subMeshes;
  9281. len = subMeshes.length;
  9282. }
  9283. for (var index = 0; index < len; index++) {
  9284. var subMesh = subMeshes[index];
  9285. // Bounding test
  9286. if (len > 1 && !subMesh._checkCollision(collider))
  9287. continue;
  9288. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9289. }
  9290. };
  9291. AbstractMesh.prototype._checkCollision = function (collider) {
  9292. // Bounding box test
  9293. if (!this._boundingInfo._checkCollision(collider))
  9294. return;
  9295. // Transformation matrix
  9296. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9297. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9298. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9299. };
  9300. // Picking
  9301. AbstractMesh.prototype._generatePointsArray = function () {
  9302. return false;
  9303. };
  9304. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9305. var pickingInfo = new BABYLON.PickingInfo();
  9306. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9307. return pickingInfo;
  9308. }
  9309. if (!this._generatePointsArray()) {
  9310. return pickingInfo;
  9311. }
  9312. var intersectInfo = null;
  9313. // Octrees
  9314. var subMeshes;
  9315. var len;
  9316. if (this._submeshesOctree && this.useOctreeForPicking) {
  9317. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9318. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9319. len = intersections.length;
  9320. subMeshes = intersections.data;
  9321. }
  9322. else {
  9323. subMeshes = this.subMeshes;
  9324. len = subMeshes.length;
  9325. }
  9326. for (var index = 0; index < len; index++) {
  9327. var subMesh = subMeshes[index];
  9328. // Bounding test
  9329. if (len > 1 && !subMesh.canIntersects(ray))
  9330. continue;
  9331. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9332. if (currentIntersectInfo) {
  9333. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9334. intersectInfo = currentIntersectInfo;
  9335. intersectInfo.subMeshId = index;
  9336. if (fastCheck) {
  9337. break;
  9338. }
  9339. }
  9340. }
  9341. }
  9342. if (intersectInfo) {
  9343. // Get picked point
  9344. var world = this.getWorldMatrix();
  9345. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9346. var direction = ray.direction.clone();
  9347. direction = direction.scale(intersectInfo.distance);
  9348. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9349. var pickedPoint = worldOrigin.add(worldDirection);
  9350. // Return result
  9351. pickingInfo.hit = true;
  9352. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9353. pickingInfo.pickedPoint = pickedPoint;
  9354. pickingInfo.pickedMesh = this;
  9355. pickingInfo.bu = intersectInfo.bu;
  9356. pickingInfo.bv = intersectInfo.bv;
  9357. pickingInfo.faceId = intersectInfo.faceId;
  9358. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9359. return pickingInfo;
  9360. }
  9361. return pickingInfo;
  9362. };
  9363. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9364. return null;
  9365. };
  9366. AbstractMesh.prototype.releaseSubMeshes = function () {
  9367. if (this.subMeshes) {
  9368. while (this.subMeshes.length) {
  9369. this.subMeshes[0].dispose();
  9370. }
  9371. }
  9372. else {
  9373. this.subMeshes = new Array();
  9374. }
  9375. };
  9376. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9377. var _this = this;
  9378. var index;
  9379. // Action manager
  9380. if (this.actionManager) {
  9381. this.actionManager.dispose();
  9382. this.actionManager = null;
  9383. }
  9384. // Skeleton
  9385. this.skeleton = null;
  9386. // Animations
  9387. this.getScene().stopAnimation(this);
  9388. // Physics
  9389. if (this.physicsImpostor) {
  9390. this.physicsImpostor.dispose();
  9391. }
  9392. // Intersections in progress
  9393. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9394. var other = this._intersectionsInProgress[index];
  9395. var pos = other._intersectionsInProgress.indexOf(this);
  9396. other._intersectionsInProgress.splice(pos, 1);
  9397. }
  9398. this._intersectionsInProgress = [];
  9399. // Lights
  9400. var lights = this.getScene().lights;
  9401. lights.forEach(function (light) {
  9402. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9403. if (meshIndex !== -1) {
  9404. light.includedOnlyMeshes.splice(meshIndex, 1);
  9405. }
  9406. meshIndex = light.excludedMeshes.indexOf(_this);
  9407. if (meshIndex !== -1) {
  9408. light.excludedMeshes.splice(meshIndex, 1);
  9409. }
  9410. });
  9411. // Edges
  9412. if (this._edgesRenderer) {
  9413. this._edgesRenderer.dispose();
  9414. this._edgesRenderer = null;
  9415. }
  9416. // SubMeshes
  9417. this.releaseSubMeshes();
  9418. // Remove from scene
  9419. this.getScene().removeMesh(this);
  9420. if (!doNotRecurse) {
  9421. // Particles
  9422. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9423. if (this.getScene().particleSystems[index].emitter === this) {
  9424. this.getScene().particleSystems[index].dispose();
  9425. index--;
  9426. }
  9427. }
  9428. // Children
  9429. var objects = this.getDescendants(true);
  9430. for (index = 0; index < objects.length; index++) {
  9431. objects[index].dispose();
  9432. }
  9433. }
  9434. else {
  9435. var childMeshes = this.getChildMeshes(true);
  9436. for (index = 0; index < childMeshes.length; index++) {
  9437. var child = childMeshes[index];
  9438. child.parent = null;
  9439. child.computeWorldMatrix(true);
  9440. }
  9441. }
  9442. _super.prototype.dispose.call(this);
  9443. this.onAfterWorldMatrixUpdateObservable.clear();
  9444. this._isDisposed = true;
  9445. // Callback
  9446. if (this.onDispose) {
  9447. this.onDispose();
  9448. }
  9449. };
  9450. // Statics
  9451. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9452. AbstractMesh._BILLBOARDMODE_X = 1;
  9453. AbstractMesh._BILLBOARDMODE_Y = 2;
  9454. AbstractMesh._BILLBOARDMODE_Z = 4;
  9455. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9456. return AbstractMesh;
  9457. })(BABYLON.Node);
  9458. BABYLON.AbstractMesh = AbstractMesh;
  9459. })(BABYLON || (BABYLON = {}));
  9460. var BABYLON;
  9461. (function (BABYLON) {
  9462. var Light = (function (_super) {
  9463. __extends(Light, _super);
  9464. function Light(name, scene) {
  9465. _super.call(this, name, scene);
  9466. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9467. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9468. this.intensity = 1.0;
  9469. this.range = Number.MAX_VALUE;
  9470. this.includeOnlyWithLayerMask = 0;
  9471. this.includedOnlyMeshes = new Array();
  9472. this.excludedMeshes = new Array();
  9473. this.excludeWithLayerMask = 0;
  9474. // PBR Properties.
  9475. this.radius = 0.00001;
  9476. this._excludedMeshesIds = new Array();
  9477. this._includedOnlyMeshesIds = new Array();
  9478. scene.addLight(this);
  9479. }
  9480. /**
  9481. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9482. */
  9483. Light.prototype.toString = function (fullDetails) {
  9484. var ret = "Name: " + this.name;
  9485. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9486. if (this.animations) {
  9487. for (var i = 0; i < this.animations.length; i++) {
  9488. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9489. }
  9490. }
  9491. if (fullDetails) {
  9492. }
  9493. return ret;
  9494. };
  9495. Light.prototype.getShadowGenerator = function () {
  9496. return this._shadowGenerator;
  9497. };
  9498. Light.prototype.getAbsolutePosition = function () {
  9499. return BABYLON.Vector3.Zero();
  9500. };
  9501. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9502. };
  9503. Light.prototype._getWorldMatrix = function () {
  9504. return BABYLON.Matrix.Identity();
  9505. };
  9506. Light.prototype.canAffectMesh = function (mesh) {
  9507. if (!mesh) {
  9508. return true;
  9509. }
  9510. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9511. return false;
  9512. }
  9513. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9514. return false;
  9515. }
  9516. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9517. return false;
  9518. }
  9519. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9520. return false;
  9521. }
  9522. return true;
  9523. };
  9524. Light.prototype.getWorldMatrix = function () {
  9525. this._currentRenderId = this.getScene().getRenderId();
  9526. var worldMatrix = this._getWorldMatrix();
  9527. if (this.parent && this.parent.getWorldMatrix) {
  9528. if (!this._parentedWorldMatrix) {
  9529. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9530. }
  9531. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9532. this._markSyncedWithParent();
  9533. return this._parentedWorldMatrix;
  9534. }
  9535. return worldMatrix;
  9536. };
  9537. Light.prototype.dispose = function () {
  9538. if (this._shadowGenerator) {
  9539. this._shadowGenerator.dispose();
  9540. this._shadowGenerator = null;
  9541. }
  9542. // Animations
  9543. this.getScene().stopAnimation(this);
  9544. // Remove from scene
  9545. this.getScene().removeLight(this);
  9546. _super.prototype.dispose.call(this);
  9547. };
  9548. Light.prototype.getTypeID = function () {
  9549. return 0;
  9550. };
  9551. Light.prototype.clone = function (name) {
  9552. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9553. };
  9554. Light.prototype.serialize = function () {
  9555. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9556. // Type
  9557. serializationObject.type = this.getTypeID();
  9558. // Parent
  9559. if (this.parent) {
  9560. serializationObject.parentId = this.parent.id;
  9561. }
  9562. // Inclusion / exclusions
  9563. if (this.excludedMeshes.length > 0) {
  9564. serializationObject.excludedMeshesIds = [];
  9565. this.excludedMeshes.forEach(function (mesh) {
  9566. serializationObject.excludedMeshesIds.push(mesh.id);
  9567. });
  9568. }
  9569. if (this.includedOnlyMeshes.length > 0) {
  9570. serializationObject.includedOnlyMeshesIds = [];
  9571. this.includedOnlyMeshes.forEach(function (mesh) {
  9572. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9573. });
  9574. }
  9575. // Animations
  9576. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9577. serializationObject.ranges = this.serializeAnimationRanges();
  9578. return serializationObject;
  9579. };
  9580. Light.GetConstructorFromName = function (type, name, scene) {
  9581. switch (type) {
  9582. case 0:
  9583. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9584. case 1:
  9585. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9586. case 2:
  9587. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9588. case 3:
  9589. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9590. }
  9591. };
  9592. Light.Parse = function (parsedLight, scene) {
  9593. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9594. // Inclusion / exclusions
  9595. if (parsedLight.excludedMeshesIds) {
  9596. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9597. }
  9598. if (parsedLight.includedOnlyMeshesIds) {
  9599. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9600. }
  9601. // Parent
  9602. if (parsedLight.parentId) {
  9603. light._waitingParentId = parsedLight.parentId;
  9604. }
  9605. // Animations
  9606. if (parsedLight.animations) {
  9607. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9608. var parsedAnimation = parsedLight.animations[animationIndex];
  9609. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9610. }
  9611. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9612. }
  9613. if (parsedLight.autoAnimate) {
  9614. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9615. }
  9616. return light;
  9617. };
  9618. __decorate([
  9619. BABYLON.serializeAsColor3()
  9620. ], Light.prototype, "diffuse", void 0);
  9621. __decorate([
  9622. BABYLON.serializeAsColor3()
  9623. ], Light.prototype, "specular", void 0);
  9624. __decorate([
  9625. BABYLON.serialize()
  9626. ], Light.prototype, "intensity", void 0);
  9627. __decorate([
  9628. BABYLON.serialize()
  9629. ], Light.prototype, "range", void 0);
  9630. __decorate([
  9631. BABYLON.serialize()
  9632. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9633. __decorate([
  9634. BABYLON.serialize()
  9635. ], Light.prototype, "excludeWithLayerMask", void 0);
  9636. __decorate([
  9637. BABYLON.serialize()
  9638. ], Light.prototype, "radius", void 0);
  9639. return Light;
  9640. })(BABYLON.Node);
  9641. BABYLON.Light = Light;
  9642. })(BABYLON || (BABYLON = {}));
  9643. var BABYLON;
  9644. (function (BABYLON) {
  9645. var PointLight = (function (_super) {
  9646. __extends(PointLight, _super);
  9647. function PointLight(name, position, scene) {
  9648. _super.call(this, name, scene);
  9649. this.position = position;
  9650. }
  9651. PointLight.prototype.getAbsolutePosition = function () {
  9652. return this.transformedPosition ? this.transformedPosition : this.position;
  9653. };
  9654. PointLight.prototype.computeTransformedPosition = function () {
  9655. if (this.parent && this.parent.getWorldMatrix) {
  9656. if (!this.transformedPosition) {
  9657. this.transformedPosition = BABYLON.Vector3.Zero();
  9658. }
  9659. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9660. return true;
  9661. }
  9662. return false;
  9663. };
  9664. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9665. if (this.parent && this.parent.getWorldMatrix) {
  9666. this.computeTransformedPosition();
  9667. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9668. return;
  9669. }
  9670. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9671. };
  9672. PointLight.prototype.needCube = function () {
  9673. return true;
  9674. };
  9675. PointLight.prototype.supportsVSM = function () {
  9676. return false;
  9677. };
  9678. PointLight.prototype.needRefreshPerFrame = function () {
  9679. return false;
  9680. };
  9681. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9682. switch (faceIndex) {
  9683. case 0:
  9684. return new BABYLON.Vector3(1, 0, 0);
  9685. case 1:
  9686. return new BABYLON.Vector3(-1, 0, 0);
  9687. case 2:
  9688. return new BABYLON.Vector3(0, -1, 0);
  9689. case 3:
  9690. return new BABYLON.Vector3(0, 1, 0);
  9691. case 4:
  9692. return new BABYLON.Vector3(0, 0, 1);
  9693. case 5:
  9694. return new BABYLON.Vector3(0, 0, -1);
  9695. }
  9696. return BABYLON.Vector3.Zero();
  9697. };
  9698. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9699. var activeCamera = this.getScene().activeCamera;
  9700. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9701. };
  9702. PointLight.prototype._getWorldMatrix = function () {
  9703. if (!this._worldMatrix) {
  9704. this._worldMatrix = BABYLON.Matrix.Identity();
  9705. }
  9706. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9707. return this._worldMatrix;
  9708. };
  9709. PointLight.prototype.getTypeID = function () {
  9710. return 0;
  9711. };
  9712. __decorate([
  9713. BABYLON.serializeAsVector3()
  9714. ], PointLight.prototype, "position", void 0);
  9715. return PointLight;
  9716. })(BABYLON.Light);
  9717. BABYLON.PointLight = PointLight;
  9718. })(BABYLON || (BABYLON = {}));
  9719. var BABYLON;
  9720. (function (BABYLON) {
  9721. var SpotLight = (function (_super) {
  9722. __extends(SpotLight, _super);
  9723. function SpotLight(name, position, direction, angle, exponent, scene) {
  9724. _super.call(this, name, scene);
  9725. this.position = position;
  9726. this.direction = direction;
  9727. this.angle = angle;
  9728. this.exponent = exponent;
  9729. }
  9730. SpotLight.prototype.getAbsolutePosition = function () {
  9731. return this.transformedPosition ? this.transformedPosition : this.position;
  9732. };
  9733. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9734. var activeCamera = this.getScene().activeCamera;
  9735. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9736. };
  9737. SpotLight.prototype.needCube = function () {
  9738. return false;
  9739. };
  9740. SpotLight.prototype.supportsVSM = function () {
  9741. return true;
  9742. };
  9743. SpotLight.prototype.needRefreshPerFrame = function () {
  9744. return false;
  9745. };
  9746. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9747. return this.direction;
  9748. };
  9749. SpotLight.prototype.setDirectionToTarget = function (target) {
  9750. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9751. return this.direction;
  9752. };
  9753. SpotLight.prototype.computeTransformedPosition = function () {
  9754. if (this.parent && this.parent.getWorldMatrix) {
  9755. if (!this.transformedPosition) {
  9756. this.transformedPosition = BABYLON.Vector3.Zero();
  9757. }
  9758. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9759. return true;
  9760. }
  9761. return false;
  9762. };
  9763. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9764. var normalizeDirection;
  9765. if (this.parent && this.parent.getWorldMatrix) {
  9766. if (!this._transformedDirection) {
  9767. this._transformedDirection = BABYLON.Vector3.Zero();
  9768. }
  9769. this.computeTransformedPosition();
  9770. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9771. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9772. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9773. }
  9774. else {
  9775. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9776. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9777. }
  9778. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9779. };
  9780. SpotLight.prototype._getWorldMatrix = function () {
  9781. if (!this._worldMatrix) {
  9782. this._worldMatrix = BABYLON.Matrix.Identity();
  9783. }
  9784. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9785. return this._worldMatrix;
  9786. };
  9787. SpotLight.prototype.getTypeID = function () {
  9788. return 2;
  9789. };
  9790. __decorate([
  9791. BABYLON.serializeAsVector3()
  9792. ], SpotLight.prototype, "position", void 0);
  9793. __decorate([
  9794. BABYLON.serializeAsVector3()
  9795. ], SpotLight.prototype, "direction", void 0);
  9796. __decorate([
  9797. BABYLON.serialize()
  9798. ], SpotLight.prototype, "angle", void 0);
  9799. __decorate([
  9800. BABYLON.serialize()
  9801. ], SpotLight.prototype, "exponent", void 0);
  9802. return SpotLight;
  9803. })(BABYLON.Light);
  9804. BABYLON.SpotLight = SpotLight;
  9805. })(BABYLON || (BABYLON = {}));
  9806. var BABYLON;
  9807. (function (BABYLON) {
  9808. var HemisphericLight = (function (_super) {
  9809. __extends(HemisphericLight, _super);
  9810. function HemisphericLight(name, direction, scene) {
  9811. _super.call(this, name, scene);
  9812. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9813. this.direction = direction;
  9814. }
  9815. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9816. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9817. return this.direction;
  9818. };
  9819. HemisphericLight.prototype.getShadowGenerator = function () {
  9820. return null;
  9821. };
  9822. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9823. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9824. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9825. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9826. };
  9827. HemisphericLight.prototype._getWorldMatrix = function () {
  9828. if (!this._worldMatrix) {
  9829. this._worldMatrix = BABYLON.Matrix.Identity();
  9830. }
  9831. return this._worldMatrix;
  9832. };
  9833. HemisphericLight.prototype.getTypeID = function () {
  9834. return 3;
  9835. };
  9836. __decorate([
  9837. BABYLON.serializeAsColor3()
  9838. ], HemisphericLight.prototype, "groundColor", void 0);
  9839. __decorate([
  9840. BABYLON.serializeAsVector3()
  9841. ], HemisphericLight.prototype, "direction", void 0);
  9842. return HemisphericLight;
  9843. })(BABYLON.Light);
  9844. BABYLON.HemisphericLight = HemisphericLight;
  9845. })(BABYLON || (BABYLON = {}));
  9846. var BABYLON;
  9847. (function (BABYLON) {
  9848. var DirectionalLight = (function (_super) {
  9849. __extends(DirectionalLight, _super);
  9850. function DirectionalLight(name, direction, scene) {
  9851. _super.call(this, name, scene);
  9852. this.shadowOrthoScale = 0.5;
  9853. this.autoUpdateExtends = true;
  9854. // Cache
  9855. this._orthoLeft = Number.MAX_VALUE;
  9856. this._orthoRight = Number.MIN_VALUE;
  9857. this._orthoTop = Number.MIN_VALUE;
  9858. this._orthoBottom = Number.MAX_VALUE;
  9859. this.position = direction.scale(-1);
  9860. this.direction = direction;
  9861. }
  9862. DirectionalLight.prototype.getAbsolutePosition = function () {
  9863. return this.transformedPosition ? this.transformedPosition : this.position;
  9864. };
  9865. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9866. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9867. return this.direction;
  9868. };
  9869. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9870. var activeCamera = this.getScene().activeCamera;
  9871. // Check extends
  9872. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9873. var tempVector3 = BABYLON.Vector3.Zero();
  9874. this._orthoLeft = Number.MAX_VALUE;
  9875. this._orthoRight = Number.MIN_VALUE;
  9876. this._orthoTop = Number.MIN_VALUE;
  9877. this._orthoBottom = Number.MAX_VALUE;
  9878. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9879. var mesh = renderList[meshIndex];
  9880. if (!mesh) {
  9881. continue;
  9882. }
  9883. var boundingInfo = mesh.getBoundingInfo();
  9884. if (!boundingInfo) {
  9885. continue;
  9886. }
  9887. var boundingBox = boundingInfo.boundingBox;
  9888. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9889. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9890. if (tempVector3.x < this._orthoLeft)
  9891. this._orthoLeft = tempVector3.x;
  9892. if (tempVector3.y < this._orthoBottom)
  9893. this._orthoBottom = tempVector3.y;
  9894. if (tempVector3.x > this._orthoRight)
  9895. this._orthoRight = tempVector3.x;
  9896. if (tempVector3.y > this._orthoTop)
  9897. this._orthoTop = tempVector3.y;
  9898. }
  9899. }
  9900. }
  9901. var xOffset = this._orthoRight - this._orthoLeft;
  9902. var yOffset = this._orthoTop - this._orthoBottom;
  9903. 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);
  9904. };
  9905. DirectionalLight.prototype.supportsVSM = function () {
  9906. return true;
  9907. };
  9908. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9909. return true;
  9910. };
  9911. DirectionalLight.prototype.needCube = function () {
  9912. return false;
  9913. };
  9914. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9915. return this.direction;
  9916. };
  9917. DirectionalLight.prototype.computeTransformedPosition = function () {
  9918. if (this.parent && this.parent.getWorldMatrix) {
  9919. if (!this.transformedPosition) {
  9920. this.transformedPosition = BABYLON.Vector3.Zero();
  9921. }
  9922. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9923. return true;
  9924. }
  9925. return false;
  9926. };
  9927. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9928. if (this.parent && this.parent.getWorldMatrix) {
  9929. if (!this._transformedDirection) {
  9930. this._transformedDirection = BABYLON.Vector3.Zero();
  9931. }
  9932. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9933. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9934. return;
  9935. }
  9936. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9937. };
  9938. DirectionalLight.prototype._getWorldMatrix = function () {
  9939. if (!this._worldMatrix) {
  9940. this._worldMatrix = BABYLON.Matrix.Identity();
  9941. }
  9942. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9943. return this._worldMatrix;
  9944. };
  9945. DirectionalLight.prototype.getTypeID = function () {
  9946. return 1;
  9947. };
  9948. __decorate([
  9949. BABYLON.serializeAsVector3()
  9950. ], DirectionalLight.prototype, "position", void 0);
  9951. __decorate([
  9952. BABYLON.serializeAsVector3()
  9953. ], DirectionalLight.prototype, "direction", void 0);
  9954. __decorate([
  9955. BABYLON.serialize()
  9956. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9957. __decorate([
  9958. BABYLON.serialize()
  9959. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9960. return DirectionalLight;
  9961. })(BABYLON.Light);
  9962. BABYLON.DirectionalLight = DirectionalLight;
  9963. })(BABYLON || (BABYLON = {}));
  9964. var BABYLON;
  9965. (function (BABYLON) {
  9966. var ShadowGenerator = (function () {
  9967. function ShadowGenerator(mapSize, light) {
  9968. var _this = this;
  9969. // Members
  9970. this._filter = ShadowGenerator.FILTER_NONE;
  9971. this.blurScale = 2;
  9972. this._blurBoxOffset = 0;
  9973. this._bias = 0.00005;
  9974. this._lightDirection = BABYLON.Vector3.Zero();
  9975. this.forceBackFacesOnly = false;
  9976. this._darkness = 0;
  9977. this._transparencyShadow = false;
  9978. this._viewMatrix = BABYLON.Matrix.Zero();
  9979. this._projectionMatrix = BABYLON.Matrix.Zero();
  9980. this._transformMatrix = BABYLON.Matrix.Zero();
  9981. this._worldViewProjection = BABYLON.Matrix.Zero();
  9982. this._currentFaceIndex = 0;
  9983. this._currentFaceIndexCache = 0;
  9984. this._light = light;
  9985. this._scene = light.getScene();
  9986. this._mapSize = mapSize;
  9987. light._shadowGenerator = this;
  9988. // Render target
  9989. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9990. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9991. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9992. this._shadowMap.anisotropicFilteringLevel = 1;
  9993. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9994. this._shadowMap.renderParticles = false;
  9995. this._shadowMap.onBeforeRender = function (faceIndex) {
  9996. _this._currentFaceIndex = faceIndex;
  9997. };
  9998. this._shadowMap.onAfterUnbind = function () {
  9999. if (!_this.useBlurVarianceShadowMap) {
  10000. return;
  10001. }
  10002. if (!_this._shadowMap2) {
  10003. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  10004. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10005. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10006. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10007. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10008. _this._downSamplePostprocess.onApply = function (effect) {
  10009. effect.setTexture("textureSampler", _this._shadowMap);
  10010. };
  10011. _this.blurBoxOffset = 1;
  10012. }
  10013. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10014. };
  10015. // Custom render function
  10016. var renderSubMesh = function (subMesh) {
  10017. var mesh = subMesh.getRenderingMesh();
  10018. var scene = _this._scene;
  10019. var engine = scene.getEngine();
  10020. // Culling
  10021. engine.setState(subMesh.getMaterial().backFaceCulling);
  10022. // Managing instances
  10023. var batch = mesh._getInstancesRenderList(subMesh._id);
  10024. if (batch.mustReturn) {
  10025. return;
  10026. }
  10027. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10028. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10029. engine.enableEffect(_this._effect);
  10030. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10031. var material = subMesh.getMaterial();
  10032. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10033. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10034. if (_this.getLight().needCube()) {
  10035. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10036. }
  10037. // Alpha test
  10038. if (material && material.needAlphaTesting()) {
  10039. var alphaTexture = material.getAlphaTestTexture();
  10040. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10041. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10042. }
  10043. // Bones
  10044. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10045. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10046. }
  10047. if (_this.forceBackFacesOnly) {
  10048. engine.setState(true, 0, false, true);
  10049. }
  10050. // Draw
  10051. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10052. if (_this.forceBackFacesOnly) {
  10053. engine.setState(true, 0, false, false);
  10054. }
  10055. }
  10056. else {
  10057. // Need to reset refresh rate of the shadowMap
  10058. _this._shadowMap.resetRefreshCounter();
  10059. }
  10060. };
  10061. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10062. var index;
  10063. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10064. renderSubMesh(opaqueSubMeshes.data[index]);
  10065. }
  10066. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10067. renderSubMesh(alphaTestSubMeshes.data[index]);
  10068. }
  10069. if (_this._transparencyShadow) {
  10070. for (index = 0; index < transparentSubMeshes.length; index++) {
  10071. renderSubMesh(transparentSubMeshes.data[index]);
  10072. }
  10073. }
  10074. };
  10075. this._shadowMap.onClear = function (engine) {
  10076. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10077. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10078. }
  10079. else {
  10080. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10081. }
  10082. };
  10083. }
  10084. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10085. // Static
  10086. get: function () {
  10087. return ShadowGenerator._FILTER_NONE;
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10093. get: function () {
  10094. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10095. },
  10096. enumerable: true,
  10097. configurable: true
  10098. });
  10099. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10100. get: function () {
  10101. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10102. },
  10103. enumerable: true,
  10104. configurable: true
  10105. });
  10106. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10107. get: function () {
  10108. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10109. },
  10110. enumerable: true,
  10111. configurable: true
  10112. });
  10113. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10114. get: function () {
  10115. return this._bias;
  10116. },
  10117. set: function (bias) {
  10118. this._bias = bias;
  10119. },
  10120. enumerable: true,
  10121. configurable: true
  10122. });
  10123. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10124. get: function () {
  10125. return this._blurBoxOffset;
  10126. },
  10127. set: function (value) {
  10128. var _this = this;
  10129. if (this._blurBoxOffset === value) {
  10130. return;
  10131. }
  10132. this._blurBoxOffset = value;
  10133. if (this._boxBlurPostprocess) {
  10134. this._boxBlurPostprocess.dispose();
  10135. }
  10136. 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);
  10137. this._boxBlurPostprocess.onApply = function (effect) {
  10138. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10139. };
  10140. },
  10141. enumerable: true,
  10142. configurable: true
  10143. });
  10144. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10145. get: function () {
  10146. return this._filter;
  10147. },
  10148. set: function (value) {
  10149. if (this._filter === value) {
  10150. return;
  10151. }
  10152. this._filter = value;
  10153. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10154. this._shadowMap.anisotropicFilteringLevel = 16;
  10155. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10156. }
  10157. else {
  10158. this._shadowMap.anisotropicFilteringLevel = 1;
  10159. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10160. }
  10161. },
  10162. enumerable: true,
  10163. configurable: true
  10164. });
  10165. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10166. get: function () {
  10167. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10168. },
  10169. set: function (value) {
  10170. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10176. get: function () {
  10177. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10178. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10179. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10180. },
  10181. set: function (value) {
  10182. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10183. },
  10184. enumerable: true,
  10185. configurable: true
  10186. });
  10187. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10188. get: function () {
  10189. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10190. },
  10191. set: function (value) {
  10192. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10193. },
  10194. enumerable: true,
  10195. configurable: true
  10196. });
  10197. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10198. var defines = [];
  10199. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10200. defines.push("#define VSM");
  10201. }
  10202. if (this.getLight().needCube()) {
  10203. defines.push("#define CUBEMAP");
  10204. }
  10205. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10206. var mesh = subMesh.getMesh();
  10207. var material = subMesh.getMaterial();
  10208. // Alpha test
  10209. if (material && material.needAlphaTesting()) {
  10210. defines.push("#define ALPHATEST");
  10211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10212. attribs.push(BABYLON.VertexBuffer.UVKind);
  10213. defines.push("#define UV1");
  10214. }
  10215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10216. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10217. defines.push("#define UV2");
  10218. }
  10219. }
  10220. // Bones
  10221. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10222. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10223. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10224. if (mesh.numBoneInfluencers > 4) {
  10225. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10226. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10227. }
  10228. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10229. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10230. }
  10231. else {
  10232. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10233. }
  10234. // Instances
  10235. if (useInstances) {
  10236. defines.push("#define INSTANCES");
  10237. attribs.push("world0");
  10238. attribs.push("world1");
  10239. attribs.push("world2");
  10240. attribs.push("world3");
  10241. }
  10242. // Get correct effect
  10243. var join = defines.join("\n");
  10244. if (this._cachedDefines !== join) {
  10245. this._cachedDefines = join;
  10246. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10247. }
  10248. return this._effect.isReady();
  10249. };
  10250. ShadowGenerator.prototype.getShadowMap = function () {
  10251. return this._shadowMap;
  10252. };
  10253. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10254. if (this._shadowMap2) {
  10255. return this._shadowMap2;
  10256. }
  10257. return this._shadowMap;
  10258. };
  10259. ShadowGenerator.prototype.getLight = function () {
  10260. return this._light;
  10261. };
  10262. // Methods
  10263. ShadowGenerator.prototype.getTransformMatrix = function () {
  10264. var scene = this._scene;
  10265. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10266. return this._transformMatrix;
  10267. }
  10268. this._currentRenderID = scene.getRenderId();
  10269. this._currentFaceIndexCache = this._currentFaceIndex;
  10270. var lightPosition = this._light.position;
  10271. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10272. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10273. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10274. }
  10275. if (this._light.computeTransformedPosition()) {
  10276. lightPosition = this._light.transformedPosition;
  10277. }
  10278. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10279. this._cachedPosition = lightPosition.clone();
  10280. this._cachedDirection = this._lightDirection.clone();
  10281. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10282. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10283. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10284. }
  10285. return this._transformMatrix;
  10286. };
  10287. ShadowGenerator.prototype.getDarkness = function () {
  10288. return this._darkness;
  10289. };
  10290. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10291. if (darkness >= 1.0)
  10292. this._darkness = 1.0;
  10293. else if (darkness <= 0.0)
  10294. this._darkness = 0.0;
  10295. else
  10296. this._darkness = darkness;
  10297. };
  10298. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10299. this._transparencyShadow = hasShadow;
  10300. };
  10301. ShadowGenerator.prototype._packHalf = function (depth) {
  10302. var scale = depth * 255.0;
  10303. var fract = scale - Math.floor(scale);
  10304. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10305. };
  10306. ShadowGenerator.prototype.dispose = function () {
  10307. this._shadowMap.dispose();
  10308. if (this._shadowMap2) {
  10309. this._shadowMap2.dispose();
  10310. }
  10311. if (this._downSamplePostprocess) {
  10312. this._downSamplePostprocess.dispose();
  10313. }
  10314. if (this._boxBlurPostprocess) {
  10315. this._boxBlurPostprocess.dispose();
  10316. }
  10317. };
  10318. ShadowGenerator.prototype.serialize = function () {
  10319. var serializationObject = {};
  10320. serializationObject.lightId = this._light.id;
  10321. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10322. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10323. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10324. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10325. serializationObject.renderList = [];
  10326. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10327. var mesh = this.getShadowMap().renderList[meshIndex];
  10328. serializationObject.renderList.push(mesh.id);
  10329. }
  10330. return serializationObject;
  10331. };
  10332. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10333. //casting to point light, as light is missing the position attr and typescript complains.
  10334. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10335. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10336. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10337. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10338. meshes.forEach(function (mesh) {
  10339. shadowGenerator.getShadowMap().renderList.push(mesh);
  10340. });
  10341. }
  10342. if (parsedShadowGenerator.usePoissonSampling) {
  10343. shadowGenerator.usePoissonSampling = true;
  10344. }
  10345. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10346. shadowGenerator.useVarianceShadowMap = true;
  10347. }
  10348. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10349. shadowGenerator.useBlurVarianceShadowMap = true;
  10350. if (parsedShadowGenerator.blurScale) {
  10351. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10352. }
  10353. if (parsedShadowGenerator.blurBoxOffset) {
  10354. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10355. }
  10356. }
  10357. if (parsedShadowGenerator.bias !== undefined) {
  10358. shadowGenerator.bias = parsedShadowGenerator.bias;
  10359. }
  10360. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10361. return shadowGenerator;
  10362. };
  10363. ShadowGenerator._FILTER_NONE = 0;
  10364. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10365. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10366. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10367. return ShadowGenerator;
  10368. })();
  10369. BABYLON.ShadowGenerator = ShadowGenerator;
  10370. })(BABYLON || (BABYLON = {}));
  10371. var BABYLON;
  10372. (function (BABYLON) {
  10373. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10374. if (boxMin.x > sphereCenter.x + sphereRadius)
  10375. return false;
  10376. if (sphereCenter.x - sphereRadius > boxMax.x)
  10377. return false;
  10378. if (boxMin.y > sphereCenter.y + sphereRadius)
  10379. return false;
  10380. if (sphereCenter.y - sphereRadius > boxMax.y)
  10381. return false;
  10382. if (boxMin.z > sphereCenter.z + sphereRadius)
  10383. return false;
  10384. if (sphereCenter.z - sphereRadius > boxMax.z)
  10385. return false;
  10386. return true;
  10387. };
  10388. var getLowestRoot = function (a, b, c, maxR) {
  10389. var determinant = b * b - 4.0 * a * c;
  10390. var result = { root: 0, found: false };
  10391. if (determinant < 0)
  10392. return result;
  10393. var sqrtD = Math.sqrt(determinant);
  10394. var r1 = (-b - sqrtD) / (2.0 * a);
  10395. var r2 = (-b + sqrtD) / (2.0 * a);
  10396. if (r1 > r2) {
  10397. var temp = r2;
  10398. r2 = r1;
  10399. r1 = temp;
  10400. }
  10401. if (r1 > 0 && r1 < maxR) {
  10402. result.root = r1;
  10403. result.found = true;
  10404. return result;
  10405. }
  10406. if (r2 > 0 && r2 < maxR) {
  10407. result.root = r2;
  10408. result.found = true;
  10409. return result;
  10410. }
  10411. return result;
  10412. };
  10413. var Collider = (function () {
  10414. function Collider() {
  10415. this.radius = new BABYLON.Vector3(1, 1, 1);
  10416. this.retry = 0;
  10417. this.basePointWorld = BABYLON.Vector3.Zero();
  10418. this.velocityWorld = BABYLON.Vector3.Zero();
  10419. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10420. this._collisionPoint = BABYLON.Vector3.Zero();
  10421. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10422. this._tempVector = BABYLON.Vector3.Zero();
  10423. this._tempVector2 = BABYLON.Vector3.Zero();
  10424. this._tempVector3 = BABYLON.Vector3.Zero();
  10425. this._tempVector4 = BABYLON.Vector3.Zero();
  10426. this._edge = BABYLON.Vector3.Zero();
  10427. this._baseToVertex = BABYLON.Vector3.Zero();
  10428. this._destinationPoint = BABYLON.Vector3.Zero();
  10429. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10430. this._displacementVector = BABYLON.Vector3.Zero();
  10431. }
  10432. // Methods
  10433. Collider.prototype._initialize = function (source, dir, e) {
  10434. this.velocity = dir;
  10435. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10436. this.basePoint = source;
  10437. source.multiplyToRef(this.radius, this.basePointWorld);
  10438. dir.multiplyToRef(this.radius, this.velocityWorld);
  10439. this.velocityWorldLength = this.velocityWorld.length();
  10440. this.epsilon = e;
  10441. this.collisionFound = false;
  10442. };
  10443. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10444. pa.subtractToRef(point, this._tempVector);
  10445. pb.subtractToRef(point, this._tempVector2);
  10446. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10447. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10448. if (d < 0)
  10449. return false;
  10450. pc.subtractToRef(point, this._tempVector3);
  10451. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10452. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10453. if (d < 0)
  10454. return false;
  10455. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10456. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10457. return d >= 0;
  10458. };
  10459. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10460. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10461. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10462. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10463. return false;
  10464. }
  10465. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10466. return false;
  10467. return true;
  10468. };
  10469. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10470. var t0;
  10471. var embeddedInPlane = false;
  10472. //defensive programming, actually not needed.
  10473. if (!trianglePlaneArray) {
  10474. trianglePlaneArray = [];
  10475. }
  10476. if (!trianglePlaneArray[faceIndex]) {
  10477. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10478. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10479. }
  10480. var trianglePlane = trianglePlaneArray[faceIndex];
  10481. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10482. return;
  10483. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10484. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10485. if (normalDotVelocity == 0) {
  10486. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10487. return;
  10488. embeddedInPlane = true;
  10489. t0 = 0;
  10490. }
  10491. else {
  10492. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10493. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10494. if (t0 > t1) {
  10495. var temp = t1;
  10496. t1 = t0;
  10497. t0 = temp;
  10498. }
  10499. if (t0 > 1.0 || t1 < 0.0)
  10500. return;
  10501. if (t0 < 0)
  10502. t0 = 0;
  10503. if (t0 > 1.0)
  10504. t0 = 1.0;
  10505. }
  10506. this._collisionPoint.copyFromFloats(0, 0, 0);
  10507. var found = false;
  10508. var t = 1.0;
  10509. if (!embeddedInPlane) {
  10510. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10511. this.velocity.scaleToRef(t0, this._tempVector);
  10512. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10513. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10514. found = true;
  10515. t = t0;
  10516. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10517. }
  10518. }
  10519. if (!found) {
  10520. var velocitySquaredLength = this.velocity.lengthSquared();
  10521. var a = velocitySquaredLength;
  10522. this.basePoint.subtractToRef(p1, this._tempVector);
  10523. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10524. var c = this._tempVector.lengthSquared() - 1.0;
  10525. var lowestRoot = getLowestRoot(a, b, c, t);
  10526. if (lowestRoot.found) {
  10527. t = lowestRoot.root;
  10528. found = true;
  10529. this._collisionPoint.copyFrom(p1);
  10530. }
  10531. this.basePoint.subtractToRef(p2, this._tempVector);
  10532. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10533. c = this._tempVector.lengthSquared() - 1.0;
  10534. lowestRoot = getLowestRoot(a, b, c, t);
  10535. if (lowestRoot.found) {
  10536. t = lowestRoot.root;
  10537. found = true;
  10538. this._collisionPoint.copyFrom(p2);
  10539. }
  10540. this.basePoint.subtractToRef(p3, this._tempVector);
  10541. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10542. c = this._tempVector.lengthSquared() - 1.0;
  10543. lowestRoot = getLowestRoot(a, b, c, t);
  10544. if (lowestRoot.found) {
  10545. t = lowestRoot.root;
  10546. found = true;
  10547. this._collisionPoint.copyFrom(p3);
  10548. }
  10549. p2.subtractToRef(p1, this._edge);
  10550. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10551. var edgeSquaredLength = this._edge.lengthSquared();
  10552. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10553. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10554. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10555. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10556. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10557. lowestRoot = getLowestRoot(a, b, c, t);
  10558. if (lowestRoot.found) {
  10559. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10560. if (f >= 0.0 && f <= 1.0) {
  10561. t = lowestRoot.root;
  10562. found = true;
  10563. this._edge.scaleInPlace(f);
  10564. p1.addToRef(this._edge, this._collisionPoint);
  10565. }
  10566. }
  10567. p3.subtractToRef(p2, this._edge);
  10568. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10569. edgeSquaredLength = this._edge.lengthSquared();
  10570. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10571. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10572. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10573. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10574. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10575. lowestRoot = getLowestRoot(a, b, c, t);
  10576. if (lowestRoot.found) {
  10577. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10578. if (f >= 0.0 && f <= 1.0) {
  10579. t = lowestRoot.root;
  10580. found = true;
  10581. this._edge.scaleInPlace(f);
  10582. p2.addToRef(this._edge, this._collisionPoint);
  10583. }
  10584. }
  10585. p1.subtractToRef(p3, this._edge);
  10586. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10587. edgeSquaredLength = this._edge.lengthSquared();
  10588. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10589. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10590. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10591. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10592. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10593. lowestRoot = getLowestRoot(a, b, c, t);
  10594. if (lowestRoot.found) {
  10595. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10596. if (f >= 0.0 && f <= 1.0) {
  10597. t = lowestRoot.root;
  10598. found = true;
  10599. this._edge.scaleInPlace(f);
  10600. p3.addToRef(this._edge, this._collisionPoint);
  10601. }
  10602. }
  10603. }
  10604. if (found) {
  10605. var distToCollision = t * this.velocity.length();
  10606. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10607. if (!this.intersectionPoint) {
  10608. this.intersectionPoint = this._collisionPoint.clone();
  10609. }
  10610. else {
  10611. this.intersectionPoint.copyFrom(this._collisionPoint);
  10612. }
  10613. this.nearestDistance = distToCollision;
  10614. this.collisionFound = true;
  10615. }
  10616. }
  10617. };
  10618. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10619. for (var i = indexStart; i < indexEnd; i += 3) {
  10620. var p1 = pts[indices[i] - decal];
  10621. var p2 = pts[indices[i + 1] - decal];
  10622. var p3 = pts[indices[i + 2] - decal];
  10623. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10624. }
  10625. };
  10626. Collider.prototype._getResponse = function (pos, vel) {
  10627. pos.addToRef(vel, this._destinationPoint);
  10628. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10629. this.basePoint.addToRef(vel, pos);
  10630. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10631. this._slidePlaneNormal.normalize();
  10632. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10633. pos.addInPlace(this._displacementVector);
  10634. this.intersectionPoint.addInPlace(this._displacementVector);
  10635. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10636. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10637. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10638. };
  10639. return Collider;
  10640. })();
  10641. BABYLON.Collider = Collider;
  10642. })(BABYLON || (BABYLON = {}));
  10643. var BABYLON;
  10644. (function (BABYLON) {
  10645. //WebWorker code will be inserted to this variable.
  10646. BABYLON.CollisionWorker = "";
  10647. (function (WorkerTaskType) {
  10648. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10649. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10650. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10651. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10652. var WorkerTaskType = BABYLON.WorkerTaskType;
  10653. (function (WorkerReplyType) {
  10654. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10655. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10656. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10657. var WorkerReplyType = BABYLON.WorkerReplyType;
  10658. var CollisionCoordinatorWorker = (function () {
  10659. function CollisionCoordinatorWorker() {
  10660. var _this = this;
  10661. this._scaledPosition = BABYLON.Vector3.Zero();
  10662. this._scaledVelocity = BABYLON.Vector3.Zero();
  10663. this.onMeshUpdated = function (mesh) {
  10664. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10665. };
  10666. this.onGeometryUpdated = function (geometry) {
  10667. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10668. };
  10669. this._afterRender = function () {
  10670. if (!_this._init)
  10671. return;
  10672. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10673. return;
  10674. }
  10675. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10676. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10677. if (_this._runningUpdated > 4) {
  10678. return;
  10679. }
  10680. ++_this._runningUpdated;
  10681. var payload = {
  10682. updatedMeshes: _this._addUpdateMeshesList,
  10683. updatedGeometries: _this._addUpdateGeometriesList,
  10684. removedGeometries: _this._toRemoveGeometryArray,
  10685. removedMeshes: _this._toRemoveMeshesArray
  10686. };
  10687. var message = {
  10688. payload: payload,
  10689. taskType: WorkerTaskType.UPDATE
  10690. };
  10691. var serializable = [];
  10692. for (var id in payload.updatedGeometries) {
  10693. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10694. //prepare transferables
  10695. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10696. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10697. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10698. }
  10699. }
  10700. _this._worker.postMessage(message, serializable);
  10701. _this._addUpdateMeshesList = {};
  10702. _this._addUpdateGeometriesList = {};
  10703. _this._toRemoveGeometryArray = [];
  10704. _this._toRemoveMeshesArray = [];
  10705. };
  10706. this._onMessageFromWorker = function (e) {
  10707. var returnData = e.data;
  10708. if (returnData.error != WorkerReplyType.SUCCESS) {
  10709. //TODO what errors can be returned from the worker?
  10710. BABYLON.Tools.Warn("error returned from worker!");
  10711. return;
  10712. }
  10713. switch (returnData.taskType) {
  10714. case WorkerTaskType.INIT:
  10715. _this._init = true;
  10716. //Update the worked with ALL of the scene's current state
  10717. _this._scene.meshes.forEach(function (mesh) {
  10718. _this.onMeshAdded(mesh);
  10719. });
  10720. _this._scene.getGeometries().forEach(function (geometry) {
  10721. _this.onGeometryAdded(geometry);
  10722. });
  10723. break;
  10724. case WorkerTaskType.UPDATE:
  10725. _this._runningUpdated--;
  10726. break;
  10727. case WorkerTaskType.COLLIDE:
  10728. _this._runningCollisionTask = false;
  10729. var returnPayload = returnData.payload;
  10730. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10731. return;
  10732. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10733. //cleanup
  10734. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10735. break;
  10736. }
  10737. };
  10738. this._collisionsCallbackArray = [];
  10739. this._init = false;
  10740. this._runningUpdated = 0;
  10741. this._runningCollisionTask = false;
  10742. this._addUpdateMeshesList = {};
  10743. this._addUpdateGeometriesList = {};
  10744. this._toRemoveGeometryArray = [];
  10745. this._toRemoveMeshesArray = [];
  10746. }
  10747. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10748. if (!this._init)
  10749. return;
  10750. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10751. return;
  10752. position.divideToRef(collider.radius, this._scaledPosition);
  10753. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10754. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10755. var payload = {
  10756. collider: {
  10757. position: this._scaledPosition.asArray(),
  10758. velocity: this._scaledVelocity.asArray(),
  10759. radius: collider.radius.asArray()
  10760. },
  10761. collisionId: collisionIndex,
  10762. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10763. maximumRetry: maximumRetry
  10764. };
  10765. var message = {
  10766. payload: payload,
  10767. taskType: WorkerTaskType.COLLIDE
  10768. };
  10769. this._worker.postMessage(message);
  10770. };
  10771. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10772. this._scene = scene;
  10773. this._scene.registerAfterRender(this._afterRender);
  10774. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10775. this._worker = new Worker(workerUrl);
  10776. this._worker.onmessage = this._onMessageFromWorker;
  10777. var message = {
  10778. payload: {},
  10779. taskType: WorkerTaskType.INIT
  10780. };
  10781. this._worker.postMessage(message);
  10782. };
  10783. CollisionCoordinatorWorker.prototype.destroy = function () {
  10784. this._scene.unregisterAfterRender(this._afterRender);
  10785. this._worker.terminate();
  10786. };
  10787. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10788. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10789. this.onMeshUpdated(mesh);
  10790. };
  10791. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10792. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10793. };
  10794. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10795. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10796. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10797. this.onGeometryUpdated(geometry);
  10798. };
  10799. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10800. this._toRemoveGeometryArray.push(geometry.id);
  10801. };
  10802. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10803. var submeshes = [];
  10804. if (mesh.subMeshes) {
  10805. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10806. return {
  10807. position: idx,
  10808. verticesStart: sm.verticesStart,
  10809. verticesCount: sm.verticesCount,
  10810. indexStart: sm.indexStart,
  10811. indexCount: sm.indexCount,
  10812. hasMaterial: !!sm.getMaterial(),
  10813. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10814. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10815. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10816. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10817. };
  10818. });
  10819. }
  10820. var geometryId = null;
  10821. if (mesh instanceof BABYLON.Mesh) {
  10822. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10823. }
  10824. else if (mesh instanceof BABYLON.InstancedMesh) {
  10825. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10826. }
  10827. return {
  10828. uniqueId: mesh.uniqueId,
  10829. id: mesh.id,
  10830. name: mesh.name,
  10831. geometryId: geometryId,
  10832. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10833. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10834. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10835. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10836. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10837. subMeshes: submeshes,
  10838. checkCollisions: mesh.checkCollisions
  10839. };
  10840. };
  10841. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10842. return {
  10843. id: geometry.id,
  10844. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10845. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10846. indices: new Int32Array(geometry.getIndices() || []),
  10847. };
  10848. };
  10849. return CollisionCoordinatorWorker;
  10850. })();
  10851. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10852. var CollisionCoordinatorLegacy = (function () {
  10853. function CollisionCoordinatorLegacy() {
  10854. this._scaledPosition = BABYLON.Vector3.Zero();
  10855. this._scaledVelocity = BABYLON.Vector3.Zero();
  10856. this._finalPosition = BABYLON.Vector3.Zero();
  10857. }
  10858. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10859. position.divideToRef(collider.radius, this._scaledPosition);
  10860. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10861. collider.collidedMesh = null;
  10862. collider.retry = 0;
  10863. collider.initialVelocity = this._scaledVelocity;
  10864. collider.initialPosition = this._scaledPosition;
  10865. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10866. this._finalPosition.multiplyInPlace(collider.radius);
  10867. //run the callback
  10868. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10869. };
  10870. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10871. this._scene = scene;
  10872. };
  10873. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10874. //Legacy need no destruction method.
  10875. };
  10876. //No update in legacy mode
  10877. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10878. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10879. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10880. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10881. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10882. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10883. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10884. if (excludedMesh === void 0) { excludedMesh = null; }
  10885. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10886. if (collider.retry >= maximumRetry) {
  10887. finalPosition.copyFrom(position);
  10888. return;
  10889. }
  10890. collider._initialize(position, velocity, closeDistance);
  10891. // Check all meshes
  10892. for (var index = 0; index < this._scene.meshes.length; index++) {
  10893. var mesh = this._scene.meshes[index];
  10894. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10895. mesh._checkCollision(collider);
  10896. }
  10897. }
  10898. if (!collider.collisionFound) {
  10899. position.addToRef(velocity, finalPosition);
  10900. return;
  10901. }
  10902. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10903. collider._getResponse(position, velocity);
  10904. }
  10905. if (velocity.length() <= closeDistance) {
  10906. finalPosition.copyFrom(position);
  10907. return;
  10908. }
  10909. collider.retry++;
  10910. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10911. };
  10912. return CollisionCoordinatorLegacy;
  10913. })();
  10914. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10915. })(BABYLON || (BABYLON = {}));
  10916. var BABYLON;
  10917. (function (BABYLON) {
  10918. var Camera = (function (_super) {
  10919. __extends(Camera, _super);
  10920. function Camera(name, position, scene) {
  10921. _super.call(this, name, scene);
  10922. this.upVector = BABYLON.Vector3.Up();
  10923. this.orthoLeft = null;
  10924. this.orthoRight = null;
  10925. this.orthoBottom = null;
  10926. this.orthoTop = null;
  10927. this.fov = 0.8;
  10928. this.minZ = 1.0;
  10929. this.maxZ = 10000.0;
  10930. this.inertia = 0.9;
  10931. this.mode = Camera.PERSPECTIVE_CAMERA;
  10932. this.isIntermediate = false;
  10933. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10934. this.layerMask = 0x0FFFFFFF;
  10935. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10936. // Camera rig members
  10937. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10938. this._rigCameras = new Array();
  10939. // Cache
  10940. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10941. this._projectionMatrix = new BABYLON.Matrix();
  10942. this._postProcesses = new Array();
  10943. this._postProcessesTakenIndices = [];
  10944. this._activeMeshes = new BABYLON.SmartArray(256);
  10945. this._globalPosition = BABYLON.Vector3.Zero();
  10946. scene.addCamera(this);
  10947. if (!scene.activeCamera) {
  10948. scene.activeCamera = this;
  10949. }
  10950. this.position = position;
  10951. }
  10952. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10953. get: function () {
  10954. return Camera._PERSPECTIVE_CAMERA;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10960. get: function () {
  10961. return Camera._ORTHOGRAPHIC_CAMERA;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10967. get: function () {
  10968. return Camera._FOVMODE_VERTICAL_FIXED;
  10969. },
  10970. enumerable: true,
  10971. configurable: true
  10972. });
  10973. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10974. get: function () {
  10975. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10981. get: function () {
  10982. return Camera._RIG_MODE_NONE;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10988. get: function () {
  10989. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10995. get: function () {
  10996. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11002. get: function () {
  11003. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11009. get: function () {
  11010. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11016. get: function () {
  11017. return Camera._RIG_MODE_VR;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. /**
  11023. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11024. */
  11025. Camera.prototype.toString = function (fullDetails) {
  11026. var ret = "Name: " + this.name;
  11027. ret += ", type: " + this.getTypeName();
  11028. if (this.animations) {
  11029. for (var i = 0; i < this.animations.length; i++) {
  11030. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11031. }
  11032. }
  11033. if (fullDetails) {
  11034. }
  11035. return ret;
  11036. };
  11037. Object.defineProperty(Camera.prototype, "globalPosition", {
  11038. get: function () {
  11039. return this._globalPosition;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Camera.prototype.getActiveMeshes = function () {
  11045. return this._activeMeshes;
  11046. };
  11047. Camera.prototype.isActiveMesh = function (mesh) {
  11048. return (this._activeMeshes.indexOf(mesh) !== -1);
  11049. };
  11050. //Cache
  11051. Camera.prototype._initCache = function () {
  11052. _super.prototype._initCache.call(this);
  11053. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11054. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11055. this._cache.mode = undefined;
  11056. this._cache.minZ = undefined;
  11057. this._cache.maxZ = undefined;
  11058. this._cache.fov = undefined;
  11059. this._cache.aspectRatio = undefined;
  11060. this._cache.orthoLeft = undefined;
  11061. this._cache.orthoRight = undefined;
  11062. this._cache.orthoBottom = undefined;
  11063. this._cache.orthoTop = undefined;
  11064. this._cache.renderWidth = undefined;
  11065. this._cache.renderHeight = undefined;
  11066. };
  11067. Camera.prototype._updateCache = function (ignoreParentClass) {
  11068. if (!ignoreParentClass) {
  11069. _super.prototype._updateCache.call(this);
  11070. }
  11071. var engine = this.getEngine();
  11072. this._cache.position.copyFrom(this.position);
  11073. this._cache.upVector.copyFrom(this.upVector);
  11074. this._cache.mode = this.mode;
  11075. this._cache.minZ = this.minZ;
  11076. this._cache.maxZ = this.maxZ;
  11077. this._cache.fov = this.fov;
  11078. this._cache.aspectRatio = engine.getAspectRatio(this);
  11079. this._cache.orthoLeft = this.orthoLeft;
  11080. this._cache.orthoRight = this.orthoRight;
  11081. this._cache.orthoBottom = this.orthoBottom;
  11082. this._cache.orthoTop = this.orthoTop;
  11083. this._cache.renderWidth = engine.getRenderWidth();
  11084. this._cache.renderHeight = engine.getRenderHeight();
  11085. };
  11086. Camera.prototype._updateFromScene = function () {
  11087. this.updateCache();
  11088. this._update();
  11089. };
  11090. // Synchronized
  11091. Camera.prototype._isSynchronized = function () {
  11092. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11093. };
  11094. Camera.prototype._isSynchronizedViewMatrix = function () {
  11095. if (!_super.prototype._isSynchronized.call(this))
  11096. return false;
  11097. return this._cache.position.equals(this.position)
  11098. && this._cache.upVector.equals(this.upVector)
  11099. && this.isSynchronizedWithParent();
  11100. };
  11101. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11102. var check = this._cache.mode === this.mode
  11103. && this._cache.minZ === this.minZ
  11104. && this._cache.maxZ === this.maxZ;
  11105. if (!check) {
  11106. return false;
  11107. }
  11108. var engine = this.getEngine();
  11109. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11110. check = this._cache.fov === this.fov
  11111. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11112. }
  11113. else {
  11114. check = this._cache.orthoLeft === this.orthoLeft
  11115. && this._cache.orthoRight === this.orthoRight
  11116. && this._cache.orthoBottom === this.orthoBottom
  11117. && this._cache.orthoTop === this.orthoTop
  11118. && this._cache.renderWidth === engine.getRenderWidth()
  11119. && this._cache.renderHeight === engine.getRenderHeight();
  11120. }
  11121. return check;
  11122. };
  11123. // Controls
  11124. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11125. };
  11126. Camera.prototype.detachControl = function (element) {
  11127. };
  11128. Camera.prototype._update = function () {
  11129. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11130. this._updateRigCameras();
  11131. }
  11132. this._checkInputs();
  11133. };
  11134. Camera.prototype._checkInputs = function () {
  11135. };
  11136. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11137. if (insertAt === void 0) { insertAt = null; }
  11138. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11139. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11140. return 0;
  11141. }
  11142. if (insertAt == null || insertAt < 0) {
  11143. this._postProcesses.push(postProcess);
  11144. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11145. return this._postProcesses.length - 1;
  11146. }
  11147. var add = 0;
  11148. var i;
  11149. var start;
  11150. if (this._postProcesses[insertAt]) {
  11151. start = this._postProcesses.length - 1;
  11152. for (i = start; i >= insertAt + 1; --i) {
  11153. this._postProcesses[i + 1] = this._postProcesses[i];
  11154. }
  11155. add = 1;
  11156. }
  11157. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11158. if (this._postProcessesTakenIndices[i] < insertAt) {
  11159. continue;
  11160. }
  11161. start = this._postProcessesTakenIndices.length - 1;
  11162. for (var j = start; j >= i; --j) {
  11163. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11164. }
  11165. this._postProcessesTakenIndices[i] = insertAt;
  11166. break;
  11167. }
  11168. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11169. this._postProcessesTakenIndices.push(insertAt);
  11170. }
  11171. var result = insertAt + add;
  11172. this._postProcesses[result] = postProcess;
  11173. return result;
  11174. };
  11175. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11176. if (atIndices === void 0) { atIndices = null; }
  11177. var result = [];
  11178. var i;
  11179. var index;
  11180. if (!atIndices) {
  11181. var length = this._postProcesses.length;
  11182. for (i = 0; i < length; i++) {
  11183. if (this._postProcesses[i] !== postProcess) {
  11184. continue;
  11185. }
  11186. delete this._postProcesses[i];
  11187. index = this._postProcessesTakenIndices.indexOf(i);
  11188. this._postProcessesTakenIndices.splice(index, 1);
  11189. }
  11190. }
  11191. else {
  11192. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11193. for (i = 0; i < atIndices.length; i++) {
  11194. var foundPostProcess = this._postProcesses[atIndices[i]];
  11195. if (foundPostProcess !== postProcess) {
  11196. result.push(i);
  11197. continue;
  11198. }
  11199. delete this._postProcesses[atIndices[i]];
  11200. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11201. this._postProcessesTakenIndices.splice(index, 1);
  11202. }
  11203. }
  11204. return result;
  11205. };
  11206. Camera.prototype.getWorldMatrix = function () {
  11207. if (!this._worldMatrix) {
  11208. this._worldMatrix = BABYLON.Matrix.Identity();
  11209. }
  11210. var viewMatrix = this.getViewMatrix();
  11211. viewMatrix.invertToRef(this._worldMatrix);
  11212. return this._worldMatrix;
  11213. };
  11214. Camera.prototype._getViewMatrix = function () {
  11215. return BABYLON.Matrix.Identity();
  11216. };
  11217. Camera.prototype.getViewMatrix = function (force) {
  11218. this._computedViewMatrix = this._computeViewMatrix(force);
  11219. if (!force && this._isSynchronizedViewMatrix()) {
  11220. return this._computedViewMatrix;
  11221. }
  11222. if (!this.parent || !this.parent.getWorldMatrix) {
  11223. this._globalPosition.copyFrom(this.position);
  11224. }
  11225. else {
  11226. if (!this._worldMatrix) {
  11227. this._worldMatrix = BABYLON.Matrix.Identity();
  11228. }
  11229. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11230. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11231. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11232. this._computedViewMatrix.invert();
  11233. this._markSyncedWithParent();
  11234. }
  11235. this._currentRenderId = this.getScene().getRenderId();
  11236. return this._computedViewMatrix;
  11237. };
  11238. Camera.prototype._computeViewMatrix = function (force) {
  11239. if (!force && this._isSynchronizedViewMatrix()) {
  11240. return this._computedViewMatrix;
  11241. }
  11242. this._computedViewMatrix = this._getViewMatrix();
  11243. this._currentRenderId = this.getScene().getRenderId();
  11244. return this._computedViewMatrix;
  11245. };
  11246. Camera.prototype.getProjectionMatrix = function (force) {
  11247. if (!force && this._isSynchronizedProjectionMatrix()) {
  11248. return this._projectionMatrix;
  11249. }
  11250. var engine = this.getEngine();
  11251. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11252. if (this.minZ <= 0) {
  11253. this.minZ = 0.1;
  11254. }
  11255. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11256. return this._projectionMatrix;
  11257. }
  11258. var halfWidth = engine.getRenderWidth() / 2.0;
  11259. var halfHeight = engine.getRenderHeight() / 2.0;
  11260. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11261. return this._projectionMatrix;
  11262. };
  11263. Camera.prototype.dispose = function () {
  11264. // Animations
  11265. this.getScene().stopAnimation(this);
  11266. // Remove from scene
  11267. this.getScene().removeCamera(this);
  11268. while (this._rigCameras.length > 0) {
  11269. this._rigCameras.pop().dispose();
  11270. }
  11271. // Postprocesses
  11272. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11273. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11274. }
  11275. _super.prototype.dispose.call(this);
  11276. };
  11277. // ---- Camera rigs section ----
  11278. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11279. while (this._rigCameras.length > 0) {
  11280. this._rigCameras.pop().dispose();
  11281. }
  11282. this.cameraRigMode = mode;
  11283. this._cameraRigParams = {};
  11284. switch (this.cameraRigMode) {
  11285. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11286. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11287. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11288. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11289. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11290. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11291. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11292. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11293. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11294. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11295. break;
  11296. }
  11297. var postProcesses = new Array();
  11298. switch (this.cameraRigMode) {
  11299. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11300. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11301. this._rigCameras[0].isIntermediate = true;
  11302. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11303. postProcesses[1].onApply = function (effect) {
  11304. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11305. };
  11306. break;
  11307. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11308. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11309. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11310. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11311. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11312. var secondCamIndex = 1 - firstCamIndex;
  11313. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11314. this._rigCameras[firstCamIndex].isIntermediate = true;
  11315. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11316. break;
  11317. case Camera.RIG_MODE_VR:
  11318. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11319. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11320. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11321. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11322. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11323. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11324. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11325. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11326. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11327. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11328. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11329. if (metrics.compensateDistortion) {
  11330. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11331. }
  11332. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11333. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11334. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11335. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11336. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11337. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11338. if (metrics.compensateDistortion) {
  11339. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11340. }
  11341. break;
  11342. }
  11343. this._update();
  11344. };
  11345. Camera.prototype._getVRProjectionMatrix = function () {
  11346. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11347. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11348. return this._projectionMatrix;
  11349. };
  11350. Camera.prototype.setCameraRigParameter = function (name, value) {
  11351. this._cameraRigParams[name] = value;
  11352. //provisionnally:
  11353. if (name === "interaxialDistance") {
  11354. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11355. }
  11356. };
  11357. /**
  11358. * May needs to be overridden by children so sub has required properties to be copied
  11359. */
  11360. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11361. return null;
  11362. };
  11363. /**
  11364. * May needs to be overridden by children
  11365. */
  11366. Camera.prototype._updateRigCameras = function () {
  11367. for (var i = 0; i < this._rigCameras.length; i++) {
  11368. this._rigCameras[i].minZ = this.minZ;
  11369. this._rigCameras[i].maxZ = this.maxZ;
  11370. this._rigCameras[i].fov = this.fov;
  11371. }
  11372. // only update viewport when ANAGLYPH
  11373. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11374. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11375. }
  11376. };
  11377. Camera.prototype._setupInputs = function () {
  11378. };
  11379. Camera.prototype.serialize = function () {
  11380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11381. // Type
  11382. serializationObject.type = this.getTypeName();
  11383. // Parent
  11384. if (this.parent) {
  11385. serializationObject.parentId = this.parent.id;
  11386. }
  11387. if (this.inputs) {
  11388. this.inputs.serialize(serializationObject);
  11389. }
  11390. // Animations
  11391. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11392. serializationObject.ranges = this.serializeAnimationRanges();
  11393. return serializationObject;
  11394. };
  11395. Camera.prototype.getTypeName = function () {
  11396. return "Camera";
  11397. };
  11398. Camera.prototype.clone = function (name) {
  11399. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11400. };
  11401. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11402. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11403. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11404. switch (type) {
  11405. case "ArcRotateCamera":
  11406. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11407. case "DeviceOrientationCamera":
  11408. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11409. case "FollowCamera":
  11410. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11411. case "ArcFollowCamera":
  11412. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11413. case "GamepadCamera":
  11414. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11415. case "TouchCamera":
  11416. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11417. case "VirtualJoysticksCamera":
  11418. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11419. case "WebVRFreeCamera":
  11420. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11421. case "VRDeviceOrientationFreeCamera":
  11422. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11423. case "AnaglyphArcRotateCamera":
  11424. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11425. case "AnaglyphFreeCamera":
  11426. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11427. case "AnaglyphGamepadCamera":
  11428. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11429. case "AnaglyphUniversalCamera":
  11430. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11431. case "StereoscopicArcRotateCamera":
  11432. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11433. case "StereoscopicFreeCamera":
  11434. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11435. case "StereoscopicGamepadCamera":
  11436. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11437. case "StereoscopicUniversalCamera":
  11438. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11439. case "FreeCamera":
  11440. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11441. default:
  11442. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11443. }
  11444. };
  11445. Camera.Parse = function (parsedCamera, scene) {
  11446. var type = parsedCamera.type;
  11447. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11448. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11449. // Parent
  11450. if (parsedCamera.parentId) {
  11451. camera._waitingParentId = parsedCamera.parentId;
  11452. }
  11453. //If camera has an input manager, let it parse inputs settings
  11454. if (camera.inputs) {
  11455. camera.inputs.parse(parsedCamera);
  11456. camera._setupInputs();
  11457. }
  11458. // Target
  11459. if (parsedCamera.target) {
  11460. if (camera.setTarget) {
  11461. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11462. }
  11463. }
  11464. // Apply 3d rig, when found
  11465. if (parsedCamera.cameraRigMode) {
  11466. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11467. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11468. }
  11469. // Animations
  11470. if (parsedCamera.animations) {
  11471. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11472. var parsedAnimation = parsedCamera.animations[animationIndex];
  11473. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11474. }
  11475. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11476. }
  11477. if (parsedCamera.autoAnimate) {
  11478. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11479. }
  11480. return camera;
  11481. };
  11482. // Statics
  11483. Camera._PERSPECTIVE_CAMERA = 0;
  11484. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11485. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11486. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11487. Camera._RIG_MODE_NONE = 0;
  11488. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11489. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11490. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11491. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11492. Camera._RIG_MODE_VR = 20;
  11493. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11494. __decorate([
  11495. BABYLON.serializeAsVector3()
  11496. ], Camera.prototype, "position", void 0);
  11497. __decorate([
  11498. BABYLON.serializeAsVector3()
  11499. ], Camera.prototype, "upVector", void 0);
  11500. __decorate([
  11501. BABYLON.serialize()
  11502. ], Camera.prototype, "orthoLeft", void 0);
  11503. __decorate([
  11504. BABYLON.serialize()
  11505. ], Camera.prototype, "orthoRight", void 0);
  11506. __decorate([
  11507. BABYLON.serialize()
  11508. ], Camera.prototype, "orthoBottom", void 0);
  11509. __decorate([
  11510. BABYLON.serialize()
  11511. ], Camera.prototype, "orthoTop", void 0);
  11512. __decorate([
  11513. BABYLON.serialize()
  11514. ], Camera.prototype, "fov", void 0);
  11515. __decorate([
  11516. BABYLON.serialize()
  11517. ], Camera.prototype, "minZ", void 0);
  11518. __decorate([
  11519. BABYLON.serialize()
  11520. ], Camera.prototype, "maxZ", void 0);
  11521. __decorate([
  11522. BABYLON.serialize()
  11523. ], Camera.prototype, "inertia", void 0);
  11524. __decorate([
  11525. BABYLON.serialize()
  11526. ], Camera.prototype, "mode", void 0);
  11527. __decorate([
  11528. BABYLON.serialize()
  11529. ], Camera.prototype, "layerMask", void 0);
  11530. __decorate([
  11531. BABYLON.serialize()
  11532. ], Camera.prototype, "fovMode", void 0);
  11533. __decorate([
  11534. BABYLON.serialize()
  11535. ], Camera.prototype, "cameraRigMode", void 0);
  11536. __decorate([
  11537. BABYLON.serialize()
  11538. ], Camera.prototype, "interaxialDistance", void 0);
  11539. __decorate([
  11540. BABYLON.serialize()
  11541. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11542. return Camera;
  11543. })(BABYLON.Node);
  11544. BABYLON.Camera = Camera;
  11545. })(BABYLON || (BABYLON = {}));
  11546. var BABYLON;
  11547. (function (BABYLON) {
  11548. BABYLON.CameraInputTypes = {};
  11549. var CameraInputsManager = (function () {
  11550. function CameraInputsManager(camera) {
  11551. this.attached = {};
  11552. this.camera = camera;
  11553. this.checkInputs = function () { };
  11554. }
  11555. CameraInputsManager.prototype.add = function (input) {
  11556. var type = input.getSimpleName();
  11557. if (this.attached[type]) {
  11558. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11559. return;
  11560. }
  11561. this.attached[type] = input;
  11562. input.camera = this.camera;
  11563. //for checkInputs, we are dynamically creating a function
  11564. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11565. if (input.checkInputs) {
  11566. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11567. }
  11568. if (this.attachedElement) {
  11569. input.attachControl(this.attachedElement);
  11570. }
  11571. };
  11572. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11573. for (var cam in this.attached) {
  11574. var input = this.attached[cam];
  11575. if (input === inputToRemove) {
  11576. input.detachControl(this.attachedElement);
  11577. delete this.attached[cam];
  11578. this.rebuildInputCheck();
  11579. }
  11580. }
  11581. };
  11582. CameraInputsManager.prototype.removeByType = function (inputType) {
  11583. for (var cam in this.attached) {
  11584. var input = this.attached[cam];
  11585. if (input.getTypeName() === inputType) {
  11586. input.detachControl(this.attachedElement);
  11587. delete this.attached[cam];
  11588. this.rebuildInputCheck();
  11589. }
  11590. }
  11591. };
  11592. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11593. var current = this.checkInputs;
  11594. return function () {
  11595. current();
  11596. fn();
  11597. };
  11598. };
  11599. CameraInputsManager.prototype.attachInput = function (input) {
  11600. input.attachControl(this.attachedElement, this.noPreventDefault);
  11601. };
  11602. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11603. if (this.attachedElement) {
  11604. return;
  11605. }
  11606. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11607. this.attachedElement = element;
  11608. this.noPreventDefault = noPreventDefault;
  11609. for (var cam in this.attached) {
  11610. var input = this.attached[cam];
  11611. this.attached[cam].attachControl(element, noPreventDefault);
  11612. }
  11613. };
  11614. CameraInputsManager.prototype.detachElement = function (element) {
  11615. if (this.attachedElement !== element) {
  11616. return;
  11617. }
  11618. for (var cam in this.attached) {
  11619. var input = this.attached[cam];
  11620. this.attached[cam].detachControl(element);
  11621. }
  11622. this.attachedElement = null;
  11623. };
  11624. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11625. this.checkInputs = function () { };
  11626. for (var cam in this.attached) {
  11627. var input = this.attached[cam];
  11628. if (input.checkInputs) {
  11629. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11630. }
  11631. }
  11632. };
  11633. CameraInputsManager.prototype.clear = function () {
  11634. if (this.attachedElement) {
  11635. this.detachElement(this.attachedElement);
  11636. }
  11637. this.attached = {};
  11638. this.attachedElement = null;
  11639. this.checkInputs = function () { };
  11640. };
  11641. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11642. var inputs = {};
  11643. for (var cam in this.attached) {
  11644. var input = this.attached[cam];
  11645. var res = BABYLON.SerializationHelper.Serialize(input);
  11646. inputs[input.getTypeName()] = res;
  11647. }
  11648. serializedCamera.inputsmgr = inputs;
  11649. };
  11650. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11651. var parsedInputs = parsedCamera.inputsmgr;
  11652. if (parsedInputs) {
  11653. this.clear();
  11654. for (var n in parsedInputs) {
  11655. var construct = BABYLON.CameraInputTypes[n];
  11656. if (construct) {
  11657. var parsedinput = parsedInputs[n];
  11658. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11659. this.add(input);
  11660. }
  11661. }
  11662. }
  11663. else {
  11664. //2016-03-08 this part is for managing backward compatibility
  11665. for (var n in this.attached) {
  11666. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11667. if (construct) {
  11668. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11669. this.remove(this.attached[n]);
  11670. this.add(input);
  11671. }
  11672. }
  11673. }
  11674. };
  11675. return CameraInputsManager;
  11676. })();
  11677. BABYLON.CameraInputsManager = CameraInputsManager;
  11678. })(BABYLON || (BABYLON = {}));
  11679. var BABYLON;
  11680. (function (BABYLON) {
  11681. var FreeCameraMouseInput = (function () {
  11682. function FreeCameraMouseInput(touchEnabled) {
  11683. if (touchEnabled === void 0) { touchEnabled = true; }
  11684. this.touchEnabled = touchEnabled;
  11685. this.angularSensibility = 2000.0;
  11686. }
  11687. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11688. var _this = this;
  11689. if (!this._pointerInput) {
  11690. var camera = this.camera;
  11691. var engine = this.camera.getEngine();
  11692. this._pointerInput = function (p, s) {
  11693. var evt = p.event;
  11694. if (!_this.touchEnabled && evt.pointerType === "touch") {
  11695. return;
  11696. }
  11697. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11698. try {
  11699. evt.srcElement.setPointerCapture(evt.pointerId);
  11700. }
  11701. catch (e) {
  11702. }
  11703. _this.previousPosition = {
  11704. x: evt.clientX,
  11705. y: evt.clientY
  11706. };
  11707. if (!noPreventDefault) {
  11708. evt.preventDefault();
  11709. }
  11710. }
  11711. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11712. try {
  11713. evt.srcElement.releasePointerCapture(evt.pointerId);
  11714. }
  11715. catch (e) {
  11716. }
  11717. _this.previousPosition = null;
  11718. if (!noPreventDefault) {
  11719. evt.preventDefault();
  11720. }
  11721. }
  11722. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11723. if (!_this.previousPosition && !engine.isPointerLock) {
  11724. return;
  11725. }
  11726. var offsetX;
  11727. var offsetY;
  11728. if (!engine.isPointerLock) {
  11729. offsetX = evt.clientX - _this.previousPosition.x;
  11730. offsetY = evt.clientY - _this.previousPosition.y;
  11731. }
  11732. else {
  11733. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11734. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11735. }
  11736. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11737. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11738. _this.previousPosition = {
  11739. x: evt.clientX,
  11740. y: evt.clientY
  11741. };
  11742. if (!noPreventDefault) {
  11743. evt.preventDefault();
  11744. }
  11745. }
  11746. };
  11747. }
  11748. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11749. };
  11750. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11751. if (this._observer && element) {
  11752. this.camera.getScene().onPointerObservable.remove(this._observer);
  11753. this._observer = null;
  11754. this.previousPosition = null;
  11755. }
  11756. };
  11757. FreeCameraMouseInput.prototype.getTypeName = function () {
  11758. return "FreeCameraMouseInput";
  11759. };
  11760. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11761. return "mouse";
  11762. };
  11763. __decorate([
  11764. BABYLON.serialize()
  11765. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11766. return FreeCameraMouseInput;
  11767. })();
  11768. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11769. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11770. })(BABYLON || (BABYLON = {}));
  11771. var BABYLON;
  11772. (function (BABYLON) {
  11773. var FreeCameraKeyboardMoveInput = (function () {
  11774. function FreeCameraKeyboardMoveInput() {
  11775. this._keys = [];
  11776. this.keysUp = [38];
  11777. this.keysDown = [40];
  11778. this.keysLeft = [37];
  11779. this.keysRight = [39];
  11780. }
  11781. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11782. var _this = this;
  11783. if (!this._onKeyDown) {
  11784. this._onKeyDown = function (evt) {
  11785. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11786. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11787. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11788. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11789. var index = _this._keys.indexOf(evt.keyCode);
  11790. if (index === -1) {
  11791. _this._keys.push(evt.keyCode);
  11792. }
  11793. if (!noPreventDefault) {
  11794. evt.preventDefault();
  11795. }
  11796. }
  11797. };
  11798. this._onKeyUp = function (evt) {
  11799. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11800. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11801. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11802. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11803. var index = _this._keys.indexOf(evt.keyCode);
  11804. if (index >= 0) {
  11805. _this._keys.splice(index, 1);
  11806. }
  11807. if (!noPreventDefault) {
  11808. evt.preventDefault();
  11809. }
  11810. }
  11811. };
  11812. BABYLON.Tools.RegisterTopRootEvents([
  11813. { name: "keydown", handler: this._onKeyDown },
  11814. { name: "keyup", handler: this._onKeyUp },
  11815. { name: "blur", handler: this._onLostFocus }
  11816. ]);
  11817. }
  11818. };
  11819. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11820. if (this._onKeyDown) {
  11821. BABYLON.Tools.UnregisterTopRootEvents([
  11822. { name: "keydown", handler: this._onKeyDown },
  11823. { name: "keyup", handler: this._onKeyUp },
  11824. { name: "blur", handler: this._onLostFocus }
  11825. ]);
  11826. this._keys = [];
  11827. this._onKeyDown = null;
  11828. this._onKeyUp = null;
  11829. }
  11830. };
  11831. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11832. if (this._onKeyDown) {
  11833. var camera = this.camera;
  11834. // Keyboard
  11835. for (var index = 0; index < this._keys.length; index++) {
  11836. var keyCode = this._keys[index];
  11837. var speed = camera._computeLocalCameraSpeed();
  11838. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11839. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11840. }
  11841. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11842. camera._localDirection.copyFromFloats(0, 0, speed);
  11843. }
  11844. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11845. camera._localDirection.copyFromFloats(speed, 0, 0);
  11846. }
  11847. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11848. camera._localDirection.copyFromFloats(0, 0, -speed);
  11849. }
  11850. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11851. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11852. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11853. }
  11854. }
  11855. };
  11856. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11857. return "FreeCameraKeyboardMoveInput";
  11858. };
  11859. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11860. this._keys = [];
  11861. };
  11862. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11863. return "keyboard";
  11864. };
  11865. __decorate([
  11866. BABYLON.serialize()
  11867. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11868. __decorate([
  11869. BABYLON.serialize()
  11870. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11871. __decorate([
  11872. BABYLON.serialize()
  11873. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11874. __decorate([
  11875. BABYLON.serialize()
  11876. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11877. return FreeCameraKeyboardMoveInput;
  11878. })();
  11879. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11880. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11881. })(BABYLON || (BABYLON = {}));
  11882. var BABYLON;
  11883. (function (BABYLON) {
  11884. var FreeCameraTouchInput = (function () {
  11885. function FreeCameraTouchInput() {
  11886. this._offsetX = null;
  11887. this._offsetY = null;
  11888. this._pointerCount = 0;
  11889. this._pointerPressed = [];
  11890. this.touchAngularSensibility = 200000.0;
  11891. this.touchMoveSensibility = 250.0;
  11892. }
  11893. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11894. var _this = this;
  11895. var previousPosition;
  11896. if (this._pointerInput === undefined) {
  11897. this._onLostFocus = function (evt) {
  11898. _this._offsetX = null;
  11899. _this._offsetY = null;
  11900. };
  11901. this._pointerInput = function (p, s) {
  11902. var evt = p.event;
  11903. if (evt.pointerType === "mouse") {
  11904. return;
  11905. }
  11906. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11907. if (!noPreventDefault) {
  11908. evt.preventDefault();
  11909. }
  11910. _this._pointerPressed.push(evt.pointerId);
  11911. if (_this._pointerPressed.length !== 1) {
  11912. return;
  11913. }
  11914. previousPosition = {
  11915. x: evt.clientX,
  11916. y: evt.clientY
  11917. };
  11918. }
  11919. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11920. if (!noPreventDefault) {
  11921. evt.preventDefault();
  11922. }
  11923. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11924. if (index === -1) {
  11925. return;
  11926. }
  11927. _this._pointerPressed.splice(index, 1);
  11928. if (index != 0) {
  11929. return;
  11930. }
  11931. previousPosition = null;
  11932. _this._offsetX = null;
  11933. _this._offsetY = null;
  11934. }
  11935. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11936. if (!noPreventDefault) {
  11937. evt.preventDefault();
  11938. }
  11939. if (!previousPosition) {
  11940. return;
  11941. }
  11942. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11943. if (index != 0) {
  11944. return;
  11945. }
  11946. _this._offsetX = evt.clientX - previousPosition.x;
  11947. _this._offsetY = -(evt.clientY - previousPosition.y);
  11948. }
  11949. };
  11950. }
  11951. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11952. element.addEventListener("blur", this._onLostFocus);
  11953. };
  11954. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11955. if (this._pointerInput && element) {
  11956. this.camera.getScene().onPointerObservable.remove(this._observer);
  11957. this._observer = null;
  11958. element.removeEventListener("blur", this._onLostFocus);
  11959. this._onLostFocus = null;
  11960. this._pointerPressed = [];
  11961. this._offsetX = null;
  11962. this._offsetY = null;
  11963. this._pointerCount = 0;
  11964. }
  11965. };
  11966. FreeCameraTouchInput.prototype.checkInputs = function () {
  11967. if (this._offsetX) {
  11968. var camera = this.camera;
  11969. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11970. if (this._pointerPressed.length > 1) {
  11971. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11972. }
  11973. else {
  11974. var speed = camera._computeLocalCameraSpeed();
  11975. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11976. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11977. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11978. }
  11979. }
  11980. };
  11981. FreeCameraTouchInput.prototype.getTypeName = function () {
  11982. return "FreeCameraTouchInput";
  11983. };
  11984. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11985. return "touch";
  11986. };
  11987. __decorate([
  11988. BABYLON.serialize()
  11989. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11990. __decorate([
  11991. BABYLON.serialize()
  11992. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11993. return FreeCameraTouchInput;
  11994. })();
  11995. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11996. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11997. })(BABYLON || (BABYLON = {}));
  11998. var BABYLON;
  11999. (function (BABYLON) {
  12000. var FreeCameraDeviceOrientationInput = (function () {
  12001. function FreeCameraDeviceOrientationInput() {
  12002. this._offsetX = null;
  12003. this._offsetY = null;
  12004. this._orientationGamma = 0;
  12005. this._orientationBeta = 0;
  12006. this._initialOrientationGamma = 0;
  12007. this._initialOrientationBeta = 0;
  12008. this.angularSensibility = 10000.0;
  12009. this.moveSensibility = 50.0;
  12010. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  12011. this._orientationChanged = this.orientationChanged.bind(this);
  12012. }
  12013. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12014. window.addEventListener("resize", this._resetOrientationGamma, false);
  12015. window.addEventListener("deviceorientation", this._orientationChanged);
  12016. };
  12017. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  12018. this._initialOrientationGamma = null;
  12019. };
  12020. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  12021. if (!this._initialOrientationGamma) {
  12022. this._initialOrientationGamma = evt.gamma;
  12023. this._initialOrientationBeta = evt.beta;
  12024. }
  12025. this._orientationGamma = evt.gamma;
  12026. this._orientationBeta = evt.beta;
  12027. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  12028. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  12029. };
  12030. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12031. window.removeEventListener("resize", this._resetOrientationGamma);
  12032. window.removeEventListener("deviceorientation", this._orientationChanged);
  12033. this._orientationGamma = 0;
  12034. this._orientationBeta = 0;
  12035. this._initialOrientationGamma = 0;
  12036. this._initialOrientationBeta = 0;
  12037. this._offsetX = null;
  12038. this._offsetY = null;
  12039. };
  12040. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12041. if (!this._offsetX) {
  12042. return;
  12043. }
  12044. var camera = this.camera;
  12045. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  12046. var speed = camera._computeLocalCameraSpeed();
  12047. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  12048. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12049. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12050. };
  12051. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12052. return "FreeCameraDeviceOrientationInput";
  12053. };
  12054. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12055. return "deviceOrientation";
  12056. };
  12057. __decorate([
  12058. BABYLON.serialize()
  12059. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  12060. __decorate([
  12061. BABYLON.serialize()
  12062. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  12063. return FreeCameraDeviceOrientationInput;
  12064. })();
  12065. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12066. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12067. })(BABYLON || (BABYLON = {}));
  12068. var BABYLON;
  12069. (function (BABYLON) {
  12070. var FreeCameraVRDeviceOrientationInput = (function () {
  12071. function FreeCameraVRDeviceOrientationInput() {
  12072. this.alphaCorrection = 1;
  12073. this.betaCorrection = 1;
  12074. this.gammaCorrection = 1;
  12075. this._alpha = 0;
  12076. this._beta = 0;
  12077. this._gamma = 0;
  12078. this._dirty = false;
  12079. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12080. }
  12081. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12082. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12083. };
  12084. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12085. var camera = this.camera;
  12086. this._alpha = evt.alpha;
  12087. this._beta = evt.beta;
  12088. this._gamma = evt.gamma;
  12089. this._dirty = true;
  12090. };
  12091. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12092. if (this._dirty) {
  12093. this._dirty = false;
  12094. var rotationX = this._gamma;
  12095. if (rotationX < 0) {
  12096. rotationX = 90 + rotationX;
  12097. }
  12098. else {
  12099. // Incline it in the correct angle.
  12100. rotationX = 270 - rotationX;
  12101. }
  12102. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12103. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12104. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12105. }
  12106. };
  12107. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12108. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12109. };
  12110. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12111. return "FreeCameraVRDeviceOrientationInput";
  12112. };
  12113. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12114. return "VRDeviceOrientation";
  12115. };
  12116. return FreeCameraVRDeviceOrientationInput;
  12117. })();
  12118. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12119. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12120. })(BABYLON || (BABYLON = {}));
  12121. var BABYLON;
  12122. (function (BABYLON) {
  12123. var FreeCameraGamepadInput = (function () {
  12124. function FreeCameraGamepadInput() {
  12125. this.gamepadAngularSensibility = 200;
  12126. this.gamepadMoveSensibility = 40;
  12127. }
  12128. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12129. var _this = this;
  12130. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12131. };
  12132. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12133. if (this._gamepads) {
  12134. this._gamepads.dispose();
  12135. }
  12136. this.gamepad = null;
  12137. };
  12138. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12139. if (this.gamepad) {
  12140. var camera = this.camera;
  12141. var LSValues = this.gamepad.leftStick;
  12142. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12143. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12144. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12145. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12146. var RSValues = this.gamepad.rightStick;
  12147. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12148. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12149. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12150. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12151. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12152. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12153. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12154. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12155. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12156. }
  12157. };
  12158. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12159. // Only the first gamepad can control the camera
  12160. if (gamepad.index === 0) {
  12161. this.gamepad = gamepad;
  12162. }
  12163. };
  12164. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12165. return "FreeCameraGamepadInput";
  12166. };
  12167. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12168. return "gamepad";
  12169. };
  12170. __decorate([
  12171. BABYLON.serialize()
  12172. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12173. __decorate([
  12174. BABYLON.serialize()
  12175. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12176. return FreeCameraGamepadInput;
  12177. })();
  12178. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12179. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12180. })(BABYLON || (BABYLON = {}));
  12181. var BABYLON;
  12182. (function (BABYLON) {
  12183. var FreeCameraVirtualJoystickInput = (function () {
  12184. function FreeCameraVirtualJoystickInput() {
  12185. }
  12186. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12187. return this._leftjoystick;
  12188. };
  12189. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12190. return this._rightjoystick;
  12191. };
  12192. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12193. if (this._leftjoystick) {
  12194. var camera = this.camera;
  12195. var speed = camera._computeLocalCameraSpeed() * 50;
  12196. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12197. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12198. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12199. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12200. if (!this._leftjoystick.pressed) {
  12201. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12202. }
  12203. if (!this._rightjoystick.pressed) {
  12204. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12205. }
  12206. }
  12207. };
  12208. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12209. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12210. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12211. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12212. this._leftjoystick.setJoystickSensibility(0.15);
  12213. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12214. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12215. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12216. this._rightjoystick.reverseUpDown = true;
  12217. this._rightjoystick.setJoystickSensibility(0.05);
  12218. this._rightjoystick.setJoystickColor("yellow");
  12219. };
  12220. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12221. this._leftjoystick.releaseCanvas();
  12222. this._rightjoystick.releaseCanvas();
  12223. };
  12224. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12225. return "FreeCameraVirtualJoystickInput";
  12226. };
  12227. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12228. return "virtualJoystick";
  12229. };
  12230. return FreeCameraVirtualJoystickInput;
  12231. })();
  12232. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12233. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12234. })(BABYLON || (BABYLON = {}));
  12235. var BABYLON;
  12236. (function (BABYLON) {
  12237. var ArcRotateCameraKeyboardMoveInput = (function () {
  12238. function ArcRotateCameraKeyboardMoveInput() {
  12239. this._keys = [];
  12240. this.keysUp = [38];
  12241. this.keysDown = [40];
  12242. this.keysLeft = [37];
  12243. this.keysRight = [39];
  12244. }
  12245. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12246. var _this = this;
  12247. this._onKeyDown = function (evt) {
  12248. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12249. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12250. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12251. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12252. var index = _this._keys.indexOf(evt.keyCode);
  12253. if (index === -1) {
  12254. _this._keys.push(evt.keyCode);
  12255. }
  12256. if (evt.preventDefault) {
  12257. if (!noPreventDefault) {
  12258. evt.preventDefault();
  12259. }
  12260. }
  12261. }
  12262. };
  12263. this._onKeyUp = function (evt) {
  12264. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12265. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12266. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12267. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12268. var index = _this._keys.indexOf(evt.keyCode);
  12269. if (index >= 0) {
  12270. _this._keys.splice(index, 1);
  12271. }
  12272. if (evt.preventDefault) {
  12273. if (!noPreventDefault) {
  12274. evt.preventDefault();
  12275. }
  12276. }
  12277. }
  12278. };
  12279. this._onLostFocus = function () {
  12280. _this._keys = [];
  12281. };
  12282. BABYLON.Tools.RegisterTopRootEvents([
  12283. { name: "keydown", handler: this._onKeyDown },
  12284. { name: "keyup", handler: this._onKeyUp },
  12285. { name: "blur", handler: this._onLostFocus }
  12286. ]);
  12287. };
  12288. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12289. BABYLON.Tools.UnregisterTopRootEvents([
  12290. { name: "keydown", handler: this._onKeyDown },
  12291. { name: "keyup", handler: this._onKeyUp },
  12292. { name: "blur", handler: this._onLostFocus }
  12293. ]);
  12294. this._keys = [];
  12295. this._onKeyDown = null;
  12296. this._onKeyUp = null;
  12297. this._onLostFocus = null;
  12298. };
  12299. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12300. if (this._onKeyDown) {
  12301. var camera = this.camera;
  12302. for (var index = 0; index < this._keys.length; index++) {
  12303. var keyCode = this._keys[index];
  12304. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12305. camera.inertialAlphaOffset -= 0.01;
  12306. }
  12307. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12308. camera.inertialBetaOffset -= 0.01;
  12309. }
  12310. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12311. camera.inertialAlphaOffset += 0.01;
  12312. }
  12313. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12314. camera.inertialBetaOffset += 0.01;
  12315. }
  12316. }
  12317. }
  12318. };
  12319. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12320. return "ArcRotateCameraKeyboardMoveInput";
  12321. };
  12322. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12323. return "keyboard";
  12324. };
  12325. __decorate([
  12326. BABYLON.serialize()
  12327. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12328. __decorate([
  12329. BABYLON.serialize()
  12330. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12331. __decorate([
  12332. BABYLON.serialize()
  12333. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12334. __decorate([
  12335. BABYLON.serialize()
  12336. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12337. return ArcRotateCameraKeyboardMoveInput;
  12338. })();
  12339. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12340. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12341. })(BABYLON || (BABYLON = {}));
  12342. var BABYLON;
  12343. (function (BABYLON) {
  12344. var ArcRotateCameraMouseWheelInput = (function () {
  12345. function ArcRotateCameraMouseWheelInput() {
  12346. this.wheelPrecision = 3.0;
  12347. }
  12348. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12349. var _this = this;
  12350. this._wheel = function (p, s) {
  12351. //sanity check - this should be a PointerWheel event.
  12352. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12353. return;
  12354. var event = p.event;
  12355. var delta = 0;
  12356. if (event.wheelDelta) {
  12357. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12358. }
  12359. else if (event.detail) {
  12360. delta = -event.detail / _this.wheelPrecision;
  12361. }
  12362. if (delta)
  12363. _this.camera.inertialRadiusOffset += delta;
  12364. if (event.preventDefault) {
  12365. if (!noPreventDefault) {
  12366. event.preventDefault();
  12367. }
  12368. }
  12369. };
  12370. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12371. };
  12372. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12373. if (this._observer && element) {
  12374. this.camera.getScene().onPointerObservable.remove(this._observer);
  12375. this._observer = null;
  12376. this._wheel = null;
  12377. }
  12378. };
  12379. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12380. return "ArcRotateCameraMouseWheelInput";
  12381. };
  12382. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12383. return "mousewheel";
  12384. };
  12385. __decorate([
  12386. BABYLON.serialize()
  12387. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12388. return ArcRotateCameraMouseWheelInput;
  12389. })();
  12390. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12391. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12392. })(BABYLON || (BABYLON = {}));
  12393. var BABYLON;
  12394. (function (BABYLON) {
  12395. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12396. var ArcRotateCameraPointersInput = (function () {
  12397. function ArcRotateCameraPointersInput() {
  12398. this.angularSensibilityX = 1000.0;
  12399. this.angularSensibilityY = 1000.0;
  12400. this.pinchPrecision = 6.0;
  12401. this.panningSensibility = 50.0;
  12402. this._isRightClick = false;
  12403. this._isCtrlPushed = false;
  12404. this.pinchInwards = true;
  12405. }
  12406. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12407. var _this = this;
  12408. var engine = this.camera.getEngine();
  12409. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12410. var pointA, pointB;
  12411. var previousPinchDistance = 0;
  12412. this._pointerInput = function (p, s) {
  12413. var evt = p.event;
  12414. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12415. try {
  12416. evt.srcElement.setPointerCapture(evt.pointerId);
  12417. }
  12418. catch (e) {
  12419. }
  12420. // Manage panning with right click
  12421. _this._isRightClick = evt.button === 2;
  12422. // manage pointers
  12423. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12424. if (pointA === undefined) {
  12425. pointA = cacheSoloPointer;
  12426. }
  12427. else if (pointB === undefined) {
  12428. pointB = cacheSoloPointer;
  12429. }
  12430. if (!noPreventDefault) {
  12431. evt.preventDefault();
  12432. }
  12433. }
  12434. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12435. try {
  12436. evt.srcElement.releasePointerCapture(evt.pointerId);
  12437. }
  12438. catch (e) {
  12439. }
  12440. cacheSoloPointer = null;
  12441. previousPinchDistance = 0;
  12442. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12443. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12444. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12445. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12446. pointA = pointB = undefined;
  12447. if (!noPreventDefault) {
  12448. evt.preventDefault();
  12449. }
  12450. }
  12451. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12452. if (!noPreventDefault) {
  12453. evt.preventDefault();
  12454. }
  12455. // One button down
  12456. if (pointA && pointB === undefined) {
  12457. if (_this.panningSensibility !== 0 &&
  12458. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12459. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12460. _this.camera
  12461. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12462. _this.camera
  12463. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12464. }
  12465. else {
  12466. var offsetX = evt.clientX - cacheSoloPointer.x;
  12467. var offsetY = evt.clientY - cacheSoloPointer.y;
  12468. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12469. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12470. }
  12471. cacheSoloPointer.x = evt.clientX;
  12472. cacheSoloPointer.y = evt.clientY;
  12473. }
  12474. else if (pointA && pointB) {
  12475. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12476. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12477. ed.x = evt.clientX;
  12478. ed.y = evt.clientY;
  12479. var direction = _this.pinchInwards ? 1 : -1;
  12480. var distX = pointA.x - pointB.x;
  12481. var distY = pointA.y - pointB.y;
  12482. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12483. if (previousPinchDistance === 0) {
  12484. previousPinchDistance = pinchSquaredDistance;
  12485. return;
  12486. }
  12487. if (pinchSquaredDistance !== previousPinchDistance) {
  12488. _this.camera
  12489. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12490. (_this.pinchPrecision *
  12491. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12492. direction);
  12493. previousPinchDistance = pinchSquaredDistance;
  12494. }
  12495. }
  12496. }
  12497. };
  12498. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12499. this._onContextMenu = function (evt) {
  12500. evt.preventDefault();
  12501. };
  12502. if (!this.camera._useCtrlForPanning) {
  12503. element.addEventListener("contextmenu", this._onContextMenu, false);
  12504. }
  12505. this._onLostFocus = function () {
  12506. //this._keys = [];
  12507. pointA = pointB = undefined;
  12508. previousPinchDistance = 0;
  12509. cacheSoloPointer = null;
  12510. };
  12511. this._onKeyDown = function (evt) {
  12512. _this._isCtrlPushed = evt.ctrlKey;
  12513. };
  12514. this._onKeyUp = function (evt) {
  12515. _this._isCtrlPushed = evt.ctrlKey;
  12516. };
  12517. this._onMouseMove = function (evt) {
  12518. if (!engine.isPointerLock) {
  12519. return;
  12520. }
  12521. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12522. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12523. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12524. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12525. if (!noPreventDefault) {
  12526. evt.preventDefault();
  12527. }
  12528. };
  12529. this._onGestureStart = function (e) {
  12530. if (window.MSGesture === undefined) {
  12531. return;
  12532. }
  12533. if (!_this._MSGestureHandler) {
  12534. _this._MSGestureHandler = new MSGesture();
  12535. _this._MSGestureHandler.target = element;
  12536. }
  12537. _this._MSGestureHandler.addPointer(e.pointerId);
  12538. };
  12539. this._onGesture = function (e) {
  12540. _this.camera.radius *= e.scale;
  12541. if (e.preventDefault) {
  12542. if (!noPreventDefault) {
  12543. e.stopPropagation();
  12544. e.preventDefault();
  12545. }
  12546. }
  12547. };
  12548. element.addEventListener("mousemove", this._onMouseMove, false);
  12549. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12550. element.addEventListener("MSGestureChange", this._onGesture, false);
  12551. BABYLON.Tools.RegisterTopRootEvents([
  12552. { name: "keydown", handler: this._onKeyDown },
  12553. { name: "keyup", handler: this._onKeyUp },
  12554. { name: "blur", handler: this._onLostFocus }
  12555. ]);
  12556. };
  12557. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12558. if (element && this._observer) {
  12559. this.camera.getScene().onPointerObservable.remove(this._observer);
  12560. this._observer = null;
  12561. element.removeEventListener("contextmenu", this._onContextMenu);
  12562. element.removeEventListener("mousemove", this._onMouseMove);
  12563. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12564. element.removeEventListener("MSGestureChange", this._onGesture);
  12565. this._isRightClick = false;
  12566. this._isCtrlPushed = false;
  12567. this.pinchInwards = true;
  12568. this._onKeyDown = null;
  12569. this._onKeyUp = null;
  12570. this._onMouseMove = null;
  12571. this._onGestureStart = null;
  12572. this._onGesture = null;
  12573. this._MSGestureHandler = null;
  12574. this._onLostFocus = null;
  12575. this._onContextMenu = null;
  12576. }
  12577. BABYLON.Tools.UnregisterTopRootEvents([
  12578. { name: "keydown", handler: this._onKeyDown },
  12579. { name: "keyup", handler: this._onKeyUp },
  12580. { name: "blur", handler: this._onLostFocus }
  12581. ]);
  12582. };
  12583. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12584. return "ArcRotateCameraPointersInput";
  12585. };
  12586. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12587. return "pointers";
  12588. };
  12589. __decorate([
  12590. BABYLON.serialize()
  12591. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12592. __decorate([
  12593. BABYLON.serialize()
  12594. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12595. __decorate([
  12596. BABYLON.serialize()
  12597. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12598. __decorate([
  12599. BABYLON.serialize()
  12600. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12601. return ArcRotateCameraPointersInput;
  12602. })();
  12603. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12604. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12605. })(BABYLON || (BABYLON = {}));
  12606. var BABYLON;
  12607. (function (BABYLON) {
  12608. var ArcRotateCameraGamepadInput = (function () {
  12609. function ArcRotateCameraGamepadInput() {
  12610. this.gamepadRotationSensibility = 80;
  12611. this.gamepadMoveSensibility = 40;
  12612. }
  12613. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12614. var _this = this;
  12615. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12616. };
  12617. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12618. if (this._gamepads) {
  12619. this._gamepads.dispose();
  12620. }
  12621. this.gamepad = null;
  12622. };
  12623. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12624. if (this.gamepad) {
  12625. var camera = this.camera;
  12626. var RSValues = this.gamepad.rightStick;
  12627. if (RSValues.x != 0) {
  12628. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12629. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12630. camera.inertialAlphaOffset += normalizedRX;
  12631. }
  12632. }
  12633. if (RSValues.y != 0) {
  12634. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12635. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12636. camera.inertialBetaOffset += normalizedRY;
  12637. }
  12638. }
  12639. var LSValues = this.gamepad.leftStick;
  12640. if (LSValues.y != 0) {
  12641. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12642. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12643. this.camera.inertialRadiusOffset -= normalizedLY;
  12644. }
  12645. }
  12646. }
  12647. };
  12648. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12649. // Only the first gamepad can control the camera
  12650. if (gamepad.index === 0) {
  12651. this.gamepad = gamepad;
  12652. }
  12653. };
  12654. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12655. return "ArcRotateCameraGamepadInput";
  12656. };
  12657. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12658. return "gamepad";
  12659. };
  12660. __decorate([
  12661. BABYLON.serialize()
  12662. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12663. __decorate([
  12664. BABYLON.serialize()
  12665. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12666. return ArcRotateCameraGamepadInput;
  12667. })();
  12668. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12669. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12670. })(BABYLON || (BABYLON = {}));
  12671. var BABYLON;
  12672. (function (BABYLON) {
  12673. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12674. function ArcRotateCameraVRDeviceOrientationInput() {
  12675. this.alphaCorrection = 1;
  12676. this.betaCorrection = 1;
  12677. this.gammaCorrection = 1;
  12678. this._alpha = 0;
  12679. this._beta = 0;
  12680. this._gamma = 0;
  12681. this._dirty = false;
  12682. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12683. }
  12684. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12685. this.camera.attachControl(element, noPreventDefault);
  12686. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12687. };
  12688. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12689. var camera = this.camera;
  12690. this._alpha = +evt.alpha | 0;
  12691. this._beta = +evt.beta | 0;
  12692. this._gamma = +evt.gamma | 0;
  12693. this._dirty = true;
  12694. };
  12695. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12696. if (this._dirty) {
  12697. this._dirty = false;
  12698. if (this._gamma < 0) {
  12699. this._gamma = 180 + this._gamma;
  12700. }
  12701. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12702. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12703. }
  12704. };
  12705. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12706. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12707. };
  12708. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12709. return "ArcRotateCameraVRDeviceOrientationInput";
  12710. };
  12711. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12712. return "VRDeviceOrientation";
  12713. };
  12714. return ArcRotateCameraVRDeviceOrientationInput;
  12715. })();
  12716. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12717. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12718. })(BABYLON || (BABYLON = {}));
  12719. var BABYLON;
  12720. (function (BABYLON) {
  12721. var TargetCamera = (function (_super) {
  12722. __extends(TargetCamera, _super);
  12723. function TargetCamera(name, position, scene) {
  12724. _super.call(this, name, position, scene);
  12725. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12726. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12727. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12728. this.speed = 2.0;
  12729. this.noRotationConstraint = false;
  12730. this.lockedTarget = null;
  12731. this._currentTarget = BABYLON.Vector3.Zero();
  12732. this._viewMatrix = BABYLON.Matrix.Zero();
  12733. this._camMatrix = BABYLON.Matrix.Zero();
  12734. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12735. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12736. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12737. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12738. this._lookAtTemp = BABYLON.Matrix.Zero();
  12739. this._tempMatrix = BABYLON.Matrix.Zero();
  12740. }
  12741. TargetCamera.prototype.getFrontPosition = function (distance) {
  12742. var direction = this.getTarget().subtract(this.position);
  12743. direction.normalize();
  12744. direction.scaleInPlace(distance);
  12745. return this.globalPosition.add(direction);
  12746. };
  12747. TargetCamera.prototype._getLockedTargetPosition = function () {
  12748. if (!this.lockedTarget) {
  12749. return null;
  12750. }
  12751. return this.lockedTarget.position || this.lockedTarget;
  12752. };
  12753. // Cache
  12754. TargetCamera.prototype._initCache = function () {
  12755. _super.prototype._initCache.call(this);
  12756. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12757. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12758. };
  12759. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12760. if (!ignoreParentClass) {
  12761. _super.prototype._updateCache.call(this);
  12762. }
  12763. var lockedTargetPosition = this._getLockedTargetPosition();
  12764. if (!lockedTargetPosition) {
  12765. this._cache.lockedTarget = null;
  12766. }
  12767. else {
  12768. if (!this._cache.lockedTarget) {
  12769. this._cache.lockedTarget = lockedTargetPosition.clone();
  12770. }
  12771. else {
  12772. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12773. }
  12774. }
  12775. this._cache.rotation.copyFrom(this.rotation);
  12776. };
  12777. // Synchronized
  12778. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12779. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12780. return false;
  12781. }
  12782. var lockedTargetPosition = this._getLockedTargetPosition();
  12783. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12784. && this._cache.rotation.equals(this.rotation);
  12785. };
  12786. // Methods
  12787. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12788. var engine = this.getEngine();
  12789. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12790. };
  12791. // Target
  12792. TargetCamera.prototype.setTarget = function (target) {
  12793. this.upVector.normalize();
  12794. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12795. this._camMatrix.invert();
  12796. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12797. var vDir = target.subtract(this.position);
  12798. if (vDir.x >= 0.0) {
  12799. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12800. }
  12801. else {
  12802. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12803. }
  12804. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12805. if (isNaN(this.rotation.x)) {
  12806. this.rotation.x = 0;
  12807. }
  12808. if (isNaN(this.rotation.y)) {
  12809. this.rotation.y = 0;
  12810. }
  12811. if (isNaN(this.rotation.z)) {
  12812. this.rotation.z = 0;
  12813. }
  12814. };
  12815. TargetCamera.prototype.getTarget = function () {
  12816. return this._currentTarget;
  12817. };
  12818. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12819. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12820. };
  12821. TargetCamera.prototype._updatePosition = function () {
  12822. this.position.addInPlace(this.cameraDirection);
  12823. };
  12824. TargetCamera.prototype._checkInputs = function () {
  12825. var needToMove = this._decideIfNeedsToMove();
  12826. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12827. // Move
  12828. if (needToMove) {
  12829. this._updatePosition();
  12830. }
  12831. // Rotate
  12832. if (needToRotate) {
  12833. this.rotation.x += this.cameraRotation.x;
  12834. this.rotation.y += this.cameraRotation.y;
  12835. if (!this.noRotationConstraint) {
  12836. var limit = (Math.PI / 2) * 0.95;
  12837. if (this.rotation.x > limit)
  12838. this.rotation.x = limit;
  12839. if (this.rotation.x < -limit)
  12840. this.rotation.x = -limit;
  12841. }
  12842. }
  12843. // Inertia
  12844. if (needToMove) {
  12845. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12846. this.cameraDirection.x = 0;
  12847. }
  12848. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12849. this.cameraDirection.y = 0;
  12850. }
  12851. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12852. this.cameraDirection.z = 0;
  12853. }
  12854. this.cameraDirection.scaleInPlace(this.inertia);
  12855. }
  12856. if (needToRotate) {
  12857. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12858. this.cameraRotation.x = 0;
  12859. }
  12860. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12861. this.cameraRotation.y = 0;
  12862. }
  12863. this.cameraRotation.scaleInPlace(this.inertia);
  12864. }
  12865. _super.prototype._checkInputs.call(this);
  12866. };
  12867. TargetCamera.prototype._getViewMatrix = function () {
  12868. if (!this.lockedTarget) {
  12869. // Compute
  12870. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12871. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12872. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12873. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12874. this._lookAtTemp.invert();
  12875. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12876. }
  12877. else {
  12878. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12879. }
  12880. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12881. // Computing target and final matrix
  12882. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12883. }
  12884. else {
  12885. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12886. }
  12887. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12888. return this._viewMatrix;
  12889. };
  12890. TargetCamera.prototype._getVRViewMatrix = function () {
  12891. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12892. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12893. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12894. // Computing target and final matrix
  12895. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12896. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12897. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12898. return this._viewMatrix;
  12899. };
  12900. /**
  12901. * @override
  12902. * Override Camera.createRigCamera
  12903. */
  12904. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12905. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12906. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12907. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12908. rigCamera._cameraRigParams = {};
  12909. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12910. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12911. }
  12912. return rigCamera;
  12913. }
  12914. return null;
  12915. };
  12916. /**
  12917. * @override
  12918. * Override Camera._updateRigCameras
  12919. */
  12920. TargetCamera.prototype._updateRigCameras = function () {
  12921. switch (this.cameraRigMode) {
  12922. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12923. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12925. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12926. case BABYLON.Camera.RIG_MODE_VR:
  12927. var camLeft = this._rigCameras[0];
  12928. var camRight = this._rigCameras[1];
  12929. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12930. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12931. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12932. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12933. camLeft.position.copyFrom(this.position);
  12934. camRight.position.copyFrom(this.position);
  12935. }
  12936. else {
  12937. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12938. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12939. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12940. camLeft.setTarget(this.getTarget());
  12941. camRight.setTarget(this.getTarget());
  12942. }
  12943. break;
  12944. }
  12945. _super.prototype._updateRigCameras.call(this);
  12946. };
  12947. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12948. if (!this._rigCamTransformMatrix) {
  12949. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12950. }
  12951. var target = this.getTarget();
  12952. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12953. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12954. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12955. };
  12956. TargetCamera.prototype.getTypeName = function () {
  12957. return "TargetCamera";
  12958. };
  12959. __decorate([
  12960. BABYLON.serializeAsVector3()
  12961. ], TargetCamera.prototype, "rotation", void 0);
  12962. __decorate([
  12963. BABYLON.serialize()
  12964. ], TargetCamera.prototype, "speed", void 0);
  12965. __decorate([
  12966. BABYLON.serializeAsMeshReference("lockedTargetId")
  12967. ], TargetCamera.prototype, "lockedTarget", void 0);
  12968. return TargetCamera;
  12969. })(BABYLON.Camera);
  12970. BABYLON.TargetCamera = TargetCamera;
  12971. })(BABYLON || (BABYLON = {}));
  12972. var BABYLON;
  12973. (function (BABYLON) {
  12974. var FreeCamera = (function (_super) {
  12975. __extends(FreeCamera, _super);
  12976. function FreeCamera(name, position, scene) {
  12977. var _this = this;
  12978. _super.call(this, name, position, scene);
  12979. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12980. this.checkCollisions = false;
  12981. this.applyGravity = false;
  12982. this._collider = new BABYLON.Collider();
  12983. this._needMoveForGravity = false;
  12984. this._oldPosition = BABYLON.Vector3.Zero();
  12985. this._diffPosition = BABYLON.Vector3.Zero();
  12986. this._newPosition = BABYLON.Vector3.Zero();
  12987. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12988. if (collidedMesh === void 0) { collidedMesh = null; }
  12989. //TODO move this to the collision coordinator!
  12990. if (_this.getScene().workerCollisions)
  12991. newPosition.multiplyInPlace(_this._collider.radius);
  12992. var updatePosition = function (newPos) {
  12993. _this._newPosition.copyFrom(newPos);
  12994. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12995. var oldPosition = _this.position.clone();
  12996. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12997. _this.position.addInPlace(_this._diffPosition);
  12998. if (_this.onCollide && collidedMesh) {
  12999. _this.onCollide(collidedMesh);
  13000. }
  13001. }
  13002. };
  13003. updatePosition(newPosition);
  13004. };
  13005. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13006. this.inputs.addKeyboard().addMouse();
  13007. }
  13008. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13009. //-- begin properties for backward compatibility for inputs
  13010. get: function () {
  13011. var mouse = this.inputs.attached["mouse"];
  13012. if (mouse)
  13013. return mouse.angularSensibility;
  13014. },
  13015. set: function (value) {
  13016. var mouse = this.inputs.attached["mouse"];
  13017. if (mouse)
  13018. mouse.angularSensibility = value;
  13019. },
  13020. enumerable: true,
  13021. configurable: true
  13022. });
  13023. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13024. get: function () {
  13025. var keyboard = this.inputs.attached["keyboard"];
  13026. if (keyboard)
  13027. return keyboard.keysUp;
  13028. },
  13029. set: function (value) {
  13030. var keyboard = this.inputs.attached["keyboard"];
  13031. if (keyboard)
  13032. keyboard.keysUp = value;
  13033. },
  13034. enumerable: true,
  13035. configurable: true
  13036. });
  13037. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13038. get: function () {
  13039. var keyboard = this.inputs.attached["keyboard"];
  13040. if (keyboard)
  13041. return keyboard.keysDown;
  13042. },
  13043. set: function (value) {
  13044. var keyboard = this.inputs.attached["keyboard"];
  13045. if (keyboard)
  13046. keyboard.keysDown = value;
  13047. },
  13048. enumerable: true,
  13049. configurable: true
  13050. });
  13051. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13052. get: function () {
  13053. var keyboard = this.inputs.attached["keyboard"];
  13054. if (keyboard)
  13055. return keyboard.keysLeft;
  13056. },
  13057. set: function (value) {
  13058. var keyboard = this.inputs.attached["keyboard"];
  13059. if (keyboard)
  13060. keyboard.keysLeft = value;
  13061. },
  13062. enumerable: true,
  13063. configurable: true
  13064. });
  13065. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13066. get: function () {
  13067. var keyboard = this.inputs.attached["keyboard"];
  13068. if (keyboard)
  13069. return keyboard.keysRight;
  13070. },
  13071. set: function (value) {
  13072. var keyboard = this.inputs.attached["keyboard"];
  13073. if (keyboard)
  13074. keyboard.keysRight = value;
  13075. },
  13076. enumerable: true,
  13077. configurable: true
  13078. });
  13079. // Controls
  13080. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13081. this.inputs.attachElement(element, noPreventDefault);
  13082. };
  13083. FreeCamera.prototype.detachControl = function (element) {
  13084. this.inputs.detachElement(element);
  13085. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13086. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13087. };
  13088. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13089. var globalPosition;
  13090. if (this.parent) {
  13091. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13092. }
  13093. else {
  13094. globalPosition = this.position;
  13095. }
  13096. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13097. this._collider.radius = this.ellipsoid;
  13098. //no need for clone, as long as gravity is not on.
  13099. var actualVelocity = velocity;
  13100. //add gravity to the velocity to prevent the dual-collision checking
  13101. if (this.applyGravity) {
  13102. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13103. actualVelocity = velocity.add(this.getScene().gravity);
  13104. }
  13105. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13106. };
  13107. FreeCamera.prototype._checkInputs = function () {
  13108. if (!this._localDirection) {
  13109. this._localDirection = BABYLON.Vector3.Zero();
  13110. this._transformedDirection = BABYLON.Vector3.Zero();
  13111. }
  13112. this.inputs.checkInputs();
  13113. _super.prototype._checkInputs.call(this);
  13114. };
  13115. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13116. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13117. };
  13118. FreeCamera.prototype._updatePosition = function () {
  13119. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13120. this._collideWithWorld(this.cameraDirection);
  13121. }
  13122. else {
  13123. this.position.addInPlace(this.cameraDirection);
  13124. }
  13125. };
  13126. FreeCamera.prototype.dispose = function () {
  13127. this.inputs.clear();
  13128. _super.prototype.dispose.call(this);
  13129. };
  13130. FreeCamera.prototype.getTypeName = function () {
  13131. return "FreeCamera";
  13132. };
  13133. __decorate([
  13134. BABYLON.serializeAsVector3()
  13135. ], FreeCamera.prototype, "ellipsoid", void 0);
  13136. __decorate([
  13137. BABYLON.serialize()
  13138. ], FreeCamera.prototype, "checkCollisions", void 0);
  13139. __decorate([
  13140. BABYLON.serialize()
  13141. ], FreeCamera.prototype, "applyGravity", void 0);
  13142. return FreeCamera;
  13143. })(BABYLON.TargetCamera);
  13144. BABYLON.FreeCamera = FreeCamera;
  13145. })(BABYLON || (BABYLON = {}));
  13146. var BABYLON;
  13147. (function (BABYLON) {
  13148. var FreeCameraInputsManager = (function (_super) {
  13149. __extends(FreeCameraInputsManager, _super);
  13150. function FreeCameraInputsManager(camera) {
  13151. _super.call(this, camera);
  13152. }
  13153. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13154. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13155. return this;
  13156. };
  13157. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13158. if (touchEnabled === void 0) { touchEnabled = true; }
  13159. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13160. return this;
  13161. };
  13162. FreeCameraInputsManager.prototype.addGamepad = function () {
  13163. this.add(new BABYLON.FreeCameraGamepadInput());
  13164. return this;
  13165. };
  13166. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13167. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13168. return this;
  13169. };
  13170. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13171. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13172. return this;
  13173. };
  13174. FreeCameraInputsManager.prototype.addTouch = function () {
  13175. this.add(new BABYLON.FreeCameraTouchInput());
  13176. return this;
  13177. };
  13178. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13179. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13180. return this;
  13181. };
  13182. return FreeCameraInputsManager;
  13183. })(BABYLON.CameraInputsManager);
  13184. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13185. })(BABYLON || (BABYLON = {}));
  13186. var BABYLON;
  13187. (function (BABYLON) {
  13188. var FollowCamera = (function (_super) {
  13189. __extends(FollowCamera, _super);
  13190. function FollowCamera(name, position, scene, target) {
  13191. _super.call(this, name, position, scene);
  13192. this.radius = 12;
  13193. this.rotationOffset = 0;
  13194. this.heightOffset = 4;
  13195. this.cameraAcceleration = 0.05;
  13196. this.maxCameraSpeed = 20;
  13197. this.target = target;
  13198. }
  13199. FollowCamera.prototype.getRadians = function (degrees) {
  13200. return degrees * Math.PI / 180;
  13201. };
  13202. FollowCamera.prototype.follow = function (cameraTarget) {
  13203. if (!cameraTarget)
  13204. return;
  13205. var yRotation;
  13206. if (cameraTarget.rotationQuaternion) {
  13207. var rotMatrix = new BABYLON.Matrix();
  13208. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13209. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13210. }
  13211. else {
  13212. yRotation = cameraTarget.rotation.y;
  13213. }
  13214. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13215. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13216. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13217. var dx = targetX - this.position.x;
  13218. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13219. var dz = (targetZ) - this.position.z;
  13220. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13221. var vy = dy * this.cameraAcceleration;
  13222. var vz = dz * this.cameraAcceleration * 2;
  13223. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13224. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13225. }
  13226. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13227. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13228. }
  13229. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13230. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13231. }
  13232. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13233. this.setTarget(cameraTarget.position);
  13234. };
  13235. FollowCamera.prototype._checkInputs = function () {
  13236. _super.prototype._checkInputs.call(this);
  13237. this.follow(this.target);
  13238. };
  13239. FollowCamera.prototype.getTypeName = function () {
  13240. return "FollowCamera";
  13241. };
  13242. __decorate([
  13243. BABYLON.serialize()
  13244. ], FollowCamera.prototype, "radius", void 0);
  13245. __decorate([
  13246. BABYLON.serialize()
  13247. ], FollowCamera.prototype, "rotationOffset", void 0);
  13248. __decorate([
  13249. BABYLON.serialize()
  13250. ], FollowCamera.prototype, "heightOffset", void 0);
  13251. __decorate([
  13252. BABYLON.serialize()
  13253. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13254. __decorate([
  13255. BABYLON.serialize()
  13256. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13257. __decorate([
  13258. BABYLON.serializeAsMeshReference("lockedTargetId")
  13259. ], FollowCamera.prototype, "target", void 0);
  13260. return FollowCamera;
  13261. })(BABYLON.TargetCamera);
  13262. BABYLON.FollowCamera = FollowCamera;
  13263. var ArcFollowCamera = (function (_super) {
  13264. __extends(ArcFollowCamera, _super);
  13265. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13266. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13267. this.alpha = alpha;
  13268. this.beta = beta;
  13269. this.radius = radius;
  13270. this.target = target;
  13271. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13272. this.follow();
  13273. }
  13274. ArcFollowCamera.prototype.follow = function () {
  13275. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13276. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13277. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13278. this.position = this.target.position.add(this._cartesianCoordinates);
  13279. this.setTarget(this.target.position);
  13280. };
  13281. ArcFollowCamera.prototype._checkInputs = function () {
  13282. _super.prototype._checkInputs.call(this);
  13283. this.follow();
  13284. };
  13285. ArcFollowCamera.prototype.getTypeName = function () {
  13286. return "ArcFollowCamera";
  13287. };
  13288. return ArcFollowCamera;
  13289. })(BABYLON.TargetCamera);
  13290. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13291. })(BABYLON || (BABYLON = {}));
  13292. var BABYLON;
  13293. (function (BABYLON) {
  13294. // We're mainly based on the logic defined into the FreeCamera code
  13295. var TouchCamera = (function (_super) {
  13296. __extends(TouchCamera, _super);
  13297. //-- end properties for backward compatibility for inputs
  13298. function TouchCamera(name, position, scene) {
  13299. _super.call(this, name, position, scene);
  13300. this.inputs.addTouch();
  13301. this._setupInputs();
  13302. }
  13303. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13304. //-- Begin properties for backward compatibility for inputs
  13305. get: function () {
  13306. var touch = this.inputs.attached["touch"];
  13307. if (touch)
  13308. return touch.touchAngularSensibility;
  13309. },
  13310. set: function (value) {
  13311. var touch = this.inputs.attached["touch"];
  13312. if (touch)
  13313. touch.touchAngularSensibility = value;
  13314. },
  13315. enumerable: true,
  13316. configurable: true
  13317. });
  13318. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13319. get: function () {
  13320. var touch = this.inputs.attached["touch"];
  13321. if (touch)
  13322. return touch.touchMoveSensibility;
  13323. },
  13324. set: function (value) {
  13325. var touch = this.inputs.attached["touch"];
  13326. if (touch)
  13327. touch.touchMoveSensibility = value;
  13328. },
  13329. enumerable: true,
  13330. configurable: true
  13331. });
  13332. TouchCamera.prototype.getTypeName = function () {
  13333. return "TouchCamera";
  13334. };
  13335. TouchCamera.prototype._setupInputs = function () {
  13336. var mouse = this.inputs.attached["mouse"];
  13337. if (mouse) {
  13338. mouse.touchEnabled = false;
  13339. }
  13340. };
  13341. return TouchCamera;
  13342. })(BABYLON.FreeCamera);
  13343. BABYLON.TouchCamera = TouchCamera;
  13344. })(BABYLON || (BABYLON = {}));
  13345. var BABYLON;
  13346. (function (BABYLON) {
  13347. var ArcRotateCamera = (function (_super) {
  13348. __extends(ArcRotateCamera, _super);
  13349. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13350. var _this = this;
  13351. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13352. this.inertialAlphaOffset = 0;
  13353. this.inertialBetaOffset = 0;
  13354. this.inertialRadiusOffset = 0;
  13355. this.lowerAlphaLimit = null;
  13356. this.upperAlphaLimit = null;
  13357. this.lowerBetaLimit = 0.01;
  13358. this.upperBetaLimit = Math.PI;
  13359. this.lowerRadiusLimit = null;
  13360. this.upperRadiusLimit = null;
  13361. this.inertialPanningX = 0;
  13362. this.inertialPanningY = 0;
  13363. //-- end properties for backward compatibility for inputs
  13364. this.zoomOnFactor = 1;
  13365. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13366. this.allowUpsideDown = true;
  13367. this._viewMatrix = new BABYLON.Matrix();
  13368. // Panning
  13369. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13370. this.checkCollisions = false;
  13371. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13372. this._collider = new BABYLON.Collider();
  13373. this._previousPosition = BABYLON.Vector3.Zero();
  13374. this._collisionVelocity = BABYLON.Vector3.Zero();
  13375. this._newPosition = BABYLON.Vector3.Zero();
  13376. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13377. if (collidedMesh === void 0) { collidedMesh = null; }
  13378. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13379. newPosition.multiplyInPlace(_this._collider.radius);
  13380. }
  13381. if (!collidedMesh) {
  13382. _this._previousPosition.copyFrom(_this.position);
  13383. }
  13384. else {
  13385. _this.setPosition(newPosition);
  13386. if (_this.onCollide) {
  13387. _this.onCollide(collidedMesh);
  13388. }
  13389. }
  13390. // Recompute because of constraints
  13391. var cosa = Math.cos(_this.alpha);
  13392. var sina = Math.sin(_this.alpha);
  13393. var cosb = Math.cos(_this.beta);
  13394. var sinb = Math.sin(_this.beta);
  13395. if (sinb === 0) {
  13396. sinb = 0.0001;
  13397. }
  13398. var target = _this._getTargetPosition();
  13399. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13400. _this.position.copyFrom(_this._newPosition);
  13401. var up = _this.upVector;
  13402. if (_this.allowUpsideDown && _this.beta < 0) {
  13403. up = up.clone();
  13404. up = up.negate();
  13405. }
  13406. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13407. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13408. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13409. _this._collisionTriggered = false;
  13410. };
  13411. if (!target) {
  13412. this.target = BABYLON.Vector3.Zero();
  13413. }
  13414. else {
  13415. this.target = target;
  13416. }
  13417. this.alpha = alpha;
  13418. this.beta = beta;
  13419. this.radius = radius;
  13420. this.getViewMatrix();
  13421. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13422. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13423. }
  13424. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13425. //-- begin properties for backward compatibility for inputs
  13426. get: function () {
  13427. var pointers = this.inputs.attached["pointers"];
  13428. if (pointers)
  13429. return pointers.angularSensibilityX;
  13430. },
  13431. set: function (value) {
  13432. var pointers = this.inputs.attached["pointers"];
  13433. if (pointers) {
  13434. pointers.angularSensibilityX = value;
  13435. }
  13436. },
  13437. enumerable: true,
  13438. configurable: true
  13439. });
  13440. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13441. get: function () {
  13442. var pointers = this.inputs.attached["pointers"];
  13443. if (pointers)
  13444. return pointers.angularSensibilityY;
  13445. },
  13446. set: function (value) {
  13447. var pointers = this.inputs.attached["pointers"];
  13448. if (pointers) {
  13449. pointers.angularSensibilityY = value;
  13450. }
  13451. },
  13452. enumerable: true,
  13453. configurable: true
  13454. });
  13455. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13456. get: function () {
  13457. var pointers = this.inputs.attached["pointers"];
  13458. if (pointers)
  13459. return pointers.pinchPrecision;
  13460. },
  13461. set: function (value) {
  13462. var pointers = this.inputs.attached["pointers"];
  13463. if (pointers) {
  13464. pointers.pinchPrecision = value;
  13465. }
  13466. },
  13467. enumerable: true,
  13468. configurable: true
  13469. });
  13470. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13471. get: function () {
  13472. var pointers = this.inputs.attached["pointers"];
  13473. if (pointers)
  13474. return pointers.panningSensibility;
  13475. },
  13476. set: function (value) {
  13477. var pointers = this.inputs.attached["pointers"];
  13478. if (pointers) {
  13479. pointers.panningSensibility = value;
  13480. }
  13481. },
  13482. enumerable: true,
  13483. configurable: true
  13484. });
  13485. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13486. get: function () {
  13487. var keyboard = this.inputs.attached["keyboard"];
  13488. if (keyboard)
  13489. return keyboard.keysUp;
  13490. },
  13491. set: function (value) {
  13492. var keyboard = this.inputs.attached["keyboard"];
  13493. if (keyboard)
  13494. keyboard.keysUp = value;
  13495. },
  13496. enumerable: true,
  13497. configurable: true
  13498. });
  13499. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13500. get: function () {
  13501. var keyboard = this.inputs.attached["keyboard"];
  13502. if (keyboard)
  13503. return keyboard.keysDown;
  13504. },
  13505. set: function (value) {
  13506. var keyboard = this.inputs.attached["keyboard"];
  13507. if (keyboard)
  13508. keyboard.keysDown = value;
  13509. },
  13510. enumerable: true,
  13511. configurable: true
  13512. });
  13513. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13514. get: function () {
  13515. var keyboard = this.inputs.attached["keyboard"];
  13516. if (keyboard)
  13517. return keyboard.keysLeft;
  13518. },
  13519. set: function (value) {
  13520. var keyboard = this.inputs.attached["keyboard"];
  13521. if (keyboard)
  13522. keyboard.keysLeft = value;
  13523. },
  13524. enumerable: true,
  13525. configurable: true
  13526. });
  13527. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13528. get: function () {
  13529. var keyboard = this.inputs.attached["keyboard"];
  13530. if (keyboard)
  13531. return keyboard.keysRight;
  13532. },
  13533. set: function (value) {
  13534. var keyboard = this.inputs.attached["keyboard"];
  13535. if (keyboard)
  13536. keyboard.keysRight = value;
  13537. },
  13538. enumerable: true,
  13539. configurable: true
  13540. });
  13541. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13542. get: function () {
  13543. var mousewheel = this.inputs.attached["mousewheel"];
  13544. if (mousewheel)
  13545. return mousewheel.wheelPrecision;
  13546. },
  13547. set: function (value) {
  13548. var mousewheel = this.inputs.attached["mousewheel"];
  13549. if (mousewheel)
  13550. mousewheel.wheelPrecision = value;
  13551. },
  13552. enumerable: true,
  13553. configurable: true
  13554. });
  13555. // Cache
  13556. ArcRotateCamera.prototype._initCache = function () {
  13557. _super.prototype._initCache.call(this);
  13558. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13559. this._cache.alpha = undefined;
  13560. this._cache.beta = undefined;
  13561. this._cache.radius = undefined;
  13562. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13563. };
  13564. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13565. if (!ignoreParentClass) {
  13566. _super.prototype._updateCache.call(this);
  13567. }
  13568. this._cache.target.copyFrom(this._getTargetPosition());
  13569. this._cache.alpha = this.alpha;
  13570. this._cache.beta = this.beta;
  13571. this._cache.radius = this.radius;
  13572. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13573. };
  13574. ArcRotateCamera.prototype._getTargetPosition = function () {
  13575. if (this.target.getAbsolutePosition) {
  13576. return this.target.getAbsolutePosition();
  13577. }
  13578. return this.target;
  13579. };
  13580. // Synchronized
  13581. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13582. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13583. return false;
  13584. return this._cache.target.equals(this.target)
  13585. && this._cache.alpha === this.alpha
  13586. && this._cache.beta === this.beta
  13587. && this._cache.radius === this.radius
  13588. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13589. };
  13590. // Methods
  13591. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13592. var _this = this;
  13593. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13594. this._useCtrlForPanning = useCtrlForPanning;
  13595. this.inputs.attachElement(element, noPreventDefault);
  13596. this._reset = function () {
  13597. _this.inertialAlphaOffset = 0;
  13598. _this.inertialBetaOffset = 0;
  13599. _this.inertialRadiusOffset = 0;
  13600. };
  13601. };
  13602. ArcRotateCamera.prototype.detachControl = function (element) {
  13603. this.inputs.detachElement(element);
  13604. if (this._reset) {
  13605. this._reset();
  13606. }
  13607. };
  13608. ArcRotateCamera.prototype._checkInputs = function () {
  13609. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13610. if (this._collisionTriggered) {
  13611. return;
  13612. }
  13613. this.inputs.checkInputs();
  13614. // Inertia
  13615. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13616. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13617. this.beta += this.inertialBetaOffset;
  13618. this.radius -= this.inertialRadiusOffset;
  13619. this.inertialAlphaOffset *= this.inertia;
  13620. this.inertialBetaOffset *= this.inertia;
  13621. this.inertialRadiusOffset *= this.inertia;
  13622. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13623. this.inertialAlphaOffset = 0;
  13624. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13625. this.inertialBetaOffset = 0;
  13626. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13627. this.inertialRadiusOffset = 0;
  13628. }
  13629. // Panning inertia
  13630. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13631. if (!this._localDirection) {
  13632. this._localDirection = BABYLON.Vector3.Zero();
  13633. this._transformedDirection = BABYLON.Vector3.Zero();
  13634. }
  13635. this.inertialPanningX *= this.inertia;
  13636. this.inertialPanningY *= this.inertia;
  13637. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13638. this.inertialPanningX = 0;
  13639. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13640. this.inertialPanningY = 0;
  13641. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13642. this._localDirection.multiplyInPlace(this.panningAxis);
  13643. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13644. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13645. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13646. if (!this.panningAxis.y) {
  13647. this._transformedDirection.y = 0;
  13648. }
  13649. this.target.addInPlace(this._transformedDirection);
  13650. }
  13651. // Limits
  13652. this._checkLimits();
  13653. _super.prototype._checkInputs.call(this);
  13654. };
  13655. ArcRotateCamera.prototype._checkLimits = function () {
  13656. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13657. if (this.allowUpsideDown && this.beta > Math.PI) {
  13658. this.beta = this.beta - (2 * Math.PI);
  13659. }
  13660. }
  13661. else {
  13662. if (this.beta < this.lowerBetaLimit) {
  13663. this.beta = this.lowerBetaLimit;
  13664. }
  13665. }
  13666. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13667. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13668. this.beta = this.beta + (2 * Math.PI);
  13669. }
  13670. }
  13671. else {
  13672. if (this.beta > this.upperBetaLimit) {
  13673. this.beta = this.upperBetaLimit;
  13674. }
  13675. }
  13676. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13677. this.alpha = this.lowerAlphaLimit;
  13678. }
  13679. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13680. this.alpha = this.upperAlphaLimit;
  13681. }
  13682. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13683. this.radius = this.lowerRadiusLimit;
  13684. }
  13685. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13686. this.radius = this.upperRadiusLimit;
  13687. }
  13688. };
  13689. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13690. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13691. this.radius = radiusv3.length();
  13692. // Alpha
  13693. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13694. if (radiusv3.z < 0) {
  13695. this.alpha = 2 * Math.PI - this.alpha;
  13696. }
  13697. // Beta
  13698. this.beta = Math.acos(radiusv3.y / this.radius);
  13699. this._checkLimits();
  13700. };
  13701. ArcRotateCamera.prototype.setPosition = function (position) {
  13702. if (this.position.equals(position)) {
  13703. return;
  13704. }
  13705. this.position = position;
  13706. this.rebuildAnglesAndRadius();
  13707. };
  13708. ArcRotateCamera.prototype.setTarget = function (target) {
  13709. if (this._getTargetPosition().equals(target)) {
  13710. return;
  13711. }
  13712. this.target = target;
  13713. this.rebuildAnglesAndRadius();
  13714. };
  13715. ArcRotateCamera.prototype._getViewMatrix = function () {
  13716. // Compute
  13717. var cosa = Math.cos(this.alpha);
  13718. var sina = Math.sin(this.alpha);
  13719. var cosb = Math.cos(this.beta);
  13720. var sinb = Math.sin(this.beta);
  13721. if (sinb === 0) {
  13722. sinb = 0.0001;
  13723. }
  13724. var target = this._getTargetPosition();
  13725. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13726. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13727. this._collider.radius = this.collisionRadius;
  13728. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13729. this._collisionTriggered = true;
  13730. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13731. }
  13732. else {
  13733. this.position.copyFrom(this._newPosition);
  13734. var up = this.upVector;
  13735. if (this.allowUpsideDown && this.beta < 0) {
  13736. up = up.clone();
  13737. up = up.negate();
  13738. }
  13739. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13740. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13741. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13742. }
  13743. return this._viewMatrix;
  13744. };
  13745. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13746. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13747. meshes = meshes || this.getScene().meshes;
  13748. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13749. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13750. this.radius = distance * this.zoomOnFactor;
  13751. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13752. };
  13753. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13754. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13755. var meshesOrMinMaxVector;
  13756. var distance;
  13757. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13758. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13759. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13760. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13761. }
  13762. else {
  13763. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13764. distance = meshesOrMinMaxVectorAndDistance.distance;
  13765. }
  13766. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13767. if (!doNotUpdateMaxZ) {
  13768. this.maxZ = distance * 2;
  13769. }
  13770. };
  13771. /**
  13772. * @override
  13773. * Override Camera.createRigCamera
  13774. */
  13775. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13776. switch (this.cameraRigMode) {
  13777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13778. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13779. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13780. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13781. case BABYLON.Camera.RIG_MODE_VR:
  13782. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13783. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13784. rigCam._cameraRigParams = {};
  13785. return rigCam;
  13786. }
  13787. return null;
  13788. };
  13789. /**
  13790. * @override
  13791. * Override Camera._updateRigCameras
  13792. */
  13793. ArcRotateCamera.prototype._updateRigCameras = function () {
  13794. switch (this.cameraRigMode) {
  13795. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13796. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13797. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13798. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13799. case BABYLON.Camera.RIG_MODE_VR:
  13800. var camLeft = this._rigCameras[0];
  13801. var camRight = this._rigCameras[1];
  13802. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13803. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13804. camLeft.beta = camRight.beta = this.beta;
  13805. camLeft.radius = camRight.radius = this.radius;
  13806. break;
  13807. }
  13808. _super.prototype._updateRigCameras.call(this);
  13809. };
  13810. ArcRotateCamera.prototype.dispose = function () {
  13811. this.inputs.clear();
  13812. _super.prototype.dispose.call(this);
  13813. };
  13814. ArcRotateCamera.prototype.getTypeName = function () {
  13815. return "ArcRotateCamera";
  13816. };
  13817. __decorate([
  13818. BABYLON.serialize()
  13819. ], ArcRotateCamera.prototype, "alpha", void 0);
  13820. __decorate([
  13821. BABYLON.serialize()
  13822. ], ArcRotateCamera.prototype, "beta", void 0);
  13823. __decorate([
  13824. BABYLON.serialize()
  13825. ], ArcRotateCamera.prototype, "radius", void 0);
  13826. __decorate([
  13827. BABYLON.serializeAsVector3()
  13828. ], ArcRotateCamera.prototype, "target", void 0);
  13829. __decorate([
  13830. BABYLON.serialize()
  13831. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13832. __decorate([
  13833. BABYLON.serialize()
  13834. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13835. __decorate([
  13836. BABYLON.serialize()
  13837. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13838. __decorate([
  13839. BABYLON.serialize()
  13840. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13841. __decorate([
  13842. BABYLON.serialize()
  13843. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13844. __decorate([
  13845. BABYLON.serialize()
  13846. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13847. __decorate([
  13848. BABYLON.serialize()
  13849. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13850. __decorate([
  13851. BABYLON.serialize()
  13852. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13853. __decorate([
  13854. BABYLON.serialize()
  13855. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13856. __decorate([
  13857. BABYLON.serialize()
  13858. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13859. __decorate([
  13860. BABYLON.serialize()
  13861. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13862. __decorate([
  13863. BABYLON.serialize()
  13864. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13865. __decorate([
  13866. BABYLON.serialize()
  13867. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13868. return ArcRotateCamera;
  13869. })(BABYLON.TargetCamera);
  13870. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13871. })(BABYLON || (BABYLON = {}));
  13872. var BABYLON;
  13873. (function (BABYLON) {
  13874. var ArcRotateCameraInputsManager = (function (_super) {
  13875. __extends(ArcRotateCameraInputsManager, _super);
  13876. function ArcRotateCameraInputsManager(camera) {
  13877. _super.call(this, camera);
  13878. }
  13879. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13880. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13881. return this;
  13882. };
  13883. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13884. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13885. return this;
  13886. };
  13887. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13888. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13889. return this;
  13890. };
  13891. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13892. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13893. return this;
  13894. };
  13895. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13896. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13897. return this;
  13898. };
  13899. return ArcRotateCameraInputsManager;
  13900. })(BABYLON.CameraInputsManager);
  13901. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13902. })(BABYLON || (BABYLON = {}));
  13903. var BABYLON;
  13904. (function (BABYLON) {
  13905. var RenderingManager = (function () {
  13906. function RenderingManager(scene) {
  13907. this._renderingGroups = new Array();
  13908. this._scene = scene;
  13909. }
  13910. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13911. if (this._scene._activeParticleSystems.length === 0) {
  13912. return;
  13913. }
  13914. // Particles
  13915. var activeCamera = this._scene.activeCamera;
  13916. var beforeParticlesDate = BABYLON.Tools.Now;
  13917. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13918. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13919. if (particleSystem.renderingGroupId !== index) {
  13920. continue;
  13921. }
  13922. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13923. continue;
  13924. }
  13925. this._clearDepthBuffer();
  13926. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13927. this._scene._activeParticles += particleSystem.render();
  13928. }
  13929. }
  13930. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13931. };
  13932. RenderingManager.prototype._renderSprites = function (index) {
  13933. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13934. return;
  13935. }
  13936. // Sprites
  13937. var activeCamera = this._scene.activeCamera;
  13938. var beforeSpritessDate = BABYLON.Tools.Now;
  13939. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13940. var spriteManager = this._scene.spriteManagers[id];
  13941. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13942. this._clearDepthBuffer();
  13943. spriteManager.render();
  13944. }
  13945. }
  13946. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13947. };
  13948. RenderingManager.prototype._clearDepthBuffer = function () {
  13949. if (this._depthBufferAlreadyCleaned) {
  13950. return;
  13951. }
  13952. this._scene.getEngine().clear(0, false, true);
  13953. this._depthBufferAlreadyCleaned = true;
  13954. };
  13955. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13956. if (this._currentRenderSprites) {
  13957. this._renderSprites(this._currentIndex);
  13958. }
  13959. if (this._currentRenderParticles) {
  13960. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13961. }
  13962. };
  13963. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13964. this._currentActiveMeshes = activeMeshes;
  13965. this._currentRenderParticles = renderParticles;
  13966. this._currentRenderSprites = renderSprites;
  13967. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13968. this._depthBufferAlreadyCleaned = index == 0;
  13969. var renderingGroup = this._renderingGroups[index];
  13970. var needToStepBack = false;
  13971. this._currentIndex = index;
  13972. if (renderingGroup) {
  13973. this._clearDepthBuffer();
  13974. if (!renderingGroup.onBeforeTransparentRendering) {
  13975. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13976. }
  13977. if (!renderingGroup.render(customRenderFunction)) {
  13978. this._renderingGroups.splice(index, 1);
  13979. needToStepBack = true;
  13980. this._renderSpritesAndParticles();
  13981. }
  13982. }
  13983. else {
  13984. this._renderSpritesAndParticles();
  13985. }
  13986. if (needToStepBack) {
  13987. index--;
  13988. }
  13989. }
  13990. };
  13991. RenderingManager.prototype.reset = function () {
  13992. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13993. if (renderingGroup) {
  13994. renderingGroup.prepare();
  13995. }
  13996. });
  13997. };
  13998. RenderingManager.prototype.dispatch = function (subMesh) {
  13999. var mesh = subMesh.getMesh();
  14000. var renderingGroupId = mesh.renderingGroupId || 0;
  14001. if (!this._renderingGroups[renderingGroupId]) {
  14002. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14003. }
  14004. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14005. };
  14006. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14007. return RenderingManager;
  14008. })();
  14009. BABYLON.RenderingManager = RenderingManager;
  14010. })(BABYLON || (BABYLON = {}));
  14011. var BABYLON;
  14012. (function (BABYLON) {
  14013. var RenderingGroup = (function () {
  14014. function RenderingGroup(index, scene) {
  14015. this.index = index;
  14016. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14017. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14018. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14019. this._scene = scene;
  14020. }
  14021. RenderingGroup.prototype.render = function (customRenderFunction) {
  14022. if (customRenderFunction) {
  14023. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14024. return true;
  14025. }
  14026. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14027. if (this.onBeforeTransparentRendering) {
  14028. this.onBeforeTransparentRendering();
  14029. }
  14030. return false;
  14031. }
  14032. var engine = this._scene.getEngine();
  14033. // Opaque
  14034. var subIndex;
  14035. var submesh;
  14036. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14037. submesh = this._opaqueSubMeshes.data[subIndex];
  14038. submesh.render(false);
  14039. }
  14040. // Alpha test
  14041. engine.setAlphaTesting(true);
  14042. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14043. submesh = this._alphaTestSubMeshes.data[subIndex];
  14044. submesh.render(false);
  14045. }
  14046. engine.setAlphaTesting(false);
  14047. if (this.onBeforeTransparentRendering) {
  14048. this.onBeforeTransparentRendering();
  14049. }
  14050. // Transparent
  14051. if (this._transparentSubMeshes.length) {
  14052. // Sorting
  14053. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14054. submesh = this._transparentSubMeshes.data[subIndex];
  14055. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14056. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14057. }
  14058. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14059. sortedArray.sort(function (a, b) {
  14060. // Alpha index first
  14061. if (a._alphaIndex > b._alphaIndex) {
  14062. return 1;
  14063. }
  14064. if (a._alphaIndex < b._alphaIndex) {
  14065. return -1;
  14066. }
  14067. // Then distance to camera
  14068. if (a._distanceToCamera < b._distanceToCamera) {
  14069. return 1;
  14070. }
  14071. if (a._distanceToCamera > b._distanceToCamera) {
  14072. return -1;
  14073. }
  14074. return 0;
  14075. });
  14076. // Rendering
  14077. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14078. submesh = sortedArray[subIndex];
  14079. submesh.render(true);
  14080. }
  14081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14082. }
  14083. return true;
  14084. };
  14085. RenderingGroup.prototype.prepare = function () {
  14086. this._opaqueSubMeshes.reset();
  14087. this._transparentSubMeshes.reset();
  14088. this._alphaTestSubMeshes.reset();
  14089. };
  14090. RenderingGroup.prototype.dispatch = function (subMesh) {
  14091. var material = subMesh.getMaterial();
  14092. var mesh = subMesh.getMesh();
  14093. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14094. this._transparentSubMeshes.push(subMesh);
  14095. }
  14096. else if (material.needAlphaTesting()) {
  14097. this._alphaTestSubMeshes.push(subMesh);
  14098. }
  14099. else {
  14100. this._opaqueSubMeshes.push(subMesh); // Opaque
  14101. }
  14102. };
  14103. return RenderingGroup;
  14104. })();
  14105. BABYLON.RenderingGroup = RenderingGroup;
  14106. })(BABYLON || (BABYLON = {}));
  14107. var BABYLON;
  14108. (function (BABYLON) {
  14109. var PointerEventTypes = (function () {
  14110. function PointerEventTypes() {
  14111. }
  14112. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14113. get: function () {
  14114. return PointerEventTypes._POINTERDOWN;
  14115. },
  14116. enumerable: true,
  14117. configurable: true
  14118. });
  14119. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14120. get: function () {
  14121. return PointerEventTypes._POINTERUP;
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14127. get: function () {
  14128. return PointerEventTypes._POINTERMOVE;
  14129. },
  14130. enumerable: true,
  14131. configurable: true
  14132. });
  14133. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14134. get: function () {
  14135. return PointerEventTypes._POINTERWHEEL;
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14141. get: function () {
  14142. return PointerEventTypes._POINTERPICK;
  14143. },
  14144. enumerable: true,
  14145. configurable: true
  14146. });
  14147. PointerEventTypes._POINTERDOWN = 0x01;
  14148. PointerEventTypes._POINTERUP = 0x02;
  14149. PointerEventTypes._POINTERMOVE = 0x04;
  14150. PointerEventTypes._POINTERWHEEL = 0x08;
  14151. PointerEventTypes._POINTERPICK = 0x10;
  14152. return PointerEventTypes;
  14153. })();
  14154. BABYLON.PointerEventTypes = PointerEventTypes;
  14155. /**
  14156. * This type contains all the data related to a pointer event in Babylon.js.
  14157. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The differents event types can be found in the PointerEventTypes class.
  14158. */
  14159. var PointerInfo = (function () {
  14160. function PointerInfo(type, event, pickInfo) {
  14161. this.type = type;
  14162. this.event = event;
  14163. this.pickInfo = pickInfo;
  14164. }
  14165. return PointerInfo;
  14166. })();
  14167. BABYLON.PointerInfo = PointerInfo;
  14168. /**
  14169. * Represents a scene to be rendered by the engine.
  14170. * @see http://doc.babylonjs.com/page.php?p=21911
  14171. */
  14172. var Scene = (function () {
  14173. /**
  14174. * @constructor
  14175. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14176. */
  14177. function Scene(engine) {
  14178. // Members
  14179. this.autoClear = true;
  14180. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14181. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14182. this.forceWireframe = false;
  14183. this.forcePointsCloud = false;
  14184. this.forceShowBoundingBoxes = false;
  14185. this.animationsEnabled = true;
  14186. this.constantlyUpdateMeshUnderPointer = false;
  14187. // Events
  14188. /**
  14189. * An event triggered when the scene is disposed.
  14190. * @type {BABYLON.Observable}
  14191. */
  14192. this.onDisposeObservable = new BABYLON.Observable();
  14193. /**
  14194. * An event triggered before rendering the scene
  14195. * @type {BABYLON.Observable}
  14196. */
  14197. this.onBeforeRenderObservable = new BABYLON.Observable();
  14198. /**
  14199. * An event triggered after rendering the scene
  14200. * @type {BABYLON.Observable}
  14201. */
  14202. this.onAfterRenderObservable = new BABYLON.Observable();
  14203. /**
  14204. * An event triggered when the scene is ready
  14205. * @type {BABYLON.Observable}
  14206. */
  14207. this.onReadyObservable = new BABYLON.Observable();
  14208. /**
  14209. * An event triggered before rendering a camera
  14210. * @type {BABYLON.Observable}
  14211. */
  14212. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14213. /**
  14214. * An event triggered after rendering a camera
  14215. * @type {BABYLON.Observable}
  14216. */
  14217. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14218. /**
  14219. * An event triggered when a camera is created
  14220. * @type {BABYLON.Observable}
  14221. */
  14222. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14223. /**
  14224. * An event triggered when a camera is removed
  14225. * @type {BABYLON.Observable}
  14226. */
  14227. this.onCameraRemovedObservable = new BABYLON.Observable();
  14228. /**
  14229. * An event triggered when a light is created
  14230. * @type {BABYLON.Observable}
  14231. */
  14232. this.onNewLightAddedObservable = new BABYLON.Observable();
  14233. /**
  14234. * An event triggered when a light is removed
  14235. * @type {BABYLON.Observable}
  14236. */
  14237. this.onLightRemovedObservable = new BABYLON.Observable();
  14238. /**
  14239. * An event triggered when a geometry is created
  14240. * @type {BABYLON.Observable}
  14241. */
  14242. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14243. /**
  14244. * An event triggered when a geometry is removed
  14245. * @type {BABYLON.Observable}
  14246. */
  14247. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14248. /**
  14249. * An event triggered when a mesh is created
  14250. * @type {BABYLON.Observable}
  14251. */
  14252. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14253. /**
  14254. * An event triggered when a mesh is removed
  14255. * @type {BABYLON.Observable}
  14256. */
  14257. this.onMeshRemovedObservable = new BABYLON.Observable();
  14258. // Animations
  14259. this.animations = [];
  14260. /**
  14261. * Observable event triggered each time an input event is received from the rendering canvas
  14262. */
  14263. this.onPointerObservable = new BABYLON.Observable();
  14264. 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
  14265. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14266. this._startingPointerTime = 0;
  14267. // Fog
  14268. /**
  14269. * is fog enabled on this scene.
  14270. * @type {boolean}
  14271. */
  14272. this.fogEnabled = true;
  14273. this.fogMode = Scene.FOGMODE_NONE;
  14274. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14275. this.fogDensity = 0.1;
  14276. this.fogStart = 0;
  14277. this.fogEnd = 1000.0;
  14278. // Lights
  14279. /**
  14280. * is shadow enabled on this scene.
  14281. * @type {boolean}
  14282. */
  14283. this.shadowsEnabled = true;
  14284. /**
  14285. * is light enabled on this scene.
  14286. * @type {boolean}
  14287. */
  14288. this.lightsEnabled = true;
  14289. /**
  14290. * All of the lights added to this scene.
  14291. * @see BABYLON.Light
  14292. * @type {BABYLON.Light[]}
  14293. */
  14294. this.lights = new Array();
  14295. // Cameras
  14296. /**
  14297. * All of the cameras added to this scene.
  14298. * @see BABYLON.Camera
  14299. * @type {BABYLON.Camera[]}
  14300. */
  14301. this.cameras = new Array();
  14302. this.activeCameras = new Array();
  14303. // Meshes
  14304. /**
  14305. * All of the (abstract) meshes added to this scene.
  14306. * @see BABYLON.AbstractMesh
  14307. * @type {BABYLON.AbstractMesh[]}
  14308. */
  14309. this.meshes = new Array();
  14310. // Geometries
  14311. this._geometries = new Array();
  14312. this.materials = new Array();
  14313. this.multiMaterials = new Array();
  14314. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14315. // Textures
  14316. this.texturesEnabled = true;
  14317. this.textures = new Array();
  14318. // Particles
  14319. this.particlesEnabled = true;
  14320. this.particleSystems = new Array();
  14321. // Sprites
  14322. this.spritesEnabled = true;
  14323. this.spriteManagers = new Array();
  14324. // Layers
  14325. this.layers = new Array();
  14326. // Skeletons
  14327. this.skeletonsEnabled = true;
  14328. this.skeletons = new Array();
  14329. // Lens flares
  14330. this.lensFlaresEnabled = true;
  14331. this.lensFlareSystems = new Array();
  14332. // Collisions
  14333. this.collisionsEnabled = true;
  14334. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14335. // Postprocesses
  14336. this.postProcessesEnabled = true;
  14337. // Customs render targets
  14338. this.renderTargetsEnabled = true;
  14339. this.dumpNextRenderTargets = false;
  14340. this.customRenderTargets = new Array();
  14341. // Imported meshes
  14342. this.importedMeshesFiles = new Array();
  14343. // Probes
  14344. this.probesEnabled = true;
  14345. this.reflectionProbes = new Array();
  14346. this._actionManagers = new Array();
  14347. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14348. // Procedural textures
  14349. this.proceduralTexturesEnabled = true;
  14350. this._proceduralTextures = new Array();
  14351. this.soundTracks = new Array();
  14352. this._audioEnabled = true;
  14353. this._headphone = false;
  14354. this._totalVertices = 0;
  14355. this._activeIndices = 0;
  14356. this._activeParticles = 0;
  14357. this._lastFrameDuration = 0;
  14358. this._evaluateActiveMeshesDuration = 0;
  14359. this._renderTargetsDuration = 0;
  14360. this._particlesDuration = 0;
  14361. this._renderDuration = 0;
  14362. this._spritesDuration = 0;
  14363. this._animationRatio = 0;
  14364. this._renderId = 0;
  14365. this._executeWhenReadyTimeoutId = -1;
  14366. this._intermediateRendering = false;
  14367. this._toBeDisposed = new BABYLON.SmartArray(256);
  14368. this._pendingData = []; //ANY
  14369. this._activeMeshes = new BABYLON.SmartArray(256);
  14370. this._processedMaterials = new BABYLON.SmartArray(256);
  14371. this._renderTargets = new BABYLON.SmartArray(256);
  14372. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14373. this._activeSkeletons = new BABYLON.SmartArray(32);
  14374. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14375. this._activeBones = 0;
  14376. this._activeAnimatables = new Array();
  14377. this._transformMatrix = BABYLON.Matrix.Zero();
  14378. this._edgesRenderers = new BABYLON.SmartArray(16);
  14379. this._uniqueIdCounter = 0;
  14380. this._engine = engine;
  14381. engine.scenes.push(this);
  14382. this._renderingManager = new BABYLON.RenderingManager(this);
  14383. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14384. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14385. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14386. if (BABYLON.OutlineRenderer) {
  14387. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14388. }
  14389. this.attachControl();
  14390. this._debugLayer = new BABYLON.DebugLayer(this);
  14391. if (BABYLON.SoundTrack) {
  14392. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14393. }
  14394. //simplification queue
  14395. if (BABYLON.SimplificationQueue) {
  14396. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14397. }
  14398. //collision coordinator initialization. For now legacy per default.
  14399. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14400. }
  14401. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14402. get: function () {
  14403. return Scene._FOGMODE_NONE;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14409. get: function () {
  14410. return Scene._FOGMODE_EXP;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14416. get: function () {
  14417. return Scene._FOGMODE_EXP2;
  14418. },
  14419. enumerable: true,
  14420. configurable: true
  14421. });
  14422. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14423. get: function () {
  14424. return Scene._FOGMODE_LINEAR;
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. Object.defineProperty(Scene.prototype, "onDispose", {
  14430. set: function (callback) {
  14431. if (this._onDisposeObserver) {
  14432. this.onDisposeObservable.remove(this._onDisposeObserver);
  14433. }
  14434. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14435. },
  14436. enumerable: true,
  14437. configurable: true
  14438. });
  14439. Object.defineProperty(Scene.prototype, "beforeRender", {
  14440. set: function (callback) {
  14441. if (this._onBeforeRenderObserver) {
  14442. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14443. }
  14444. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14445. },
  14446. enumerable: true,
  14447. configurable: true
  14448. });
  14449. Object.defineProperty(Scene.prototype, "afterRender", {
  14450. set: function (callback) {
  14451. if (this._onAfterRenderObserver) {
  14452. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14453. }
  14454. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14455. },
  14456. enumerable: true,
  14457. configurable: true
  14458. });
  14459. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14460. set: function (callback) {
  14461. if (this._onBeforeCameraRenderObserver) {
  14462. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14463. }
  14464. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14470. set: function (callback) {
  14471. if (this._onAfterCameraRenderObserver) {
  14472. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14473. }
  14474. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14475. },
  14476. enumerable: true,
  14477. configurable: true
  14478. });
  14479. Object.defineProperty(Scene.prototype, "debugLayer", {
  14480. // Properties
  14481. get: function () {
  14482. return this._debugLayer;
  14483. },
  14484. enumerable: true,
  14485. configurable: true
  14486. });
  14487. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14488. get: function () {
  14489. return this._workerCollisions;
  14490. },
  14491. set: function (enabled) {
  14492. enabled = (enabled && !!Worker);
  14493. this._workerCollisions = enabled;
  14494. if (this.collisionCoordinator) {
  14495. this.collisionCoordinator.destroy();
  14496. }
  14497. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14498. this.collisionCoordinator.init(this);
  14499. },
  14500. enumerable: true,
  14501. configurable: true
  14502. });
  14503. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14504. get: function () {
  14505. return this._selectionOctree;
  14506. },
  14507. enumerable: true,
  14508. configurable: true
  14509. });
  14510. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14511. /**
  14512. * The mesh that is currently under the pointer.
  14513. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14514. */
  14515. get: function () {
  14516. return this._pointerOverMesh;
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(Scene.prototype, "pointerX", {
  14522. /**
  14523. * Current on-screen X position of the pointer
  14524. * @return {number} X position of the pointer
  14525. */
  14526. get: function () {
  14527. return this._pointerX;
  14528. },
  14529. enumerable: true,
  14530. configurable: true
  14531. });
  14532. Object.defineProperty(Scene.prototype, "pointerY", {
  14533. /**
  14534. * Current on-screen Y position of the pointer
  14535. * @return {number} Y position of the pointer
  14536. */
  14537. get: function () {
  14538. return this._pointerY;
  14539. },
  14540. enumerable: true,
  14541. configurable: true
  14542. });
  14543. Scene.prototype.getCachedMaterial = function () {
  14544. return this._cachedMaterial;
  14545. };
  14546. Scene.prototype.getBoundingBoxRenderer = function () {
  14547. return this._boundingBoxRenderer;
  14548. };
  14549. Scene.prototype.getOutlineRenderer = function () {
  14550. return this._outlineRenderer;
  14551. };
  14552. Scene.prototype.getEngine = function () {
  14553. return this._engine;
  14554. };
  14555. Scene.prototype.getTotalVertices = function () {
  14556. return this._totalVertices;
  14557. };
  14558. Scene.prototype.getActiveIndices = function () {
  14559. return this._activeIndices;
  14560. };
  14561. Scene.prototype.getActiveParticles = function () {
  14562. return this._activeParticles;
  14563. };
  14564. Scene.prototype.getActiveBones = function () {
  14565. return this._activeBones;
  14566. };
  14567. // Stats
  14568. Scene.prototype.getLastFrameDuration = function () {
  14569. return this._lastFrameDuration;
  14570. };
  14571. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14572. return this._evaluateActiveMeshesDuration;
  14573. };
  14574. Scene.prototype.getActiveMeshes = function () {
  14575. return this._activeMeshes;
  14576. };
  14577. Scene.prototype.getRenderTargetsDuration = function () {
  14578. return this._renderTargetsDuration;
  14579. };
  14580. Scene.prototype.getRenderDuration = function () {
  14581. return this._renderDuration;
  14582. };
  14583. Scene.prototype.getParticlesDuration = function () {
  14584. return this._particlesDuration;
  14585. };
  14586. Scene.prototype.getSpritesDuration = function () {
  14587. return this._spritesDuration;
  14588. };
  14589. Scene.prototype.getAnimationRatio = function () {
  14590. return this._animationRatio;
  14591. };
  14592. Scene.prototype.getRenderId = function () {
  14593. return this._renderId;
  14594. };
  14595. Scene.prototype.incrementRenderId = function () {
  14596. this._renderId++;
  14597. };
  14598. Scene.prototype._updatePointerPosition = function (evt) {
  14599. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14600. this._pointerX = evt.clientX - canvasRect.left;
  14601. this._pointerY = evt.clientY - canvasRect.top;
  14602. this._unTranslatedPointerX = this._pointerX;
  14603. this._unTranslatedPointerY = this._pointerY;
  14604. if (this.cameraToUseForPointers) {
  14605. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14606. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14607. }
  14608. };
  14609. // Pointers handling
  14610. /**
  14611. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14612. * @param attachUp defines if you want to attach events to pointerup
  14613. * @param attachDown defines if you want to attach events to pointerdown
  14614. * @param attachMove defines if you want to attach events to pointermove
  14615. */
  14616. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14617. var _this = this;
  14618. if (attachUp === void 0) { attachUp = true; }
  14619. if (attachDown === void 0) { attachDown = true; }
  14620. if (attachMove === void 0) { attachMove = true; }
  14621. var spritePredicate = function (sprite) {
  14622. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14623. };
  14624. this._onPointerMove = function (evt) {
  14625. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14626. return;
  14627. }
  14628. var canvas = _this._engine.getRenderingCanvas();
  14629. _this._updatePointerPosition(evt);
  14630. if (!_this.pointerMovePredicate) {
  14631. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14632. }
  14633. // Meshes
  14634. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14635. if (pickResult.hit && pickResult.pickedMesh) {
  14636. _this.setPointerOverSprite(null);
  14637. _this.setPointerOverMesh(pickResult.pickedMesh);
  14638. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14639. canvas.style.cursor = "pointer";
  14640. }
  14641. else {
  14642. canvas.style.cursor = "";
  14643. }
  14644. }
  14645. else {
  14646. _this.setPointerOverMesh(null);
  14647. // Sprites
  14648. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14649. if (pickResult.hit && pickResult.pickedSprite) {
  14650. canvas.style.cursor = "pointer";
  14651. _this.setPointerOverSprite(pickResult.pickedSprite);
  14652. }
  14653. else {
  14654. _this.setPointerOverSprite(null);
  14655. // Restore pointer
  14656. canvas.style.cursor = "";
  14657. }
  14658. }
  14659. if (_this.onPointerMove) {
  14660. _this.onPointerMove(evt, pickResult);
  14661. }
  14662. if (_this.onPointerObservable.hasObservers()) {
  14663. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14664. var pi = new PointerInfo(type, evt, pickResult);
  14665. _this.onPointerObservable.notifyObservers(pi, type);
  14666. }
  14667. };
  14668. this._onPointerDown = function (evt) {
  14669. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14670. return;
  14671. }
  14672. _this._updatePointerPosition(evt);
  14673. _this._startingPointerPosition.x = _this._pointerX;
  14674. _this._startingPointerPosition.y = _this._pointerY;
  14675. _this._startingPointerTime = new Date().getTime();
  14676. if (!_this.pointerDownPredicate) {
  14677. _this.pointerDownPredicate = function (mesh) {
  14678. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14679. };
  14680. }
  14681. // Meshes
  14682. _this._pickedDownMesh = null;
  14683. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14684. if (pickResult.hit && pickResult.pickedMesh) {
  14685. if (pickResult.pickedMesh.actionManager) {
  14686. _this._pickedDownMesh = pickResult.pickedMesh;
  14687. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14688. switch (evt.button) {
  14689. case 0:
  14690. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14691. break;
  14692. case 1:
  14693. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14694. break;
  14695. case 2:
  14696. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14697. break;
  14698. }
  14699. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14700. }
  14701. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14702. var that = _this;
  14703. window.setTimeout(function () {
  14704. 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);
  14705. if (pickResult.hit && pickResult.pickedMesh) {
  14706. if (pickResult.pickedMesh.actionManager) {
  14707. 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)) {
  14708. that._startingPointerTime = 0;
  14709. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14710. }
  14711. }
  14712. }
  14713. }, BABYLON.ActionManager.LongPressDelay);
  14714. }
  14715. }
  14716. }
  14717. if (_this.onPointerDown) {
  14718. _this.onPointerDown(evt, pickResult);
  14719. }
  14720. if (_this.onPointerObservable.hasObservers()) {
  14721. var type = PointerEventTypes.POINTERDOWN;
  14722. var pi = new PointerInfo(type, evt, pickResult);
  14723. _this.onPointerObservable.notifyObservers(pi, type);
  14724. }
  14725. // Sprites
  14726. _this._pickedDownSprite = null;
  14727. if (_this.spriteManagers.length > 0) {
  14728. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14729. if (pickResult.hit && pickResult.pickedSprite) {
  14730. if (pickResult.pickedSprite.actionManager) {
  14731. _this._pickedDownSprite = pickResult.pickedSprite;
  14732. switch (evt.button) {
  14733. case 0:
  14734. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14735. break;
  14736. case 1:
  14737. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14738. break;
  14739. case 2:
  14740. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14741. break;
  14742. }
  14743. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14744. }
  14745. }
  14746. }
  14747. };
  14748. this._onPointerUp = function (evt) {
  14749. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14750. return;
  14751. }
  14752. _this._updatePointerPosition(evt);
  14753. if (!_this.pointerUpPredicate) {
  14754. _this.pointerUpPredicate = function (mesh) {
  14755. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14756. };
  14757. }
  14758. // Meshes
  14759. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14760. if (pickResult.hit && pickResult.pickedMesh) {
  14761. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14762. if (_this.onPointerPick) {
  14763. _this.onPointerPick(evt, pickResult);
  14764. }
  14765. if (_this.onPointerObservable.hasObservers()) {
  14766. var type = PointerEventTypes.POINTERPICK;
  14767. var pi = new PointerInfo(type, evt, pickResult);
  14768. _this.onPointerObservable.notifyObservers(pi, type);
  14769. }
  14770. }
  14771. if (pickResult.pickedMesh.actionManager) {
  14772. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14773. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14774. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14775. }
  14776. }
  14777. }
  14778. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14779. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14780. }
  14781. if (_this.onPointerUp) {
  14782. _this.onPointerUp(evt, pickResult);
  14783. }
  14784. if (_this.onPointerObservable.hasObservers()) {
  14785. var type = PointerEventTypes.POINTERUP;
  14786. var pi = new PointerInfo(type, evt, pickResult);
  14787. _this.onPointerObservable.notifyObservers(pi, type);
  14788. }
  14789. _this._startingPointerTime = 0;
  14790. // Sprites
  14791. if (_this.spriteManagers.length > 0) {
  14792. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14793. if (pickResult.hit && pickResult.pickedSprite) {
  14794. if (pickResult.pickedSprite.actionManager) {
  14795. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14796. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14797. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14798. }
  14799. }
  14800. }
  14801. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14802. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14803. }
  14804. }
  14805. };
  14806. this._onKeyDown = function (evt) {
  14807. if (_this.actionManager) {
  14808. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14809. }
  14810. };
  14811. this._onKeyUp = function (evt) {
  14812. if (_this.actionManager) {
  14813. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14814. }
  14815. };
  14816. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14817. if (attachMove) {
  14818. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14819. // Wheel
  14820. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14821. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14822. }
  14823. if (attachDown) {
  14824. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14825. }
  14826. if (attachUp) {
  14827. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14828. }
  14829. BABYLON.Tools.RegisterTopRootEvents([
  14830. { name: "keydown", handler: this._onKeyDown },
  14831. { name: "keyup", handler: this._onKeyUp }
  14832. ]);
  14833. };
  14834. Scene.prototype.detachControl = function () {
  14835. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14836. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14837. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14838. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14839. // Wheel
  14840. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14841. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14842. BABYLON.Tools.UnregisterTopRootEvents([
  14843. { name: "keydown", handler: this._onKeyDown },
  14844. { name: "keyup", handler: this._onKeyUp }
  14845. ]);
  14846. };
  14847. // Ready
  14848. Scene.prototype.isReady = function () {
  14849. if (this._pendingData.length > 0) {
  14850. return false;
  14851. }
  14852. var index;
  14853. for (index = 0; index < this._geometries.length; index++) {
  14854. var geometry = this._geometries[index];
  14855. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14856. return false;
  14857. }
  14858. }
  14859. for (index = 0; index < this.meshes.length; index++) {
  14860. var mesh = this.meshes[index];
  14861. if (!mesh.isReady()) {
  14862. return false;
  14863. }
  14864. var mat = mesh.material;
  14865. if (mat) {
  14866. if (!mat.isReady(mesh)) {
  14867. return false;
  14868. }
  14869. }
  14870. }
  14871. return true;
  14872. };
  14873. Scene.prototype.resetCachedMaterial = function () {
  14874. this._cachedMaterial = null;
  14875. };
  14876. Scene.prototype.registerBeforeRender = function (func) {
  14877. this.onBeforeRenderObservable.add(func);
  14878. };
  14879. Scene.prototype.unregisterBeforeRender = function (func) {
  14880. this.onBeforeRenderObservable.removeCallback(func);
  14881. };
  14882. Scene.prototype.registerAfterRender = function (func) {
  14883. this.onAfterRenderObservable.add(func);
  14884. };
  14885. Scene.prototype.unregisterAfterRender = function (func) {
  14886. this.onAfterRenderObservable.removeCallback(func);
  14887. };
  14888. Scene.prototype._addPendingData = function (data) {
  14889. this._pendingData.push(data);
  14890. };
  14891. Scene.prototype._removePendingData = function (data) {
  14892. var index = this._pendingData.indexOf(data);
  14893. if (index !== -1) {
  14894. this._pendingData.splice(index, 1);
  14895. }
  14896. };
  14897. Scene.prototype.getWaitingItemsCount = function () {
  14898. return this._pendingData.length;
  14899. };
  14900. /**
  14901. * Registers a function to be executed when the scene is ready.
  14902. * @param {Function} func - the function to be executed.
  14903. */
  14904. Scene.prototype.executeWhenReady = function (func) {
  14905. var _this = this;
  14906. this.onReadyObservable.add(func);
  14907. if (this._executeWhenReadyTimeoutId !== -1) {
  14908. return;
  14909. }
  14910. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14911. _this._checkIsReady();
  14912. }, 150);
  14913. };
  14914. Scene.prototype._checkIsReady = function () {
  14915. var _this = this;
  14916. if (this.isReady()) {
  14917. this.onReadyObservable.notifyObservers(this);
  14918. this.onReadyObservable.clear();
  14919. this._executeWhenReadyTimeoutId = -1;
  14920. return;
  14921. }
  14922. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14923. _this._checkIsReady();
  14924. }, 150);
  14925. };
  14926. // Animations
  14927. /**
  14928. * Will start the animation sequence of a given target
  14929. * @param target - the target
  14930. * @param {number} from - from which frame should animation start
  14931. * @param {number} to - till which frame should animation run.
  14932. * @param {boolean} [loop] - should the animation loop
  14933. * @param {number} [speedRatio] - the speed in which to run the animation
  14934. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14935. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14936. * @return {BABYLON.Animatable} the animatable object created for this animation
  14937. * @see BABYLON.Animatable
  14938. * @see http://doc.babylonjs.com/page.php?p=22081
  14939. */
  14940. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14941. if (speedRatio === void 0) { speedRatio = 1.0; }
  14942. this.stopAnimation(target);
  14943. if (!animatable) {
  14944. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14945. }
  14946. // Local animations
  14947. if (target.animations) {
  14948. animatable.appendAnimations(target, target.animations);
  14949. }
  14950. // Children animations
  14951. if (target.getAnimatables) {
  14952. var animatables = target.getAnimatables();
  14953. for (var index = 0; index < animatables.length; index++) {
  14954. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14955. }
  14956. }
  14957. animatable.reset();
  14958. return animatable;
  14959. };
  14960. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14961. if (speedRatio === undefined) {
  14962. speedRatio = 1.0;
  14963. }
  14964. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14965. return animatable;
  14966. };
  14967. Scene.prototype.getAnimatableByTarget = function (target) {
  14968. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14969. if (this._activeAnimatables[index].target === target) {
  14970. return this._activeAnimatables[index];
  14971. }
  14972. }
  14973. return null;
  14974. };
  14975. Object.defineProperty(Scene.prototype, "Animatables", {
  14976. get: function () {
  14977. return this._activeAnimatables;
  14978. },
  14979. enumerable: true,
  14980. configurable: true
  14981. });
  14982. /**
  14983. * Will stop the animation of the given target
  14984. * @param target - the target
  14985. * @see beginAnimation
  14986. */
  14987. Scene.prototype.stopAnimation = function (target) {
  14988. var animatable = this.getAnimatableByTarget(target);
  14989. if (animatable) {
  14990. animatable.stop();
  14991. }
  14992. };
  14993. Scene.prototype._animate = function () {
  14994. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14995. return;
  14996. }
  14997. if (!this._animationStartDate) {
  14998. if (this._pendingData.length > 0) {
  14999. return;
  15000. }
  15001. this._animationStartDate = BABYLON.Tools.Now;
  15002. }
  15003. // Getting time
  15004. var now = BABYLON.Tools.Now;
  15005. var delay = now - this._animationStartDate;
  15006. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15007. this._activeAnimatables[index]._animate(delay);
  15008. }
  15009. };
  15010. // Matrix
  15011. Scene.prototype.getViewMatrix = function () {
  15012. return this._viewMatrix;
  15013. };
  15014. Scene.prototype.getProjectionMatrix = function () {
  15015. return this._projectionMatrix;
  15016. };
  15017. Scene.prototype.getTransformMatrix = function () {
  15018. return this._transformMatrix;
  15019. };
  15020. Scene.prototype.setTransformMatrix = function (view, projection) {
  15021. this._viewMatrix = view;
  15022. this._projectionMatrix = projection;
  15023. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15024. };
  15025. // Methods
  15026. Scene.prototype.addMesh = function (newMesh) {
  15027. newMesh.uniqueId = this._uniqueIdCounter++;
  15028. var position = this.meshes.push(newMesh);
  15029. //notify the collision coordinator
  15030. this.collisionCoordinator.onMeshAdded(newMesh);
  15031. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15032. };
  15033. Scene.prototype.removeMesh = function (toRemove) {
  15034. var index = this.meshes.indexOf(toRemove);
  15035. if (index !== -1) {
  15036. // Remove from the scene if mesh found
  15037. this.meshes.splice(index, 1);
  15038. }
  15039. //notify the collision coordinator
  15040. this.collisionCoordinator.onMeshRemoved(toRemove);
  15041. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15042. return index;
  15043. };
  15044. Scene.prototype.removeSkeleton = function (toRemove) {
  15045. var index = this.skeletons.indexOf(toRemove);
  15046. if (index !== -1) {
  15047. // Remove from the scene if mesh found
  15048. this.skeletons.splice(index, 1);
  15049. }
  15050. return index;
  15051. };
  15052. Scene.prototype.removeLight = function (toRemove) {
  15053. var index = this.lights.indexOf(toRemove);
  15054. if (index !== -1) {
  15055. // Remove from the scene if mesh found
  15056. this.lights.splice(index, 1);
  15057. }
  15058. this.onLightRemovedObservable.notifyObservers(toRemove);
  15059. return index;
  15060. };
  15061. Scene.prototype.removeCamera = function (toRemove) {
  15062. var index = this.cameras.indexOf(toRemove);
  15063. if (index !== -1) {
  15064. // Remove from the scene if mesh found
  15065. this.cameras.splice(index, 1);
  15066. }
  15067. // Remove from activeCameras
  15068. var index2 = this.activeCameras.indexOf(toRemove);
  15069. if (index2 !== -1) {
  15070. // Remove from the scene if mesh found
  15071. this.activeCameras.splice(index2, 1);
  15072. }
  15073. // Reset the activeCamera
  15074. if (this.activeCamera === toRemove) {
  15075. if (this.cameras.length > 0) {
  15076. this.activeCamera = this.cameras[0];
  15077. }
  15078. else {
  15079. this.activeCamera = null;
  15080. }
  15081. }
  15082. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15083. return index;
  15084. };
  15085. Scene.prototype.addLight = function (newLight) {
  15086. newLight.uniqueId = this._uniqueIdCounter++;
  15087. var position = this.lights.push(newLight);
  15088. this.onNewLightAddedObservable.notifyObservers(newLight);
  15089. };
  15090. Scene.prototype.addCamera = function (newCamera) {
  15091. newCamera.uniqueId = this._uniqueIdCounter++;
  15092. var position = this.cameras.push(newCamera);
  15093. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15094. };
  15095. /**
  15096. * Switch active camera
  15097. * @param {Camera} newCamera - new active camera
  15098. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15099. */
  15100. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15101. if (attachControl === void 0) { attachControl = true; }
  15102. var canvas = this._engine.getRenderingCanvas();
  15103. this.activeCamera.detachControl(canvas);
  15104. this.activeCamera = newCamera;
  15105. if (attachControl) {
  15106. newCamera.attachControl(canvas);
  15107. }
  15108. };
  15109. /**
  15110. * sets the active camera of the scene using its ID
  15111. * @param {string} id - the camera's ID
  15112. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15113. * @see activeCamera
  15114. */
  15115. Scene.prototype.setActiveCameraByID = function (id) {
  15116. var camera = this.getCameraByID(id);
  15117. if (camera) {
  15118. this.activeCamera = camera;
  15119. return camera;
  15120. }
  15121. return null;
  15122. };
  15123. /**
  15124. * sets the active camera of the scene using its name
  15125. * @param {string} name - the camera's name
  15126. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15127. * @see activeCamera
  15128. */
  15129. Scene.prototype.setActiveCameraByName = function (name) {
  15130. var camera = this.getCameraByName(name);
  15131. if (camera) {
  15132. this.activeCamera = camera;
  15133. return camera;
  15134. }
  15135. return null;
  15136. };
  15137. /**
  15138. * get a material using its id
  15139. * @param {string} the material's ID
  15140. * @return {BABYLON.Material|null} the material or null if none found.
  15141. */
  15142. Scene.prototype.getMaterialByID = function (id) {
  15143. for (var index = 0; index < this.materials.length; index++) {
  15144. if (this.materials[index].id === id) {
  15145. return this.materials[index];
  15146. }
  15147. }
  15148. return null;
  15149. };
  15150. /**
  15151. * get a material using its name
  15152. * @param {string} the material's name
  15153. * @return {BABYLON.Material|null} the material or null if none found.
  15154. */
  15155. Scene.prototype.getMaterialByName = function (name) {
  15156. for (var index = 0; index < this.materials.length; index++) {
  15157. if (this.materials[index].name === name) {
  15158. return this.materials[index];
  15159. }
  15160. }
  15161. return null;
  15162. };
  15163. Scene.prototype.getLensFlareSystemByName = function (name) {
  15164. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15165. if (this.lensFlareSystems[index].name === name) {
  15166. return this.lensFlareSystems[index];
  15167. }
  15168. }
  15169. return null;
  15170. };
  15171. Scene.prototype.getLensFlareSystemByID = function (id) {
  15172. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15173. if (this.lensFlareSystems[index].id === id) {
  15174. return this.lensFlareSystems[index];
  15175. }
  15176. }
  15177. return null;
  15178. };
  15179. Scene.prototype.getCameraByID = function (id) {
  15180. for (var index = 0; index < this.cameras.length; index++) {
  15181. if (this.cameras[index].id === id) {
  15182. return this.cameras[index];
  15183. }
  15184. }
  15185. return null;
  15186. };
  15187. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15188. for (var index = 0; index < this.cameras.length; index++) {
  15189. if (this.cameras[index].uniqueId === uniqueId) {
  15190. return this.cameras[index];
  15191. }
  15192. }
  15193. return null;
  15194. };
  15195. /**
  15196. * get a camera using its name
  15197. * @param {string} the camera's name
  15198. * @return {BABYLON.Camera|null} the camera or null if none found.
  15199. */
  15200. Scene.prototype.getCameraByName = function (name) {
  15201. for (var index = 0; index < this.cameras.length; index++) {
  15202. if (this.cameras[index].name === name) {
  15203. return this.cameras[index];
  15204. }
  15205. }
  15206. return null;
  15207. };
  15208. /**
  15209. * get a bone using its id
  15210. * @param {string} the bone's id
  15211. * @return {BABYLON.Bone|null} the bone or null if not found
  15212. */
  15213. Scene.prototype.getBoneByID = function (id) {
  15214. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15215. var skeleton = this.skeletons[skeletonIndex];
  15216. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15217. if (skeleton.bones[boneIndex].id === id) {
  15218. return skeleton.bones[boneIndex];
  15219. }
  15220. }
  15221. }
  15222. return null;
  15223. };
  15224. /**
  15225. * get a bone using its id
  15226. * @param {string} the bone's name
  15227. * @return {BABYLON.Bone|null} the bone or null if not found
  15228. */
  15229. Scene.prototype.getBoneByName = function (name) {
  15230. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15231. var skeleton = this.skeletons[skeletonIndex];
  15232. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15233. if (skeleton.bones[boneIndex].name === name) {
  15234. return skeleton.bones[boneIndex];
  15235. }
  15236. }
  15237. }
  15238. return null;
  15239. };
  15240. /**
  15241. * get a light node using its name
  15242. * @param {string} the light's name
  15243. * @return {BABYLON.Light|null} the light or null if none found.
  15244. */
  15245. Scene.prototype.getLightByName = function (name) {
  15246. for (var index = 0; index < this.lights.length; index++) {
  15247. if (this.lights[index].name === name) {
  15248. return this.lights[index];
  15249. }
  15250. }
  15251. return null;
  15252. };
  15253. /**
  15254. * get a light node using its ID
  15255. * @param {string} the light's id
  15256. * @return {BABYLON.Light|null} the light or null if none found.
  15257. */
  15258. Scene.prototype.getLightByID = function (id) {
  15259. for (var index = 0; index < this.lights.length; index++) {
  15260. if (this.lights[index].id === id) {
  15261. return this.lights[index];
  15262. }
  15263. }
  15264. return null;
  15265. };
  15266. /**
  15267. * get a light node using its scene-generated unique ID
  15268. * @param {number} the light's unique id
  15269. * @return {BABYLON.Light|null} the light or null if none found.
  15270. */
  15271. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15272. for (var index = 0; index < this.lights.length; index++) {
  15273. if (this.lights[index].uniqueId === uniqueId) {
  15274. return this.lights[index];
  15275. }
  15276. }
  15277. return null;
  15278. };
  15279. /**
  15280. * get a particle system by id
  15281. * @param id {number} the particle system id
  15282. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15283. */
  15284. Scene.prototype.getParticleSystemByID = function (id) {
  15285. for (var index = 0; index < this.particleSystems.length; index++) {
  15286. if (this.particleSystems[index].id === id) {
  15287. return this.particleSystems[index];
  15288. }
  15289. }
  15290. return null;
  15291. };
  15292. /**
  15293. * get a geometry using its ID
  15294. * @param {string} the geometry's id
  15295. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15296. */
  15297. Scene.prototype.getGeometryByID = function (id) {
  15298. for (var index = 0; index < this._geometries.length; index++) {
  15299. if (this._geometries[index].id === id) {
  15300. return this._geometries[index];
  15301. }
  15302. }
  15303. return null;
  15304. };
  15305. /**
  15306. * add a new geometry to this scene.
  15307. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15308. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15309. * @return {boolean} was the geometry added or not
  15310. */
  15311. Scene.prototype.pushGeometry = function (geometry, force) {
  15312. if (!force && this.getGeometryByID(geometry.id)) {
  15313. return false;
  15314. }
  15315. this._geometries.push(geometry);
  15316. //notify the collision coordinator
  15317. this.collisionCoordinator.onGeometryAdded(geometry);
  15318. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15319. return true;
  15320. };
  15321. /**
  15322. * Removes an existing geometry
  15323. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15324. * @return {boolean} was the geometry removed or not
  15325. */
  15326. Scene.prototype.removeGeometry = function (geometry) {
  15327. var index = this._geometries.indexOf(geometry);
  15328. if (index > -1) {
  15329. this._geometries.splice(index, 1);
  15330. //notify the collision coordinator
  15331. this.collisionCoordinator.onGeometryDeleted(geometry);
  15332. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15333. return true;
  15334. }
  15335. return false;
  15336. };
  15337. Scene.prototype.getGeometries = function () {
  15338. return this._geometries;
  15339. };
  15340. /**
  15341. * Get the first added mesh found of a given ID
  15342. * @param {string} id - the id to search for
  15343. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15344. */
  15345. Scene.prototype.getMeshByID = function (id) {
  15346. for (var index = 0; index < this.meshes.length; index++) {
  15347. if (this.meshes[index].id === id) {
  15348. return this.meshes[index];
  15349. }
  15350. }
  15351. return null;
  15352. };
  15353. Scene.prototype.getMeshesByID = function (id) {
  15354. return this.meshes.filter(function (m) {
  15355. return m.id === id;
  15356. });
  15357. };
  15358. /**
  15359. * Get a mesh with its auto-generated unique id
  15360. * @param {number} uniqueId - the unique id to search for
  15361. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15362. */
  15363. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15364. for (var index = 0; index < this.meshes.length; index++) {
  15365. if (this.meshes[index].uniqueId === uniqueId) {
  15366. return this.meshes[index];
  15367. }
  15368. }
  15369. return null;
  15370. };
  15371. /**
  15372. * Get a the last added mesh found of a given ID
  15373. * @param {string} id - the id to search for
  15374. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15375. */
  15376. Scene.prototype.getLastMeshByID = function (id) {
  15377. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15378. if (this.meshes[index].id === id) {
  15379. return this.meshes[index];
  15380. }
  15381. }
  15382. return null;
  15383. };
  15384. /**
  15385. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15386. * @param {string} id - the id to search for
  15387. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15388. */
  15389. Scene.prototype.getLastEntryByID = function (id) {
  15390. var index;
  15391. for (index = this.meshes.length - 1; index >= 0; index--) {
  15392. if (this.meshes[index].id === id) {
  15393. return this.meshes[index];
  15394. }
  15395. }
  15396. for (index = this.cameras.length - 1; index >= 0; index--) {
  15397. if (this.cameras[index].id === id) {
  15398. return this.cameras[index];
  15399. }
  15400. }
  15401. for (index = this.lights.length - 1; index >= 0; index--) {
  15402. if (this.lights[index].id === id) {
  15403. return this.lights[index];
  15404. }
  15405. }
  15406. return null;
  15407. };
  15408. Scene.prototype.getNodeByID = function (id) {
  15409. var mesh = this.getMeshByID(id);
  15410. if (mesh) {
  15411. return mesh;
  15412. }
  15413. var light = this.getLightByID(id);
  15414. if (light) {
  15415. return light;
  15416. }
  15417. var camera = this.getCameraByID(id);
  15418. if (camera) {
  15419. return camera;
  15420. }
  15421. var bone = this.getBoneByID(id);
  15422. return bone;
  15423. };
  15424. Scene.prototype.getNodeByName = function (name) {
  15425. var mesh = this.getMeshByName(name);
  15426. if (mesh) {
  15427. return mesh;
  15428. }
  15429. var light = this.getLightByName(name);
  15430. if (light) {
  15431. return light;
  15432. }
  15433. var camera = this.getCameraByName(name);
  15434. if (camera) {
  15435. return camera;
  15436. }
  15437. var bone = this.getBoneByName(name);
  15438. return bone;
  15439. };
  15440. Scene.prototype.getMeshByName = function (name) {
  15441. for (var index = 0; index < this.meshes.length; index++) {
  15442. if (this.meshes[index].name === name) {
  15443. return this.meshes[index];
  15444. }
  15445. }
  15446. return null;
  15447. };
  15448. Scene.prototype.getSoundByName = function (name) {
  15449. var index;
  15450. if (BABYLON.AudioEngine) {
  15451. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15452. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15453. return this.mainSoundTrack.soundCollection[index];
  15454. }
  15455. }
  15456. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15457. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15458. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15459. return this.soundTracks[sdIndex].soundCollection[index];
  15460. }
  15461. }
  15462. }
  15463. }
  15464. return null;
  15465. };
  15466. Scene.prototype.getLastSkeletonByID = function (id) {
  15467. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15468. if (this.skeletons[index].id === id) {
  15469. return this.skeletons[index];
  15470. }
  15471. }
  15472. return null;
  15473. };
  15474. Scene.prototype.getSkeletonById = function (id) {
  15475. for (var index = 0; index < this.skeletons.length; index++) {
  15476. if (this.skeletons[index].id === id) {
  15477. return this.skeletons[index];
  15478. }
  15479. }
  15480. return null;
  15481. };
  15482. Scene.prototype.getSkeletonByName = function (name) {
  15483. for (var index = 0; index < this.skeletons.length; index++) {
  15484. if (this.skeletons[index].name === name) {
  15485. return this.skeletons[index];
  15486. }
  15487. }
  15488. return null;
  15489. };
  15490. Scene.prototype.isActiveMesh = function (mesh) {
  15491. return (this._activeMeshes.indexOf(mesh) !== -1);
  15492. };
  15493. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15494. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15495. var material = subMesh.getMaterial();
  15496. if (mesh.showSubMeshesBoundingBox) {
  15497. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15498. }
  15499. if (material) {
  15500. // Render targets
  15501. if (material.getRenderTargetTextures) {
  15502. if (this._processedMaterials.indexOf(material) === -1) {
  15503. this._processedMaterials.push(material);
  15504. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15505. }
  15506. }
  15507. // Dispatch
  15508. this._activeIndices += subMesh.indexCount;
  15509. this._renderingManager.dispatch(subMesh);
  15510. }
  15511. }
  15512. };
  15513. Scene.prototype._isInIntermediateRendering = function () {
  15514. return this._intermediateRendering;
  15515. };
  15516. Scene.prototype._evaluateActiveMeshes = function () {
  15517. this.activeCamera._activeMeshes.reset();
  15518. this._activeMeshes.reset();
  15519. this._renderingManager.reset();
  15520. this._processedMaterials.reset();
  15521. this._activeParticleSystems.reset();
  15522. this._activeSkeletons.reset();
  15523. this._softwareSkinnedMeshes.reset();
  15524. this._boundingBoxRenderer.reset();
  15525. this._edgesRenderers.reset();
  15526. if (!this._frustumPlanes) {
  15527. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15528. }
  15529. else {
  15530. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15531. }
  15532. // Meshes
  15533. var meshes;
  15534. var len;
  15535. if (this._selectionOctree) {
  15536. var selection = this._selectionOctree.select(this._frustumPlanes);
  15537. meshes = selection.data;
  15538. len = selection.length;
  15539. }
  15540. else {
  15541. len = this.meshes.length;
  15542. meshes = this.meshes;
  15543. }
  15544. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15545. var mesh = meshes[meshIndex];
  15546. if (mesh.isBlocked) {
  15547. continue;
  15548. }
  15549. this._totalVertices += mesh.getTotalVertices();
  15550. if (!mesh.isReady() || !mesh.isEnabled()) {
  15551. continue;
  15552. }
  15553. mesh.computeWorldMatrix();
  15554. // Intersections
  15555. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15556. this._meshesForIntersections.pushNoDuplicate(mesh);
  15557. }
  15558. // Switch to current LOD
  15559. var meshLOD = mesh.getLOD(this.activeCamera);
  15560. if (!meshLOD) {
  15561. continue;
  15562. }
  15563. mesh._preActivate();
  15564. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15565. this._activeMeshes.push(mesh);
  15566. this.activeCamera._activeMeshes.push(mesh);
  15567. mesh._activate(this._renderId);
  15568. this._activeMesh(meshLOD);
  15569. }
  15570. }
  15571. // Particle systems
  15572. var beforeParticlesDate = BABYLON.Tools.Now;
  15573. if (this.particlesEnabled) {
  15574. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15575. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15576. var particleSystem = this.particleSystems[particleIndex];
  15577. if (!particleSystem.isStarted()) {
  15578. continue;
  15579. }
  15580. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15581. this._activeParticleSystems.push(particleSystem);
  15582. particleSystem.animate();
  15583. }
  15584. }
  15585. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15586. }
  15587. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15588. };
  15589. Scene.prototype._activeMesh = function (mesh) {
  15590. if (mesh.skeleton && this.skeletonsEnabled) {
  15591. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15592. if (!mesh.computeBonesUsingShaders) {
  15593. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15594. }
  15595. }
  15596. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15597. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15598. }
  15599. if (mesh._edgesRenderer) {
  15600. this._edgesRenderers.push(mesh._edgesRenderer);
  15601. }
  15602. if (mesh && mesh.subMeshes) {
  15603. // Submeshes Octrees
  15604. var len;
  15605. var subMeshes;
  15606. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15607. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15608. len = intersections.length;
  15609. subMeshes = intersections.data;
  15610. }
  15611. else {
  15612. subMeshes = mesh.subMeshes;
  15613. len = subMeshes.length;
  15614. }
  15615. for (var subIndex = 0; subIndex < len; subIndex++) {
  15616. var subMesh = subMeshes[subIndex];
  15617. this._evaluateSubMesh(subMesh, mesh);
  15618. }
  15619. }
  15620. };
  15621. Scene.prototype.updateTransformMatrix = function (force) {
  15622. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15623. };
  15624. Scene.prototype._renderForCamera = function (camera) {
  15625. var engine = this._engine;
  15626. this.activeCamera = camera;
  15627. if (!this.activeCamera)
  15628. throw new Error("Active camera not set");
  15629. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15630. // Viewport
  15631. engine.setViewport(this.activeCamera.viewport);
  15632. // Camera
  15633. this.resetCachedMaterial();
  15634. this._renderId++;
  15635. this.updateTransformMatrix();
  15636. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15637. // Meshes
  15638. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15639. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15640. this._evaluateActiveMeshes();
  15641. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15642. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15643. // Skeletons
  15644. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15645. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15646. skeleton.prepare();
  15647. }
  15648. // Software skinning
  15649. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15650. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15651. mesh.applySkeleton(mesh.skeleton);
  15652. }
  15653. // Render targets
  15654. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15655. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15656. this._intermediateRendering = true;
  15657. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15658. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15659. var renderTarget = this._renderTargets.data[renderIndex];
  15660. if (renderTarget._shouldRender()) {
  15661. this._renderId++;
  15662. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15663. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15664. }
  15665. }
  15666. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15667. this._intermediateRendering = false;
  15668. this._renderId++;
  15669. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15670. }
  15671. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15672. // Prepare Frame
  15673. this.postProcessManager._prepareFrame();
  15674. var beforeRenderDate = BABYLON.Tools.Now;
  15675. // Backgrounds
  15676. var layerIndex;
  15677. var layer;
  15678. if (this.layers.length) {
  15679. engine.setDepthBuffer(false);
  15680. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15681. layer = this.layers[layerIndex];
  15682. if (layer.isBackground) {
  15683. layer.render();
  15684. }
  15685. }
  15686. engine.setDepthBuffer(true);
  15687. }
  15688. // Render
  15689. BABYLON.Tools.StartPerformanceCounter("Main render");
  15690. this._renderingManager.render(null, null, true, true);
  15691. BABYLON.Tools.EndPerformanceCounter("Main render");
  15692. // Bounding boxes
  15693. this._boundingBoxRenderer.render();
  15694. // Edges
  15695. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15696. this._edgesRenderers.data[edgesRendererIndex].render();
  15697. }
  15698. // Lens flares
  15699. if (this.lensFlaresEnabled) {
  15700. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15701. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15702. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15703. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15704. lensFlareSystem.render();
  15705. }
  15706. }
  15707. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15708. }
  15709. // Foregrounds
  15710. if (this.layers.length) {
  15711. engine.setDepthBuffer(false);
  15712. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15713. layer = this.layers[layerIndex];
  15714. if (!layer.isBackground) {
  15715. layer.render();
  15716. }
  15717. }
  15718. engine.setDepthBuffer(true);
  15719. }
  15720. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15721. // Finalize frame
  15722. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15723. // Update camera
  15724. this.activeCamera._updateFromScene();
  15725. // Reset some special arrays
  15726. this._renderTargets.reset();
  15727. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15728. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15729. };
  15730. Scene.prototype._processSubCameras = function (camera) {
  15731. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15732. this._renderForCamera(camera);
  15733. return;
  15734. }
  15735. // rig cameras
  15736. for (var index = 0; index < camera._rigCameras.length; index++) {
  15737. this._renderForCamera(camera._rigCameras[index]);
  15738. }
  15739. this.activeCamera = camera;
  15740. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15741. // Update camera
  15742. this.activeCamera._updateFromScene();
  15743. };
  15744. Scene.prototype._checkIntersections = function () {
  15745. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15746. var sourceMesh = this._meshesForIntersections.data[index];
  15747. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15748. var action = sourceMesh.actionManager.actions[actionIndex];
  15749. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15750. var parameters = action.getTriggerParameter();
  15751. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15752. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15753. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15754. if (areIntersecting && currentIntersectionInProgress === -1) {
  15755. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15756. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15757. sourceMesh._intersectionsInProgress.push(otherMesh);
  15758. }
  15759. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15760. sourceMesh._intersectionsInProgress.push(otherMesh);
  15761. }
  15762. }
  15763. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15764. //They intersected, and now they don't.
  15765. //is this trigger an exit trigger? execute an event.
  15766. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15767. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15768. }
  15769. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15770. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15771. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15772. }
  15773. }
  15774. }
  15775. }
  15776. }
  15777. };
  15778. Scene.prototype.render = function () {
  15779. var startDate = BABYLON.Tools.Now;
  15780. this._particlesDuration = 0;
  15781. this._spritesDuration = 0;
  15782. this._activeParticles = 0;
  15783. this._renderDuration = 0;
  15784. this._renderTargetsDuration = 0;
  15785. this._evaluateActiveMeshesDuration = 0;
  15786. this._totalVertices = 0;
  15787. this._activeIndices = 0;
  15788. this._activeBones = 0;
  15789. this.getEngine().resetDrawCalls();
  15790. this._meshesForIntersections.reset();
  15791. this.resetCachedMaterial();
  15792. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15793. // Actions
  15794. if (this.actionManager) {
  15795. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15796. }
  15797. //Simplification Queue
  15798. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15799. this.simplificationQueue.executeNext();
  15800. }
  15801. // Animations
  15802. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15803. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15804. this._animate();
  15805. // Physics
  15806. if (this._physicsEngine) {
  15807. BABYLON.Tools.StartPerformanceCounter("Physics");
  15808. this._physicsEngine._step(deltaTime / 1000.0);
  15809. BABYLON.Tools.EndPerformanceCounter("Physics");
  15810. }
  15811. // Before render
  15812. this.onBeforeRenderObservable.notifyObservers(this);
  15813. // Customs render targets
  15814. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15815. var engine = this.getEngine();
  15816. var currentActiveCamera = this.activeCamera;
  15817. if (this.renderTargetsEnabled) {
  15818. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15819. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15820. var renderTarget = this.customRenderTargets[customIndex];
  15821. if (renderTarget._shouldRender()) {
  15822. this._renderId++;
  15823. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15824. if (!this.activeCamera)
  15825. throw new Error("Active camera not set");
  15826. // Viewport
  15827. engine.setViewport(this.activeCamera.viewport);
  15828. // Camera
  15829. this.updateTransformMatrix();
  15830. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15831. }
  15832. }
  15833. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15834. this._renderId++;
  15835. }
  15836. if (this.customRenderTargets.length > 0) {
  15837. engine.restoreDefaultFramebuffer();
  15838. }
  15839. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15840. this.activeCamera = currentActiveCamera;
  15841. // Procedural textures
  15842. if (this.proceduralTexturesEnabled) {
  15843. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15844. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15845. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15846. if (proceduralTexture._shouldRender()) {
  15847. proceduralTexture.render();
  15848. }
  15849. }
  15850. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15851. }
  15852. // Clear
  15853. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15854. // Shadows
  15855. if (this.shadowsEnabled) {
  15856. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15857. var light = this.lights[lightIndex];
  15858. var shadowGenerator = light.getShadowGenerator();
  15859. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15860. this._renderTargets.push(shadowGenerator.getShadowMap());
  15861. }
  15862. }
  15863. }
  15864. // Depth renderer
  15865. if (this._depthRenderer) {
  15866. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15867. }
  15868. // RenderPipeline
  15869. this.postProcessRenderPipelineManager.update();
  15870. // Multi-cameras?
  15871. if (this.activeCameras.length > 0) {
  15872. var currentRenderId = this._renderId;
  15873. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15874. this._renderId = currentRenderId;
  15875. if (cameraIndex > 0) {
  15876. this._engine.clear(0, false, true);
  15877. }
  15878. this._processSubCameras(this.activeCameras[cameraIndex]);
  15879. }
  15880. }
  15881. else {
  15882. if (!this.activeCamera) {
  15883. throw new Error("No camera defined");
  15884. }
  15885. this._processSubCameras(this.activeCamera);
  15886. }
  15887. // Intersection checks
  15888. this._checkIntersections();
  15889. // Update the audio listener attached to the camera
  15890. if (BABYLON.AudioEngine) {
  15891. this._updateAudioParameters();
  15892. }
  15893. // After render
  15894. if (this.afterRender) {
  15895. this.afterRender();
  15896. }
  15897. this.onAfterRenderObservable.notifyObservers(this);
  15898. // Cleaning
  15899. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15900. this._toBeDisposed.data[index].dispose();
  15901. this._toBeDisposed[index] = null;
  15902. }
  15903. this._toBeDisposed.reset();
  15904. if (this.dumpNextRenderTargets) {
  15905. this.dumpNextRenderTargets = false;
  15906. }
  15907. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15908. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15909. };
  15910. Scene.prototype._updateAudioParameters = function () {
  15911. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15912. return;
  15913. }
  15914. var listeningCamera;
  15915. var audioEngine = BABYLON.Engine.audioEngine;
  15916. if (this.activeCameras.length > 0) {
  15917. listeningCamera = this.activeCameras[0];
  15918. }
  15919. else {
  15920. listeningCamera = this.activeCamera;
  15921. }
  15922. if (listeningCamera && audioEngine.canUseWebAudio) {
  15923. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15924. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15925. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15926. cameraDirection.normalize();
  15927. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15928. var i;
  15929. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15930. var sound = this.mainSoundTrack.soundCollection[i];
  15931. if (sound.useCustomAttenuation) {
  15932. sound.updateDistanceFromListener();
  15933. }
  15934. }
  15935. for (i = 0; i < this.soundTracks.length; i++) {
  15936. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15937. sound = this.soundTracks[i].soundCollection[j];
  15938. if (sound.useCustomAttenuation) {
  15939. sound.updateDistanceFromListener();
  15940. }
  15941. }
  15942. }
  15943. }
  15944. };
  15945. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15946. // Audio
  15947. get: function () {
  15948. return this._audioEnabled;
  15949. },
  15950. set: function (value) {
  15951. this._audioEnabled = value;
  15952. if (BABYLON.AudioEngine) {
  15953. if (this._audioEnabled) {
  15954. this._enableAudio();
  15955. }
  15956. else {
  15957. this._disableAudio();
  15958. }
  15959. }
  15960. },
  15961. enumerable: true,
  15962. configurable: true
  15963. });
  15964. Scene.prototype._disableAudio = function () {
  15965. var i;
  15966. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15967. this.mainSoundTrack.soundCollection[i].pause();
  15968. }
  15969. for (i = 0; i < this.soundTracks.length; i++) {
  15970. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15971. this.soundTracks[i].soundCollection[j].pause();
  15972. }
  15973. }
  15974. };
  15975. Scene.prototype._enableAudio = function () {
  15976. var i;
  15977. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15978. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15979. this.mainSoundTrack.soundCollection[i].play();
  15980. }
  15981. }
  15982. for (i = 0; i < this.soundTracks.length; i++) {
  15983. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15984. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15985. this.soundTracks[i].soundCollection[j].play();
  15986. }
  15987. }
  15988. }
  15989. };
  15990. Object.defineProperty(Scene.prototype, "headphone", {
  15991. get: function () {
  15992. return this._headphone;
  15993. },
  15994. set: function (value) {
  15995. this._headphone = value;
  15996. if (BABYLON.AudioEngine) {
  15997. if (this._headphone) {
  15998. this._switchAudioModeForHeadphones();
  15999. }
  16000. else {
  16001. this._switchAudioModeForNormalSpeakers();
  16002. }
  16003. }
  16004. },
  16005. enumerable: true,
  16006. configurable: true
  16007. });
  16008. Scene.prototype._switchAudioModeForHeadphones = function () {
  16009. this.mainSoundTrack.switchPanningModelToHRTF();
  16010. for (var i = 0; i < this.soundTracks.length; i++) {
  16011. this.soundTracks[i].switchPanningModelToHRTF();
  16012. }
  16013. };
  16014. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16015. this.mainSoundTrack.switchPanningModelToEqualPower();
  16016. for (var i = 0; i < this.soundTracks.length; i++) {
  16017. this.soundTracks[i].switchPanningModelToEqualPower();
  16018. }
  16019. };
  16020. Scene.prototype.enableDepthRenderer = function () {
  16021. if (this._depthRenderer) {
  16022. return this._depthRenderer;
  16023. }
  16024. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16025. return this._depthRenderer;
  16026. };
  16027. Scene.prototype.disableDepthRenderer = function () {
  16028. if (!this._depthRenderer) {
  16029. return;
  16030. }
  16031. this._depthRenderer.dispose();
  16032. this._depthRenderer = null;
  16033. };
  16034. Scene.prototype.freezeMaterials = function () {
  16035. for (var i = 0; i < this.materials.length; i++) {
  16036. this.materials[i].freeze();
  16037. }
  16038. };
  16039. Scene.prototype.unfreezeMaterials = function () {
  16040. for (var i = 0; i < this.materials.length; i++) {
  16041. this.materials[i].unfreeze();
  16042. }
  16043. };
  16044. Scene.prototype.dispose = function () {
  16045. this.beforeRender = null;
  16046. this.afterRender = null;
  16047. this.skeletons = [];
  16048. this._boundingBoxRenderer.dispose();
  16049. if (this._depthRenderer) {
  16050. this._depthRenderer.dispose();
  16051. }
  16052. // Debug layer
  16053. this.debugLayer.hide();
  16054. // Events
  16055. if (this.onDispose) {
  16056. this.onDispose();
  16057. }
  16058. this.onBeforeRenderObservable.clear();
  16059. this.onAfterRenderObservable.clear();
  16060. this.detachControl();
  16061. // Release sounds & sounds tracks
  16062. if (BABYLON.AudioEngine) {
  16063. this.disposeSounds();
  16064. }
  16065. // Detach cameras
  16066. var canvas = this._engine.getRenderingCanvas();
  16067. var index;
  16068. for (index = 0; index < this.cameras.length; index++) {
  16069. this.cameras[index].detachControl(canvas);
  16070. }
  16071. // Release lights
  16072. while (this.lights.length) {
  16073. this.lights[0].dispose();
  16074. }
  16075. // Release meshes
  16076. while (this.meshes.length) {
  16077. this.meshes[0].dispose(true);
  16078. }
  16079. // Release cameras
  16080. while (this.cameras.length) {
  16081. this.cameras[0].dispose();
  16082. }
  16083. // Release materials
  16084. while (this.materials.length) {
  16085. this.materials[0].dispose();
  16086. }
  16087. // Release particles
  16088. while (this.particleSystems.length) {
  16089. this.particleSystems[0].dispose();
  16090. }
  16091. // Release sprites
  16092. while (this.spriteManagers.length) {
  16093. this.spriteManagers[0].dispose();
  16094. }
  16095. // Release layers
  16096. while (this.layers.length) {
  16097. this.layers[0].dispose();
  16098. }
  16099. // Release textures
  16100. while (this.textures.length) {
  16101. this.textures[0].dispose();
  16102. }
  16103. // Post-processes
  16104. this.postProcessManager.dispose();
  16105. // Physics
  16106. if (this._physicsEngine) {
  16107. this.disablePhysicsEngine();
  16108. }
  16109. // Remove from engine
  16110. index = this._engine.scenes.indexOf(this);
  16111. if (index > -1) {
  16112. this._engine.scenes.splice(index, 1);
  16113. }
  16114. this._engine.wipeCaches();
  16115. };
  16116. // Release sounds & sounds tracks
  16117. Scene.prototype.disposeSounds = function () {
  16118. this.mainSoundTrack.dispose();
  16119. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16120. this.soundTracks[scIndex].dispose();
  16121. }
  16122. };
  16123. // Octrees
  16124. Scene.prototype.getWorldExtends = function () {
  16125. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16126. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16127. for (var index = 0; index < this.meshes.length; index++) {
  16128. var mesh = this.meshes[index];
  16129. mesh.computeWorldMatrix(true);
  16130. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16131. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16132. BABYLON.Tools.CheckExtends(minBox, min, max);
  16133. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16134. }
  16135. return {
  16136. min: min,
  16137. max: max
  16138. };
  16139. };
  16140. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16141. if (maxCapacity === void 0) { maxCapacity = 64; }
  16142. if (maxDepth === void 0) { maxDepth = 2; }
  16143. if (!this._selectionOctree) {
  16144. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16145. }
  16146. var worldExtends = this.getWorldExtends();
  16147. // Update octree
  16148. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16149. return this._selectionOctree;
  16150. };
  16151. // Picking
  16152. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16153. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16154. var engine = this._engine;
  16155. if (!camera) {
  16156. if (!this.activeCamera)
  16157. throw new Error("Active camera not set");
  16158. camera = this.activeCamera;
  16159. }
  16160. var cameraViewport = camera.viewport;
  16161. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16162. // Moving coordinates to local viewport world
  16163. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16164. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16165. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16166. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16167. };
  16168. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16169. var engine = this._engine;
  16170. if (!camera) {
  16171. if (!this.activeCamera)
  16172. throw new Error("Active camera not set");
  16173. camera = this.activeCamera;
  16174. }
  16175. var cameraViewport = camera.viewport;
  16176. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16177. var identity = BABYLON.Matrix.Identity();
  16178. // Moving coordinates to local viewport world
  16179. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16180. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16181. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16182. };
  16183. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16184. var pickingInfo = null;
  16185. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16186. var mesh = this.meshes[meshIndex];
  16187. if (predicate) {
  16188. if (!predicate(mesh)) {
  16189. continue;
  16190. }
  16191. }
  16192. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16193. continue;
  16194. }
  16195. var world = mesh.getWorldMatrix();
  16196. var ray = rayFunction(world);
  16197. var result = mesh.intersects(ray, fastCheck);
  16198. if (!result || !result.hit)
  16199. continue;
  16200. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16201. continue;
  16202. pickingInfo = result;
  16203. if (fastCheck) {
  16204. break;
  16205. }
  16206. }
  16207. return pickingInfo || new BABYLON.PickingInfo();
  16208. };
  16209. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16210. var pickingInfo = null;
  16211. camera = camera || this.activeCamera;
  16212. if (this.spriteManagers.length > 0) {
  16213. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16214. var spriteManager = this.spriteManagers[spriteIndex];
  16215. if (!spriteManager.isPickable) {
  16216. continue;
  16217. }
  16218. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16219. if (!result || !result.hit)
  16220. continue;
  16221. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16222. continue;
  16223. pickingInfo = result;
  16224. if (fastCheck) {
  16225. break;
  16226. }
  16227. }
  16228. }
  16229. return pickingInfo || new BABYLON.PickingInfo();
  16230. };
  16231. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16232. var _this = this;
  16233. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16234. /// <param name="x">X position on screen</param>
  16235. /// <param name="y">Y position on screen</param>
  16236. /// <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>
  16237. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16238. /// <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>
  16239. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16240. };
  16241. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16242. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16243. /// <param name="x">X position on screen</param>
  16244. /// <param name="y">Y position on screen</param>
  16245. /// <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>
  16246. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16247. /// <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>
  16248. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16249. };
  16250. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16251. var _this = this;
  16252. return this._internalPick(function (world) {
  16253. if (!_this._pickWithRayInverseMatrix) {
  16254. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16255. }
  16256. world.invertToRef(_this._pickWithRayInverseMatrix);
  16257. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16258. }, predicate, fastCheck);
  16259. };
  16260. Scene.prototype.setPointerOverMesh = function (mesh) {
  16261. if (this._pointerOverMesh === mesh) {
  16262. return;
  16263. }
  16264. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16265. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16266. }
  16267. this._pointerOverMesh = mesh;
  16268. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16269. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16270. }
  16271. };
  16272. Scene.prototype.getPointerOverMesh = function () {
  16273. return this._pointerOverMesh;
  16274. };
  16275. Scene.prototype.setPointerOverSprite = function (sprite) {
  16276. if (this._pointerOverSprite === sprite) {
  16277. return;
  16278. }
  16279. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16280. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16281. }
  16282. this._pointerOverSprite = sprite;
  16283. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16284. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16285. }
  16286. };
  16287. Scene.prototype.getPointerOverSprite = function () {
  16288. return this._pointerOverSprite;
  16289. };
  16290. // Physics
  16291. Scene.prototype.getPhysicsEngine = function () {
  16292. return this._physicsEngine;
  16293. };
  16294. /**
  16295. * Enables physics to the current scene
  16296. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16297. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16298. * @return {boolean} was the physics engine initialized
  16299. */
  16300. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16301. if (this._physicsEngine) {
  16302. return true;
  16303. }
  16304. try {
  16305. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16306. return true;
  16307. }
  16308. catch (e) {
  16309. BABYLON.Tools.Error(e.message);
  16310. return false;
  16311. }
  16312. };
  16313. Scene.prototype.disablePhysicsEngine = function () {
  16314. if (!this._physicsEngine) {
  16315. return;
  16316. }
  16317. this._physicsEngine.dispose();
  16318. this._physicsEngine = undefined;
  16319. };
  16320. Scene.prototype.isPhysicsEnabled = function () {
  16321. return this._physicsEngine !== undefined;
  16322. };
  16323. /**
  16324. *
  16325. * Sets the gravity of the physics engine (and NOT of the scene)
  16326. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16327. */
  16328. Scene.prototype.setGravity = function (gravity) {
  16329. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16330. if (!this._physicsEngine) {
  16331. return;
  16332. }
  16333. this._physicsEngine.setGravity(gravity);
  16334. };
  16335. /**
  16336. * Legacy support, using the new API
  16337. * @Deprecated
  16338. */
  16339. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16340. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16341. if (parts.parts) {
  16342. options = parts;
  16343. parts = parts.parts;
  16344. }
  16345. var mainMesh = parts[0].mesh;
  16346. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16347. for (var index = 1; index < parts.length; index++) {
  16348. var mesh = parts[index].mesh;
  16349. if (mesh.parent !== mainMesh) {
  16350. mesh.position = mesh.position.subtract(mainMesh.position);
  16351. mesh.parent = mainMesh;
  16352. }
  16353. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16354. }
  16355. mainMesh.physicsImpostor.forceUpdate();
  16356. };
  16357. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16358. var mesh = compound.parts[0].mesh;
  16359. mesh.physicsImpostor.dispose();
  16360. mesh.physicsImpostor = null;
  16361. };
  16362. // Misc.
  16363. Scene.prototype.createDefaultCameraOrLight = function () {
  16364. // Light
  16365. if (this.lights.length === 0) {
  16366. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16367. }
  16368. // Camera
  16369. if (!this.activeCamera) {
  16370. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16371. // Compute position
  16372. var worldExtends = this.getWorldExtends();
  16373. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16374. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16375. camera.setTarget(worldCenter);
  16376. this.activeCamera = camera;
  16377. }
  16378. };
  16379. // Tags
  16380. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16381. if (tagsQuery === undefined) {
  16382. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16383. return list;
  16384. }
  16385. var listByTags = [];
  16386. forEach = forEach || (function (item) { return; });
  16387. for (var i in list) {
  16388. var item = list[i];
  16389. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16390. listByTags.push(item);
  16391. forEach(item);
  16392. }
  16393. }
  16394. return listByTags;
  16395. };
  16396. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16397. return this._getByTags(this.meshes, tagsQuery, forEach);
  16398. };
  16399. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16400. return this._getByTags(this.cameras, tagsQuery, forEach);
  16401. };
  16402. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16403. return this._getByTags(this.lights, tagsQuery, forEach);
  16404. };
  16405. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16406. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16407. };
  16408. // Statics
  16409. Scene._FOGMODE_NONE = 0;
  16410. Scene._FOGMODE_EXP = 1;
  16411. Scene._FOGMODE_EXP2 = 2;
  16412. Scene._FOGMODE_LINEAR = 3;
  16413. Scene.MinDeltaTime = 1.0;
  16414. Scene.MaxDeltaTime = 1000.0;
  16415. return Scene;
  16416. })();
  16417. BABYLON.Scene = Scene;
  16418. })(BABYLON || (BABYLON = {}));
  16419. var BABYLON;
  16420. (function (BABYLON) {
  16421. var VertexBuffer = (function () {
  16422. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16423. if (engine instanceof BABYLON.Mesh) {
  16424. this._engine = engine.getScene().getEngine();
  16425. }
  16426. else {
  16427. this._engine = engine;
  16428. }
  16429. this._updatable = updatable;
  16430. this._data = data;
  16431. if (!postponeInternalCreation) {
  16432. this.create();
  16433. }
  16434. this._kind = kind;
  16435. if (stride) {
  16436. this._strideSize = stride;
  16437. return;
  16438. }
  16439. // Deduce stride from kind
  16440. switch (kind) {
  16441. case VertexBuffer.PositionKind:
  16442. this._strideSize = 3;
  16443. break;
  16444. case VertexBuffer.NormalKind:
  16445. this._strideSize = 3;
  16446. break;
  16447. case VertexBuffer.UVKind:
  16448. case VertexBuffer.UV2Kind:
  16449. case VertexBuffer.UV3Kind:
  16450. case VertexBuffer.UV4Kind:
  16451. case VertexBuffer.UV5Kind:
  16452. case VertexBuffer.UV6Kind:
  16453. this._strideSize = 2;
  16454. break;
  16455. case VertexBuffer.ColorKind:
  16456. this._strideSize = 4;
  16457. break;
  16458. case VertexBuffer.MatricesIndicesKind:
  16459. case VertexBuffer.MatricesIndicesExtraKind:
  16460. this._strideSize = 4;
  16461. break;
  16462. case VertexBuffer.MatricesWeightsKind:
  16463. case VertexBuffer.MatricesWeightsExtraKind:
  16464. this._strideSize = 4;
  16465. break;
  16466. }
  16467. }
  16468. // Properties
  16469. VertexBuffer.prototype.isUpdatable = function () {
  16470. return this._updatable;
  16471. };
  16472. VertexBuffer.prototype.getData = function () {
  16473. return this._data;
  16474. };
  16475. VertexBuffer.prototype.getBuffer = function () {
  16476. return this._buffer;
  16477. };
  16478. VertexBuffer.prototype.getStrideSize = function () {
  16479. return this._strideSize;
  16480. };
  16481. // Methods
  16482. VertexBuffer.prototype.create = function (data) {
  16483. if (!data && this._buffer) {
  16484. return; // nothing to do
  16485. }
  16486. data = data || this._data;
  16487. if (!this._buffer) {
  16488. if (this._updatable) {
  16489. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16490. }
  16491. else {
  16492. this._buffer = this._engine.createVertexBuffer(data);
  16493. }
  16494. }
  16495. if (this._updatable) {
  16496. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16497. this._data = data;
  16498. }
  16499. };
  16500. VertexBuffer.prototype.update = function (data) {
  16501. this.create(data);
  16502. };
  16503. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16504. if (!this._buffer) {
  16505. return;
  16506. }
  16507. if (this._updatable) {
  16508. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16509. this._data = null;
  16510. }
  16511. };
  16512. VertexBuffer.prototype.dispose = function () {
  16513. if (!this._buffer) {
  16514. return;
  16515. }
  16516. if (this._engine._releaseBuffer(this._buffer)) {
  16517. this._buffer = null;
  16518. }
  16519. };
  16520. Object.defineProperty(VertexBuffer, "PositionKind", {
  16521. get: function () {
  16522. return VertexBuffer._PositionKind;
  16523. },
  16524. enumerable: true,
  16525. configurable: true
  16526. });
  16527. Object.defineProperty(VertexBuffer, "NormalKind", {
  16528. get: function () {
  16529. return VertexBuffer._NormalKind;
  16530. },
  16531. enumerable: true,
  16532. configurable: true
  16533. });
  16534. Object.defineProperty(VertexBuffer, "UVKind", {
  16535. get: function () {
  16536. return VertexBuffer._UVKind;
  16537. },
  16538. enumerable: true,
  16539. configurable: true
  16540. });
  16541. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16542. get: function () {
  16543. return VertexBuffer._UV2Kind;
  16544. },
  16545. enumerable: true,
  16546. configurable: true
  16547. });
  16548. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16549. get: function () {
  16550. return VertexBuffer._UV3Kind;
  16551. },
  16552. enumerable: true,
  16553. configurable: true
  16554. });
  16555. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16556. get: function () {
  16557. return VertexBuffer._UV4Kind;
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16563. get: function () {
  16564. return VertexBuffer._UV5Kind;
  16565. },
  16566. enumerable: true,
  16567. configurable: true
  16568. });
  16569. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16570. get: function () {
  16571. return VertexBuffer._UV6Kind;
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(VertexBuffer, "ColorKind", {
  16577. get: function () {
  16578. return VertexBuffer._ColorKind;
  16579. },
  16580. enumerable: true,
  16581. configurable: true
  16582. });
  16583. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16584. get: function () {
  16585. return VertexBuffer._MatricesIndicesKind;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16591. get: function () {
  16592. return VertexBuffer._MatricesWeightsKind;
  16593. },
  16594. enumerable: true,
  16595. configurable: true
  16596. });
  16597. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16598. get: function () {
  16599. return VertexBuffer._MatricesIndicesExtraKind;
  16600. },
  16601. enumerable: true,
  16602. configurable: true
  16603. });
  16604. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16605. get: function () {
  16606. return VertexBuffer._MatricesWeightsExtraKind;
  16607. },
  16608. enumerable: true,
  16609. configurable: true
  16610. });
  16611. // Enums
  16612. VertexBuffer._PositionKind = "position";
  16613. VertexBuffer._NormalKind = "normal";
  16614. VertexBuffer._UVKind = "uv";
  16615. VertexBuffer._UV2Kind = "uv2";
  16616. VertexBuffer._UV3Kind = "uv3";
  16617. VertexBuffer._UV4Kind = "uv4";
  16618. VertexBuffer._UV5Kind = "uv5";
  16619. VertexBuffer._UV6Kind = "uv6";
  16620. VertexBuffer._ColorKind = "color";
  16621. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16622. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16623. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16624. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16625. return VertexBuffer;
  16626. })();
  16627. BABYLON.VertexBuffer = VertexBuffer;
  16628. })(BABYLON || (BABYLON = {}));
  16629. var BABYLON;
  16630. (function (BABYLON) {
  16631. /**
  16632. * Creates an instance based on a source mesh.
  16633. */
  16634. var InstancedMesh = (function (_super) {
  16635. __extends(InstancedMesh, _super);
  16636. function InstancedMesh(name, source) {
  16637. _super.call(this, name, source.getScene());
  16638. source.instances.push(this);
  16639. this._sourceMesh = source;
  16640. this.position.copyFrom(source.position);
  16641. this.rotation.copyFrom(source.rotation);
  16642. this.scaling.copyFrom(source.scaling);
  16643. if (source.rotationQuaternion) {
  16644. this.rotationQuaternion = source.rotationQuaternion.clone();
  16645. }
  16646. this.infiniteDistance = source.infiniteDistance;
  16647. this.setPivotMatrix(source.getPivotMatrix());
  16648. this.refreshBoundingInfo();
  16649. this._syncSubMeshes();
  16650. }
  16651. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16652. // Methods
  16653. get: function () {
  16654. return this._sourceMesh.receiveShadows;
  16655. },
  16656. enumerable: true,
  16657. configurable: true
  16658. });
  16659. Object.defineProperty(InstancedMesh.prototype, "material", {
  16660. get: function () {
  16661. return this._sourceMesh.material;
  16662. },
  16663. enumerable: true,
  16664. configurable: true
  16665. });
  16666. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16667. get: function () {
  16668. return this._sourceMesh.visibility;
  16669. },
  16670. enumerable: true,
  16671. configurable: true
  16672. });
  16673. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16674. get: function () {
  16675. return this._sourceMesh.skeleton;
  16676. },
  16677. enumerable: true,
  16678. configurable: true
  16679. });
  16680. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16681. get: function () {
  16682. return this._sourceMesh.renderingGroupId;
  16683. },
  16684. enumerable: true,
  16685. configurable: true
  16686. });
  16687. InstancedMesh.prototype.getTotalVertices = function () {
  16688. return this._sourceMesh.getTotalVertices();
  16689. };
  16690. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16691. get: function () {
  16692. return this._sourceMesh;
  16693. },
  16694. enumerable: true,
  16695. configurable: true
  16696. });
  16697. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16698. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16699. };
  16700. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16701. return this._sourceMesh.isVerticesDataPresent(kind);
  16702. };
  16703. InstancedMesh.prototype.getIndices = function () {
  16704. return this._sourceMesh.getIndices();
  16705. };
  16706. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16707. get: function () {
  16708. return this._sourceMesh._positions;
  16709. },
  16710. enumerable: true,
  16711. configurable: true
  16712. });
  16713. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16714. var meshBB = this._sourceMesh.getBoundingInfo();
  16715. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16716. this._updateBoundingInfo();
  16717. };
  16718. InstancedMesh.prototype._preActivate = function () {
  16719. if (this._currentLOD) {
  16720. this._currentLOD._preActivate();
  16721. }
  16722. };
  16723. InstancedMesh.prototype._activate = function (renderId) {
  16724. if (this._currentLOD) {
  16725. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16726. }
  16727. };
  16728. InstancedMesh.prototype.getLOD = function (camera) {
  16729. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16730. if (this._currentLOD === this.sourceMesh) {
  16731. return this;
  16732. }
  16733. return this._currentLOD;
  16734. };
  16735. InstancedMesh.prototype._syncSubMeshes = function () {
  16736. this.releaseSubMeshes();
  16737. if (this._sourceMesh.subMeshes) {
  16738. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16739. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16740. }
  16741. }
  16742. };
  16743. InstancedMesh.prototype._generatePointsArray = function () {
  16744. return this._sourceMesh._generatePointsArray();
  16745. };
  16746. // Clone
  16747. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16748. var result = this._sourceMesh.createInstance(name);
  16749. // Deep copy
  16750. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  16751. // Bounding info
  16752. this.refreshBoundingInfo();
  16753. // Parent
  16754. if (newParent) {
  16755. result.parent = newParent;
  16756. }
  16757. if (!doNotCloneChildren) {
  16758. // Children
  16759. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16760. var mesh = this.getScene().meshes[index];
  16761. if (mesh.parent === this) {
  16762. mesh.clone(mesh.name, result);
  16763. }
  16764. }
  16765. }
  16766. result.computeWorldMatrix(true);
  16767. return result;
  16768. };
  16769. // Dispoe
  16770. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16771. // Remove from mesh
  16772. var index = this._sourceMesh.instances.indexOf(this);
  16773. this._sourceMesh.instances.splice(index, 1);
  16774. _super.prototype.dispose.call(this, doNotRecurse);
  16775. };
  16776. return InstancedMesh;
  16777. })(BABYLON.AbstractMesh);
  16778. BABYLON.InstancedMesh = InstancedMesh;
  16779. })(BABYLON || (BABYLON = {}));
  16780. var BABYLON;
  16781. (function (BABYLON) {
  16782. var _InstancesBatch = (function () {
  16783. function _InstancesBatch() {
  16784. this.mustReturn = false;
  16785. this.visibleInstances = new Array();
  16786. this.renderSelf = new Array();
  16787. }
  16788. return _InstancesBatch;
  16789. })();
  16790. BABYLON._InstancesBatch = _InstancesBatch;
  16791. var Mesh = (function (_super) {
  16792. __extends(Mesh, _super);
  16793. /**
  16794. * @constructor
  16795. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16796. * @param {Scene} scene - The scene to add this mesh to.
  16797. * @param {Node} parent - The parent of this mesh, if it has one
  16798. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16799. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16800. * When false, achieved by calling a clone(), also passing False.
  16801. * This will make creation of children, recursive.
  16802. */
  16803. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16804. if (parent === void 0) { parent = null; }
  16805. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16806. _super.call(this, name, scene);
  16807. // Events
  16808. /**
  16809. * An event triggered before rendering the mesh
  16810. * @type {BABYLON.Observable}
  16811. */
  16812. this.onBeforeRenderObservable = new BABYLON.Observable();
  16813. /**
  16814. * An event triggered after rendering the mesh
  16815. * @type {BABYLON.Observable}
  16816. */
  16817. this.onAfterRenderObservable = new BABYLON.Observable();
  16818. /**
  16819. * An event triggered before drawing the mesh
  16820. * @type {BABYLON.Observable}
  16821. */
  16822. this.onBeforeDrawObservable = new BABYLON.Observable();
  16823. // Members
  16824. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16825. this.instances = new Array();
  16826. this._LODLevels = new Array();
  16827. this._visibleInstances = {};
  16828. this._renderIdForInstances = new Array();
  16829. this._batchCache = new _InstancesBatch();
  16830. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16831. this._sideOrientation = Mesh._DEFAULTSIDE;
  16832. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16833. if (source) {
  16834. // Geometry
  16835. if (source._geometry) {
  16836. source._geometry.applyToMesh(this);
  16837. }
  16838. // Deep copy
  16839. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16840. // Pivot
  16841. this.setPivotMatrix(source.getPivotMatrix());
  16842. this.id = name + "." + source.id;
  16843. // Material
  16844. this.material = source.material;
  16845. var index;
  16846. if (!doNotCloneChildren) {
  16847. // Children
  16848. for (index = 0; index < scene.meshes.length; index++) {
  16849. var mesh = scene.meshes[index];
  16850. if (mesh.parent === source) {
  16851. // doNotCloneChildren is always going to be False
  16852. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16853. }
  16854. }
  16855. }
  16856. // Physics clone
  16857. var physicsEngine = this.getScene().getPhysicsEngine();
  16858. if (clonePhysicsImpostor && physicsEngine) {
  16859. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16860. if (impostor) {
  16861. this.physicsImpostor = impostor.clone(this);
  16862. }
  16863. }
  16864. // Particles
  16865. for (index = 0; index < scene.particleSystems.length; index++) {
  16866. var system = scene.particleSystems[index];
  16867. if (system.emitter === source) {
  16868. system.clone(system.name, this);
  16869. }
  16870. }
  16871. this.computeWorldMatrix(true);
  16872. }
  16873. // Parent
  16874. if (parent !== null) {
  16875. this.parent = parent;
  16876. }
  16877. }
  16878. Object.defineProperty(Mesh, "FRONTSIDE", {
  16879. /**
  16880. * Mesh side orientation : usually the external or front surface
  16881. */
  16882. get: function () {
  16883. return Mesh._FRONTSIDE;
  16884. },
  16885. enumerable: true,
  16886. configurable: true
  16887. });
  16888. Object.defineProperty(Mesh, "BACKSIDE", {
  16889. /**
  16890. * Mesh side orientation : usually the internal or back surface
  16891. */
  16892. get: function () {
  16893. return Mesh._BACKSIDE;
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16899. /**
  16900. * Mesh side orientation : both internal and external or front and back surfaces
  16901. */
  16902. get: function () {
  16903. return Mesh._DOUBLESIDE;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16909. /**
  16910. * Mesh side orientation : by default, `FRONTSIDE`
  16911. */
  16912. get: function () {
  16913. return Mesh._DEFAULTSIDE;
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. Object.defineProperty(Mesh, "NO_CAP", {
  16919. /**
  16920. * Mesh cap setting : no cap
  16921. */
  16922. get: function () {
  16923. return Mesh._NO_CAP;
  16924. },
  16925. enumerable: true,
  16926. configurable: true
  16927. });
  16928. Object.defineProperty(Mesh, "CAP_START", {
  16929. /**
  16930. * Mesh cap setting : one cap at the beginning of the mesh
  16931. */
  16932. get: function () {
  16933. return Mesh._CAP_START;
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Object.defineProperty(Mesh, "CAP_END", {
  16939. /**
  16940. * Mesh cap setting : one cap at the end of the mesh
  16941. */
  16942. get: function () {
  16943. return Mesh._CAP_END;
  16944. },
  16945. enumerable: true,
  16946. configurable: true
  16947. });
  16948. Object.defineProperty(Mesh, "CAP_ALL", {
  16949. /**
  16950. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16951. */
  16952. get: function () {
  16953. return Mesh._CAP_ALL;
  16954. },
  16955. enumerable: true,
  16956. configurable: true
  16957. });
  16958. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16959. set: function (callback) {
  16960. if (this._onBeforeDrawObserver) {
  16961. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16962. }
  16963. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. // Methods
  16969. /**
  16970. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16971. */
  16972. Mesh.prototype.toString = function (fullDetails) {
  16973. var ret = _super.prototype.toString.call(this, fullDetails);
  16974. ret += ", n vertices: " + this.getTotalVertices();
  16975. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16976. if (this.animations) {
  16977. for (var i = 0; i < this.animations.length; i++) {
  16978. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16979. }
  16980. }
  16981. if (fullDetails) {
  16982. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16983. }
  16984. return ret;
  16985. };
  16986. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16987. get: function () {
  16988. return this._LODLevels.length > 0;
  16989. },
  16990. enumerable: true,
  16991. configurable: true
  16992. });
  16993. Mesh.prototype._sortLODLevels = function () {
  16994. this._LODLevels.sort(function (a, b) {
  16995. if (a.distance < b.distance) {
  16996. return 1;
  16997. }
  16998. if (a.distance > b.distance) {
  16999. return -1;
  17000. }
  17001. return 0;
  17002. });
  17003. };
  17004. /**
  17005. * Add a mesh as LOD level triggered at the given distance.
  17006. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17007. * @param {number} distance - the distance from the center of the object to show this level
  17008. * @param {Mesh} mesh - the mesh to be added as LOD level
  17009. * @return {Mesh} this mesh (for chaining)
  17010. */
  17011. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17012. if (mesh && mesh._masterMesh) {
  17013. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17014. return this;
  17015. }
  17016. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17017. this._LODLevels.push(level);
  17018. if (mesh) {
  17019. mesh._masterMesh = this;
  17020. }
  17021. this._sortLODLevels();
  17022. return this;
  17023. };
  17024. /**
  17025. * Returns the LOD level mesh at the passed distance or null if not found.
  17026. * It is related to the method `addLODLevel(distance, mesh)`.
  17027. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17028. */
  17029. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17030. for (var index = 0; index < this._LODLevels.length; index++) {
  17031. var level = this._LODLevels[index];
  17032. if (level.distance === distance) {
  17033. return level.mesh;
  17034. }
  17035. }
  17036. return null;
  17037. };
  17038. /**
  17039. * Remove a mesh from the LOD array
  17040. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17041. * @param {Mesh} mesh - the mesh to be removed.
  17042. * @return {Mesh} this mesh (for chaining)
  17043. */
  17044. Mesh.prototype.removeLODLevel = function (mesh) {
  17045. for (var index = 0; index < this._LODLevels.length; index++) {
  17046. if (this._LODLevels[index].mesh === mesh) {
  17047. this._LODLevels.splice(index, 1);
  17048. if (mesh) {
  17049. mesh._masterMesh = null;
  17050. }
  17051. }
  17052. }
  17053. this._sortLODLevels();
  17054. return this;
  17055. };
  17056. /**
  17057. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17058. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17059. */
  17060. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17061. if (!this._LODLevels || this._LODLevels.length === 0) {
  17062. return this;
  17063. }
  17064. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17065. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17066. if (this.onLODLevelSelection) {
  17067. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17068. }
  17069. return this;
  17070. }
  17071. for (var index = 0; index < this._LODLevels.length; index++) {
  17072. var level = this._LODLevels[index];
  17073. if (level.distance < distanceToCamera) {
  17074. if (level.mesh) {
  17075. level.mesh._preActivate();
  17076. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17077. }
  17078. if (this.onLODLevelSelection) {
  17079. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17080. }
  17081. return level.mesh;
  17082. }
  17083. }
  17084. if (this.onLODLevelSelection) {
  17085. this.onLODLevelSelection(distanceToCamera, this, this);
  17086. }
  17087. return this;
  17088. };
  17089. Object.defineProperty(Mesh.prototype, "geometry", {
  17090. /**
  17091. * Returns the mesh internal `Geometry` object.
  17092. */
  17093. get: function () {
  17094. return this._geometry;
  17095. },
  17096. enumerable: true,
  17097. configurable: true
  17098. });
  17099. /**
  17100. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17101. */
  17102. Mesh.prototype.getTotalVertices = function () {
  17103. if (!this._geometry) {
  17104. return 0;
  17105. }
  17106. return this._geometry.getTotalVertices();
  17107. };
  17108. /**
  17109. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17110. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17111. * Returns null if the mesh has no geometry or no vertex buffer.
  17112. * Possible `kind` values :
  17113. * - BABYLON.VertexBuffer.PositionKind
  17114. * - BABYLON.VertexBuffer.UVKind
  17115. * - BABYLON.VertexBuffer.UV2Kind
  17116. * - BABYLON.VertexBuffer.UV3Kind
  17117. * - BABYLON.VertexBuffer.UV4Kind
  17118. * - BABYLON.VertexBuffer.UV5Kind
  17119. * - BABYLON.VertexBuffer.UV6Kind
  17120. * - BABYLON.VertexBuffer.ColorKind
  17121. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17122. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17123. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17124. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17125. */
  17126. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17127. if (!this._geometry) {
  17128. return null;
  17129. }
  17130. return this._geometry.getVerticesData(kind, copyWhenShared);
  17131. };
  17132. /**
  17133. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17134. * Returns `undefined` if the mesh has no geometry.
  17135. * Possible `kind` values :
  17136. * - BABYLON.VertexBuffer.PositionKind
  17137. * - BABYLON.VertexBuffer.UVKind
  17138. * - BABYLON.VertexBuffer.UV2Kind
  17139. * - BABYLON.VertexBuffer.UV3Kind
  17140. * - BABYLON.VertexBuffer.UV4Kind
  17141. * - BABYLON.VertexBuffer.UV5Kind
  17142. * - BABYLON.VertexBuffer.UV6Kind
  17143. * - BABYLON.VertexBuffer.ColorKind
  17144. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17145. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17146. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17147. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17148. */
  17149. Mesh.prototype.getVertexBuffer = function (kind) {
  17150. if (!this._geometry) {
  17151. return undefined;
  17152. }
  17153. return this._geometry.getVertexBuffer(kind);
  17154. };
  17155. /**
  17156. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17157. * Possible `kind` values :
  17158. * - BABYLON.VertexBuffer.PositionKind
  17159. * - BABYLON.VertexBuffer.UVKind
  17160. * - BABYLON.VertexBuffer.UV2Kind
  17161. * - BABYLON.VertexBuffer.UV3Kind
  17162. * - BABYLON.VertexBuffer.UV4Kind
  17163. * - BABYLON.VertexBuffer.UV5Kind
  17164. * - BABYLON.VertexBuffer.UV6Kind
  17165. * - BABYLON.VertexBuffer.ColorKind
  17166. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17167. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17168. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17169. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17170. */
  17171. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17172. if (!this._geometry) {
  17173. if (this._delayInfo) {
  17174. return this._delayInfo.indexOf(kind) !== -1;
  17175. }
  17176. return false;
  17177. }
  17178. return this._geometry.isVerticesDataPresent(kind);
  17179. };
  17180. /**
  17181. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17182. * Possible `kind` values :
  17183. * - BABYLON.VertexBuffer.PositionKind
  17184. * - BABYLON.VertexBuffer.UVKind
  17185. * - BABYLON.VertexBuffer.UV2Kind
  17186. * - BABYLON.VertexBuffer.UV3Kind
  17187. * - BABYLON.VertexBuffer.UV4Kind
  17188. * - BABYLON.VertexBuffer.UV5Kind
  17189. * - BABYLON.VertexBuffer.UV6Kind
  17190. * - BABYLON.VertexBuffer.ColorKind
  17191. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17192. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17193. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17194. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17195. */
  17196. Mesh.prototype.getVerticesDataKinds = function () {
  17197. if (!this._geometry) {
  17198. var result = [];
  17199. if (this._delayInfo) {
  17200. for (var kind in this._delayInfo) {
  17201. result.push(kind);
  17202. }
  17203. }
  17204. return result;
  17205. }
  17206. return this._geometry.getVerticesDataKinds();
  17207. };
  17208. /**
  17209. * Returns a positive integer : the total number of indices in this mesh geometry.
  17210. * Returns zero if the mesh has no geometry.
  17211. */
  17212. Mesh.prototype.getTotalIndices = function () {
  17213. if (!this._geometry) {
  17214. return 0;
  17215. }
  17216. return this._geometry.getTotalIndices();
  17217. };
  17218. /**
  17219. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17220. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17221. * Returns an empty array if the mesh has no geometry.
  17222. */
  17223. Mesh.prototype.getIndices = function (copyWhenShared) {
  17224. if (!this._geometry) {
  17225. return [];
  17226. }
  17227. return this._geometry.getIndices(copyWhenShared);
  17228. };
  17229. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17230. get: function () {
  17231. return this._masterMesh !== null && this._masterMesh !== undefined;
  17232. },
  17233. enumerable: true,
  17234. configurable: true
  17235. });
  17236. /**
  17237. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17238. */
  17239. Mesh.prototype.isReady = function () {
  17240. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17241. return false;
  17242. }
  17243. return _super.prototype.isReady.call(this);
  17244. };
  17245. /**
  17246. * Boolean : true if the mesh has been disposed.
  17247. */
  17248. Mesh.prototype.isDisposed = function () {
  17249. return this._isDisposed;
  17250. };
  17251. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17252. get: function () {
  17253. return this._sideOrientation;
  17254. },
  17255. /**
  17256. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17257. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17258. */
  17259. set: function (sideO) {
  17260. this._sideOrientation = sideO;
  17261. },
  17262. enumerable: true,
  17263. configurable: true
  17264. });
  17265. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17266. /**
  17267. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17268. * This property is pertinent only for updatable parametric shapes.
  17269. */
  17270. get: function () {
  17271. return this._areNormalsFrozen;
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. /**
  17277. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17278. * It has no effect at all on other shapes.
  17279. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17280. */
  17281. Mesh.prototype.freezeNormals = function () {
  17282. this._areNormalsFrozen = true;
  17283. };
  17284. /**
  17285. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17286. * It has no effect at all on other shapes.
  17287. * It reactivates the mesh normals computation if it was previously frozen.
  17288. */
  17289. Mesh.prototype.unfreezeNormals = function () {
  17290. this._areNormalsFrozen = false;
  17291. };
  17292. // Methods
  17293. Mesh.prototype._preActivate = function () {
  17294. var sceneRenderId = this.getScene().getRenderId();
  17295. if (this._preActivateId === sceneRenderId) {
  17296. return;
  17297. }
  17298. this._preActivateId = sceneRenderId;
  17299. this._visibleInstances = null;
  17300. };
  17301. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17302. if (this._visibleInstances) {
  17303. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17304. }
  17305. };
  17306. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17307. if (!this._visibleInstances) {
  17308. this._visibleInstances = {};
  17309. this._visibleInstances.defaultRenderId = renderId;
  17310. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17311. }
  17312. if (!this._visibleInstances[renderId]) {
  17313. this._visibleInstances[renderId] = new Array();
  17314. }
  17315. this._visibleInstances[renderId].push(instance);
  17316. };
  17317. /**
  17318. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17319. * This means the mesh underlying bounding box and sphere are recomputed.
  17320. */
  17321. Mesh.prototype.refreshBoundingInfo = function () {
  17322. if (this._boundingInfo.isLocked) {
  17323. return;
  17324. }
  17325. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17326. if (data) {
  17327. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17328. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17329. }
  17330. if (this.subMeshes) {
  17331. for (var index = 0; index < this.subMeshes.length; index++) {
  17332. this.subMeshes[index].refreshBoundingInfo();
  17333. }
  17334. }
  17335. this._updateBoundingInfo();
  17336. };
  17337. Mesh.prototype._createGlobalSubMesh = function () {
  17338. var totalVertices = this.getTotalVertices();
  17339. if (!totalVertices || !this.getIndices()) {
  17340. return null;
  17341. }
  17342. this.releaseSubMeshes();
  17343. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17344. };
  17345. Mesh.prototype.subdivide = function (count) {
  17346. if (count < 1) {
  17347. return;
  17348. }
  17349. var totalIndices = this.getTotalIndices();
  17350. var subdivisionSize = (totalIndices / count) | 0;
  17351. var offset = 0;
  17352. // Ensure that subdivisionSize is a multiple of 3
  17353. while (subdivisionSize % 3 !== 0) {
  17354. subdivisionSize++;
  17355. }
  17356. this.releaseSubMeshes();
  17357. for (var index = 0; index < count; index++) {
  17358. if (offset >= totalIndices) {
  17359. break;
  17360. }
  17361. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17362. offset += subdivisionSize;
  17363. }
  17364. this.synchronizeInstances();
  17365. };
  17366. /**
  17367. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17368. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17369. * The `data` are either a numeric array either a Float32Array.
  17370. * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
  17371. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17372. * Note that a new underlying `VertexBuffer` object is created each call.
  17373. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17374. *
  17375. * Possible `kind` values :
  17376. * - BABYLON.VertexBuffer.PositionKind
  17377. * - BABYLON.VertexBuffer.UVKind
  17378. * - BABYLON.VertexBuffer.UV2Kind
  17379. * - BABYLON.VertexBuffer.UV3Kind
  17380. * - BABYLON.VertexBuffer.UV4Kind
  17381. * - BABYLON.VertexBuffer.UV5Kind
  17382. * - BABYLON.VertexBuffer.UV6Kind
  17383. * - BABYLON.VertexBuffer.ColorKind
  17384. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17385. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17386. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17387. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17388. */
  17389. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17390. if (!this._geometry) {
  17391. var vertexData = new BABYLON.VertexData();
  17392. vertexData.set(data, kind);
  17393. var scene = this.getScene();
  17394. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17395. }
  17396. else {
  17397. this._geometry.setVerticesData(kind, data, updatable, stride);
  17398. }
  17399. };
  17400. /**
  17401. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17402. * If the mesh has no geometry, it is simply returned as it is.
  17403. * The `data` are either a numeric array either a Float32Array.
  17404. * No new underlying `VertexBuffer` object is created.
  17405. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17406. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17407. *
  17408. * Possible `kind` values :
  17409. * - BABYLON.VertexBuffer.PositionKind
  17410. * - BABYLON.VertexBuffer.UVKind
  17411. * - BABYLON.VertexBuffer.UV2Kind
  17412. * - BABYLON.VertexBuffer.UV3Kind
  17413. * - BABYLON.VertexBuffer.UV4Kind
  17414. * - BABYLON.VertexBuffer.UV5Kind
  17415. * - BABYLON.VertexBuffer.UV6Kind
  17416. * - BABYLON.VertexBuffer.ColorKind
  17417. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17418. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17419. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17420. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17421. */
  17422. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17423. if (!this._geometry) {
  17424. return;
  17425. }
  17426. if (!makeItUnique) {
  17427. this._geometry.updateVerticesData(kind, data, updateExtends);
  17428. }
  17429. else {
  17430. this.makeGeometryUnique();
  17431. this.updateVerticesData(kind, data, updateExtends, false);
  17432. }
  17433. };
  17434. /**
  17435. * Deprecated since BabylonJS v2.3
  17436. */
  17437. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17438. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17439. if (!this._geometry) {
  17440. return;
  17441. }
  17442. if (!makeItUnique) {
  17443. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17444. }
  17445. else {
  17446. this.makeGeometryUnique();
  17447. this.updateVerticesDataDirectly(kind, data, offset, false);
  17448. }
  17449. };
  17450. /**
  17451. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17452. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17453. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17454. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17455. */
  17456. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17457. if (computeNormals === void 0) { computeNormals = true; }
  17458. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17459. positionFunction(positions);
  17460. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17461. if (computeNormals) {
  17462. var indices = this.getIndices();
  17463. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17464. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17465. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17466. }
  17467. };
  17468. Mesh.prototype.makeGeometryUnique = function () {
  17469. if (!this._geometry) {
  17470. return;
  17471. }
  17472. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17473. geometry.applyToMesh(this);
  17474. };
  17475. /**
  17476. * Sets the mesh indices.
  17477. * Expects an array populated with integers or a Int32Array.
  17478. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17479. * This method creates a new index buffer each call.
  17480. */
  17481. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17482. if (!this._geometry) {
  17483. var vertexData = new BABYLON.VertexData();
  17484. vertexData.indices = indices;
  17485. var scene = this.getScene();
  17486. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17487. }
  17488. else {
  17489. this._geometry.setIndices(indices, totalVertices);
  17490. }
  17491. };
  17492. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17493. var engine = this.getScene().getEngine();
  17494. // Wireframe
  17495. var indexToBind;
  17496. if (this._unIndexed) {
  17497. indexToBind = null;
  17498. }
  17499. else {
  17500. switch (fillMode) {
  17501. case BABYLON.Material.PointFillMode:
  17502. indexToBind = null;
  17503. break;
  17504. case BABYLON.Material.WireFrameFillMode:
  17505. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17506. break;
  17507. default:
  17508. case BABYLON.Material.TriangleFillMode:
  17509. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17510. break;
  17511. }
  17512. }
  17513. // VBOs
  17514. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17515. };
  17516. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17517. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17518. return;
  17519. }
  17520. this.onBeforeDrawObservable.notifyObservers(this);
  17521. var engine = this.getScene().getEngine();
  17522. // Draw order
  17523. switch (fillMode) {
  17524. case BABYLON.Material.PointFillMode:
  17525. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17526. break;
  17527. case BABYLON.Material.WireFrameFillMode:
  17528. if (this._unIndexed) {
  17529. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17530. }
  17531. else {
  17532. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17533. }
  17534. break;
  17535. default:
  17536. if (this._unIndexed) {
  17537. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17538. }
  17539. else {
  17540. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17541. }
  17542. }
  17543. };
  17544. /**
  17545. * Registers for this mesh a javascript function called just before the rendering process.
  17546. * This function is passed the current mesh and doesn't return anything.
  17547. */
  17548. Mesh.prototype.registerBeforeRender = function (func) {
  17549. this.onBeforeRenderObservable.add(func);
  17550. };
  17551. /**
  17552. * Disposes a previously registered javascript function called before the rendering.
  17553. * This function is passed the current mesh and doesn't return anything.
  17554. */
  17555. Mesh.prototype.unregisterBeforeRender = function (func) {
  17556. this.onBeforeRenderObservable.removeCallback(func);
  17557. };
  17558. /**
  17559. * Registers for this mesh a javascript function called just after the rendering is complete.
  17560. * This function is passed the current mesh and doesn't return anything.
  17561. */
  17562. Mesh.prototype.registerAfterRender = function (func) {
  17563. this.onAfterRenderObservable.add(func);
  17564. };
  17565. /**
  17566. * Disposes a previously registered javascript function called after the rendering.
  17567. * This function is passed the current mesh and doesn't return anything.
  17568. */
  17569. Mesh.prototype.unregisterAfterRender = function (func) {
  17570. this.onAfterRenderObservable.removeCallback(func);
  17571. };
  17572. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17573. var scene = this.getScene();
  17574. this._batchCache.mustReturn = false;
  17575. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17576. this._batchCache.visibleInstances[subMeshId] = null;
  17577. if (this._visibleInstances) {
  17578. var currentRenderId = scene.getRenderId();
  17579. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17580. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17581. var selfRenderId = this._renderId;
  17582. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17583. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17584. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17585. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17586. }
  17587. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17588. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17589. this._batchCache.mustReturn = true;
  17590. return this._batchCache;
  17591. }
  17592. if (currentRenderId !== selfRenderId) {
  17593. this._batchCache.renderSelf[subMeshId] = false;
  17594. }
  17595. }
  17596. this._renderIdForInstances[subMeshId] = currentRenderId;
  17597. }
  17598. return this._batchCache;
  17599. };
  17600. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17601. var visibleInstances = batch.visibleInstances[subMesh._id];
  17602. var matricesCount = visibleInstances.length + 1;
  17603. var bufferSize = matricesCount * 16 * 4;
  17604. while (this._instancesBufferSize < bufferSize) {
  17605. this._instancesBufferSize *= 2;
  17606. }
  17607. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17608. if (this._worldMatricesInstancesBuffer) {
  17609. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17610. }
  17611. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17612. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17613. }
  17614. var offset = 0;
  17615. var instancesCount = 0;
  17616. var world = this.getWorldMatrix();
  17617. if (batch.renderSelf[subMesh._id]) {
  17618. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17619. offset += 16;
  17620. instancesCount++;
  17621. }
  17622. if (visibleInstances) {
  17623. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17624. var instance = visibleInstances[instanceIndex];
  17625. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17626. offset += 16;
  17627. instancesCount++;
  17628. }
  17629. }
  17630. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17631. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17632. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17633. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17634. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17635. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17636. this._draw(subMesh, fillMode, instancesCount);
  17637. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17638. };
  17639. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17640. var scene = this.getScene();
  17641. var engine = scene.getEngine();
  17642. if (hardwareInstancedRendering) {
  17643. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17644. }
  17645. else {
  17646. if (batch.renderSelf[subMesh._id]) {
  17647. // Draw
  17648. if (onBeforeDraw) {
  17649. onBeforeDraw(false, this.getWorldMatrix());
  17650. }
  17651. this._draw(subMesh, fillMode);
  17652. }
  17653. if (batch.visibleInstances[subMesh._id]) {
  17654. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17655. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17656. // World
  17657. var world = instance.getWorldMatrix();
  17658. if (onBeforeDraw) {
  17659. onBeforeDraw(true, world);
  17660. }
  17661. // Draw
  17662. this._draw(subMesh, fillMode);
  17663. }
  17664. }
  17665. }
  17666. };
  17667. /**
  17668. * Triggers the draw call for the mesh.
  17669. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  17670. */
  17671. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17672. var scene = this.getScene();
  17673. // Managing instances
  17674. var batch = this._getInstancesRenderList(subMesh._id);
  17675. if (batch.mustReturn) {
  17676. return;
  17677. }
  17678. // Checking geometry state
  17679. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17680. return;
  17681. }
  17682. var callbackIndex;
  17683. this.onBeforeRenderObservable.notifyObservers(this);
  17684. var engine = scene.getEngine();
  17685. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17686. // Material
  17687. var effectiveMaterial = subMesh.getMaterial();
  17688. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17689. return;
  17690. }
  17691. // Outline - step 1
  17692. var savedDepthWrite = engine.getDepthWrite();
  17693. if (this.renderOutline) {
  17694. engine.setDepthWrite(false);
  17695. scene.getOutlineRenderer().render(subMesh, batch);
  17696. engine.setDepthWrite(savedDepthWrite);
  17697. }
  17698. effectiveMaterial._preBind();
  17699. var effect = effectiveMaterial.getEffect();
  17700. // Bind
  17701. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17702. this._bind(subMesh, effect, fillMode);
  17703. var world = this.getWorldMatrix();
  17704. effectiveMaterial.bind(world, this);
  17705. // Alpha mode
  17706. if (enableAlphaMode) {
  17707. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17708. }
  17709. // Draw
  17710. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17711. if (isInstance) {
  17712. effectiveMaterial.bindOnlyWorldMatrix(world);
  17713. }
  17714. });
  17715. // Unbind
  17716. effectiveMaterial.unbind();
  17717. // Outline - step 2
  17718. if (this.renderOutline && savedDepthWrite) {
  17719. engine.setDepthWrite(true);
  17720. engine.setColorWrite(false);
  17721. scene.getOutlineRenderer().render(subMesh, batch);
  17722. engine.setColorWrite(true);
  17723. }
  17724. // Overlay
  17725. if (this.renderOverlay) {
  17726. var currentMode = engine.getAlphaMode();
  17727. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17728. scene.getOutlineRenderer().render(subMesh, batch, true);
  17729. engine.setAlphaMode(currentMode);
  17730. }
  17731. this.onAfterRenderObservable.notifyObservers(this);
  17732. };
  17733. /**
  17734. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17735. */
  17736. Mesh.prototype.getEmittedParticleSystems = function () {
  17737. var results = new Array();
  17738. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17739. var particleSystem = this.getScene().particleSystems[index];
  17740. if (particleSystem.emitter === this) {
  17741. results.push(particleSystem);
  17742. }
  17743. }
  17744. return results;
  17745. };
  17746. /**
  17747. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17748. */
  17749. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17750. var results = new Array();
  17751. var descendants = this.getDescendants();
  17752. descendants.push(this);
  17753. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17754. var particleSystem = this.getScene().particleSystems[index];
  17755. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17756. results.push(particleSystem);
  17757. }
  17758. }
  17759. return results;
  17760. };
  17761. Mesh.prototype._checkDelayState = function () {
  17762. var _this = this;
  17763. var that = this;
  17764. var scene = this.getScene();
  17765. if (this._geometry) {
  17766. this._geometry.load(scene);
  17767. }
  17768. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17769. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17770. scene._addPendingData(that);
  17771. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17772. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17773. if (data instanceof ArrayBuffer) {
  17774. _this._delayLoadingFunction(data, _this);
  17775. }
  17776. else {
  17777. _this._delayLoadingFunction(JSON.parse(data), _this);
  17778. }
  17779. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17780. scene._removePendingData(_this);
  17781. }, function () { }, scene.database, getBinaryData);
  17782. }
  17783. };
  17784. /**
  17785. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17786. */
  17787. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17788. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17789. return false;
  17790. }
  17791. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17792. return false;
  17793. }
  17794. this._checkDelayState();
  17795. return true;
  17796. };
  17797. /**
  17798. * Sets the mesh material by the material or multiMaterial `id` property.
  17799. * The material `id` is a string identifying the material or the multiMaterial.
  17800. * This method returns nothing.
  17801. */
  17802. Mesh.prototype.setMaterialByID = function (id) {
  17803. var materials = this.getScene().materials;
  17804. var index;
  17805. for (index = 0; index < materials.length; index++) {
  17806. if (materials[index].id === id) {
  17807. this.material = materials[index];
  17808. return;
  17809. }
  17810. }
  17811. // Multi
  17812. var multiMaterials = this.getScene().multiMaterials;
  17813. for (index = 0; index < multiMaterials.length; index++) {
  17814. if (multiMaterials[index].id === id) {
  17815. this.material = multiMaterials[index];
  17816. return;
  17817. }
  17818. }
  17819. };
  17820. /**
  17821. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  17822. */
  17823. Mesh.prototype.getAnimatables = function () {
  17824. var results = [];
  17825. if (this.material) {
  17826. results.push(this.material);
  17827. }
  17828. if (this.skeleton) {
  17829. results.push(this.skeleton);
  17830. }
  17831. return results;
  17832. };
  17833. /**
  17834. * Modifies the mesh geometry according to the passed transformation matrix.
  17835. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  17836. * The mesh normals are modified accordingly the same transformation.
  17837. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  17838. * Note that, under the hood, this method sets a new VertexBuffer each call.
  17839. */
  17840. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17841. // Position
  17842. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17843. return;
  17844. }
  17845. var submeshes = this.subMeshes.splice(0);
  17846. this._resetPointsArrayCache();
  17847. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17848. var temp = [];
  17849. var index;
  17850. for (index = 0; index < data.length; index += 3) {
  17851. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17852. }
  17853. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17854. // Normals
  17855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17856. return;
  17857. }
  17858. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17859. temp = [];
  17860. for (index = 0; index < data.length; index += 3) {
  17861. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17862. }
  17863. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17864. // flip faces?
  17865. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17866. this.flipFaces();
  17867. }
  17868. // Restore submeshes
  17869. this.releaseSubMeshes();
  17870. this.subMeshes = submeshes;
  17871. };
  17872. /**
  17873. * Modifies the mesh geometry according to its own current World Matrix.
  17874. * The mesh World Matrix is then reset.
  17875. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  17876. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  17877. * Note that, under the hood, this method sets a new VertexBuffer each call.
  17878. */
  17879. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17880. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17881. this.scaling.copyFromFloats(1, 1, 1);
  17882. this.position.copyFromFloats(0, 0, 0);
  17883. this.rotation.copyFromFloats(0, 0, 0);
  17884. //only if quaternion is already set
  17885. if (this.rotationQuaternion) {
  17886. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17887. }
  17888. this._worldMatrix = BABYLON.Matrix.Identity();
  17889. };
  17890. // Cache
  17891. Mesh.prototype._resetPointsArrayCache = function () {
  17892. this._positions = null;
  17893. };
  17894. Mesh.prototype._generatePointsArray = function () {
  17895. if (this._positions)
  17896. return true;
  17897. this._positions = [];
  17898. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17899. if (!data) {
  17900. return false;
  17901. }
  17902. for (var index = 0; index < data.length; index += 3) {
  17903. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17904. }
  17905. return true;
  17906. };
  17907. /**
  17908. * Returns a new `Mesh` object generated from the current mesh properties.
  17909. * This method must not get confused with createInstance().
  17910. * The parameter `name` is a string, the name given to the new mesh.
  17911. * The optional parameter `newParent` can be any `Node` object (default `null`).
  17912. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  17913. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  17914. */
  17915. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17916. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17917. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17918. };
  17919. /**
  17920. * Disposes the mesh.
  17921. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  17922. */
  17923. Mesh.prototype.dispose = function (doNotRecurse) {
  17924. if (this._geometry) {
  17925. this._geometry.releaseForMesh(this, true);
  17926. }
  17927. // Instances
  17928. if (this._worldMatricesInstancesBuffer) {
  17929. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17930. this._worldMatricesInstancesBuffer = null;
  17931. }
  17932. while (this.instances.length) {
  17933. this.instances[0].dispose();
  17934. }
  17935. _super.prototype.dispose.call(this, doNotRecurse);
  17936. };
  17937. /**
  17938. * Modifies the mesh geometry according to a displacement map.
  17939. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  17940. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  17941. * This method returns nothing.
  17942. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  17943. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  17944. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  17945. */
  17946. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17947. var _this = this;
  17948. var scene = this.getScene();
  17949. var onload = function (img) {
  17950. // Getting height map data
  17951. var canvas = document.createElement("canvas");
  17952. var context = canvas.getContext("2d");
  17953. var heightMapWidth = img.width;
  17954. var heightMapHeight = img.height;
  17955. canvas.width = heightMapWidth;
  17956. canvas.height = heightMapHeight;
  17957. context.drawImage(img, 0, 0);
  17958. // Create VertexData from map data
  17959. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17960. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17961. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17962. //execute success callback, if set
  17963. if (onSuccess) {
  17964. onSuccess(_this);
  17965. }
  17966. };
  17967. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17968. };
  17969. /**
  17970. * Modifies the mesh geometry according to a displacementMap buffer.
  17971. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  17972. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  17973. * This method returns nothing.
  17974. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  17975. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  17976. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  17977. */
  17978. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17979. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17980. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17981. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17982. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17983. return;
  17984. }
  17985. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17986. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17987. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17988. var position = BABYLON.Vector3.Zero();
  17989. var normal = BABYLON.Vector3.Zero();
  17990. var uv = BABYLON.Vector2.Zero();
  17991. for (var index = 0; index < positions.length; index += 3) {
  17992. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17993. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17994. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17995. // Compute height
  17996. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17997. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17998. var pos = (u + v * heightMapWidth) * 4;
  17999. var r = buffer[pos] / 255.0;
  18000. var g = buffer[pos + 1] / 255.0;
  18001. var b = buffer[pos + 2] / 255.0;
  18002. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  18003. normal.normalize();
  18004. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  18005. position = position.add(normal);
  18006. position.toArray(positions, index);
  18007. }
  18008. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18009. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18010. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18011. };
  18012. /**
  18013. * Modify the mesh to get a flat shading rendering.
  18014. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18015. * This method returns nothing.
  18016. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18017. */
  18018. Mesh.prototype.convertToFlatShadedMesh = function () {
  18019. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18020. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18021. var kinds = this.getVerticesDataKinds();
  18022. var vbs = [];
  18023. var data = [];
  18024. var newdata = [];
  18025. var updatableNormals = false;
  18026. var kindIndex;
  18027. var kind;
  18028. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18029. kind = kinds[kindIndex];
  18030. var vertexBuffer = this.getVertexBuffer(kind);
  18031. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18032. updatableNormals = vertexBuffer.isUpdatable();
  18033. kinds.splice(kindIndex, 1);
  18034. kindIndex--;
  18035. continue;
  18036. }
  18037. vbs[kind] = vertexBuffer;
  18038. data[kind] = vbs[kind].getData();
  18039. newdata[kind] = [];
  18040. }
  18041. // Save previous submeshes
  18042. var previousSubmeshes = this.subMeshes.slice(0);
  18043. var indices = this.getIndices();
  18044. var totalIndices = this.getTotalIndices();
  18045. // Generating unique vertices per face
  18046. var index;
  18047. for (index = 0; index < totalIndices; index++) {
  18048. var vertexIndex = indices[index];
  18049. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18050. kind = kinds[kindIndex];
  18051. var stride = vbs[kind].getStrideSize();
  18052. for (var offset = 0; offset < stride; offset++) {
  18053. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18054. }
  18055. }
  18056. }
  18057. // Updating faces & normal
  18058. var normals = [];
  18059. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18060. for (index = 0; index < totalIndices; index += 3) {
  18061. indices[index] = index;
  18062. indices[index + 1] = index + 1;
  18063. indices[index + 2] = index + 2;
  18064. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18065. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18066. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18067. var p1p2 = p1.subtract(p2);
  18068. var p3p2 = p3.subtract(p2);
  18069. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18070. // Store same normals for every vertex
  18071. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18072. normals.push(normal.x);
  18073. normals.push(normal.y);
  18074. normals.push(normal.z);
  18075. }
  18076. }
  18077. this.setIndices(indices);
  18078. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18079. // Updating vertex buffers
  18080. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18081. kind = kinds[kindIndex];
  18082. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18083. }
  18084. // Updating submeshes
  18085. this.releaseSubMeshes();
  18086. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18087. var previousOne = previousSubmeshes[submeshIndex];
  18088. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18089. }
  18090. this.synchronizeInstances();
  18091. };
  18092. /**
  18093. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18094. * In other words, more vertices, no more indices and a single bigger VBO.
  18095. * This method returns nothing.
  18096. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18097. *
  18098. */
  18099. Mesh.prototype.convertToUnIndexedMesh = function () {
  18100. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18101. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18102. var kinds = this.getVerticesDataKinds();
  18103. var vbs = [];
  18104. var data = [];
  18105. var newdata = [];
  18106. var updatableNormals = false;
  18107. var kindIndex;
  18108. var kind;
  18109. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18110. kind = kinds[kindIndex];
  18111. var vertexBuffer = this.getVertexBuffer(kind);
  18112. vbs[kind] = vertexBuffer;
  18113. data[kind] = vbs[kind].getData();
  18114. newdata[kind] = [];
  18115. }
  18116. // Save previous submeshes
  18117. var previousSubmeshes = this.subMeshes.slice(0);
  18118. var indices = this.getIndices();
  18119. var totalIndices = this.getTotalIndices();
  18120. // Generating unique vertices per face
  18121. var index;
  18122. for (index = 0; index < totalIndices; index++) {
  18123. var vertexIndex = indices[index];
  18124. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18125. kind = kinds[kindIndex];
  18126. var stride = vbs[kind].getStrideSize();
  18127. for (var offset = 0; offset < stride; offset++) {
  18128. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18129. }
  18130. }
  18131. }
  18132. // Updating indices
  18133. for (index = 0; index < totalIndices; index += 3) {
  18134. indices[index] = index;
  18135. indices[index + 1] = index + 1;
  18136. indices[index + 2] = index + 2;
  18137. }
  18138. this.setIndices(indices);
  18139. // Updating vertex buffers
  18140. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18141. kind = kinds[kindIndex];
  18142. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18143. }
  18144. // Updating submeshes
  18145. this.releaseSubMeshes();
  18146. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18147. var previousOne = previousSubmeshes[submeshIndex];
  18148. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18149. }
  18150. this._unIndexed = true;
  18151. this.synchronizeInstances();
  18152. };
  18153. /**
  18154. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18155. * This method returns nothing.
  18156. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18157. */
  18158. Mesh.prototype.flipFaces = function (flipNormals) {
  18159. if (flipNormals === void 0) { flipNormals = false; }
  18160. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18161. var i;
  18162. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18163. for (i = 0; i < vertex_data.normals.length; i++) {
  18164. vertex_data.normals[i] *= -1;
  18165. }
  18166. }
  18167. var temp;
  18168. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18169. // reassign indices
  18170. temp = vertex_data.indices[i + 1];
  18171. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18172. vertex_data.indices[i + 2] = temp;
  18173. }
  18174. vertex_data.applyToMesh(this);
  18175. };
  18176. // Instances
  18177. /**
  18178. * Creates a new `InstancedMesh` object from the mesh model.
  18179. * An instance shares the same properties and the same material than its model.
  18180. * Only these properties of each instance can then be set individually :
  18181. * - position
  18182. * - rotation
  18183. * - rotationQuaternion
  18184. * - setPivotMatrix
  18185. * - scaling
  18186. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18187. * Warning : this method is not supported for `Line` mesh and `LineSystem`
  18188. */
  18189. Mesh.prototype.createInstance = function (name) {
  18190. return new BABYLON.InstancedMesh(name, this);
  18191. };
  18192. /**
  18193. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18194. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18195. * This method returns nothing.
  18196. */
  18197. Mesh.prototype.synchronizeInstances = function () {
  18198. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18199. var instance = this.instances[instanceIndex];
  18200. instance._syncSubMeshes();
  18201. }
  18202. };
  18203. /**
  18204. * Simplify the mesh according to the given array of settings.
  18205. * Function will return immediately and will simplify async. It returns nothing.
  18206. * @param settings a collection of simplification settings.
  18207. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18208. * @param type the type of simplification to run.
  18209. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18210. */
  18211. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18212. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18213. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18214. this.getScene().simplificationQueue.addTask({
  18215. settings: settings,
  18216. parallelProcessing: parallelProcessing,
  18217. mesh: this,
  18218. simplificationType: simplificationType,
  18219. successCallback: successCallback
  18220. });
  18221. };
  18222. /**
  18223. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18224. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18225. * This should be used together with the simplification to avoid disappearing triangles.
  18226. * @param successCallback an optional success callback to be called after the optimization finished.
  18227. */
  18228. Mesh.prototype.optimizeIndices = function (successCallback) {
  18229. var _this = this;
  18230. var indices = this.getIndices();
  18231. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18232. var vectorPositions = [];
  18233. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18234. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18235. }
  18236. var dupes = [];
  18237. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18238. var realPos = vectorPositions.length - 1 - iteration;
  18239. var testedPosition = vectorPositions[realPos];
  18240. for (var j = 0; j < realPos; ++j) {
  18241. var againstPosition = vectorPositions[j];
  18242. if (testedPosition.equals(againstPosition)) {
  18243. dupes[realPos] = j;
  18244. break;
  18245. }
  18246. }
  18247. }, function () {
  18248. for (var i = 0; i < indices.length; ++i) {
  18249. indices[i] = dupes[indices[i]] || indices[i];
  18250. }
  18251. //indices are now reordered
  18252. var originalSubMeshes = _this.subMeshes.slice(0);
  18253. _this.setIndices(indices);
  18254. _this.subMeshes = originalSubMeshes;
  18255. if (successCallback) {
  18256. successCallback(_this);
  18257. }
  18258. });
  18259. };
  18260. // Statics
  18261. /**
  18262. * Returns a new `Mesh` object what is a deep copy of the passed mesh.
  18263. * The parameter `parsedMesh` is the mesh to be copied.
  18264. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18265. */
  18266. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18267. var mesh = new Mesh(parsedMesh.name, scene);
  18268. mesh.id = parsedMesh.id;
  18269. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18270. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18271. if (parsedMesh.rotationQuaternion) {
  18272. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18273. }
  18274. else if (parsedMesh.rotation) {
  18275. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18276. }
  18277. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18278. if (parsedMesh.localMatrix) {
  18279. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18280. }
  18281. else if (parsedMesh.pivotMatrix) {
  18282. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18283. }
  18284. mesh.setEnabled(parsedMesh.isEnabled);
  18285. mesh.isVisible = parsedMesh.isVisible;
  18286. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18287. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18288. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18289. if (parsedMesh.applyFog !== undefined) {
  18290. mesh.applyFog = parsedMesh.applyFog;
  18291. }
  18292. if (parsedMesh.pickable !== undefined) {
  18293. mesh.isPickable = parsedMesh.pickable;
  18294. }
  18295. if (parsedMesh.alphaIndex !== undefined) {
  18296. mesh.alphaIndex = parsedMesh.alphaIndex;
  18297. }
  18298. mesh.receiveShadows = parsedMesh.receiveShadows;
  18299. mesh.billboardMode = parsedMesh.billboardMode;
  18300. if (parsedMesh.visibility !== undefined) {
  18301. mesh.visibility = parsedMesh.visibility;
  18302. }
  18303. mesh.checkCollisions = parsedMesh.checkCollisions;
  18304. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18305. // freezeWorldMatrix
  18306. if (parsedMesh.freezeWorldMatrix) {
  18307. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18308. }
  18309. // Parent
  18310. if (parsedMesh.parentId) {
  18311. mesh._waitingParentId = parsedMesh.parentId;
  18312. }
  18313. // Actions
  18314. if (parsedMesh.actions !== undefined) {
  18315. mesh._waitingActions = parsedMesh.actions;
  18316. }
  18317. // Geometry
  18318. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18319. if (parsedMesh.delayLoadingFile) {
  18320. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18321. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18322. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18323. if (parsedMesh._binaryInfo) {
  18324. mesh._binaryInfo = parsedMesh._binaryInfo;
  18325. }
  18326. mesh._delayInfo = [];
  18327. if (parsedMesh.hasUVs) {
  18328. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18329. }
  18330. if (parsedMesh.hasUVs2) {
  18331. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18332. }
  18333. if (parsedMesh.hasUVs3) {
  18334. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18335. }
  18336. if (parsedMesh.hasUVs4) {
  18337. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18338. }
  18339. if (parsedMesh.hasUVs5) {
  18340. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18341. }
  18342. if (parsedMesh.hasUVs6) {
  18343. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18344. }
  18345. if (parsedMesh.hasColors) {
  18346. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18347. }
  18348. if (parsedMesh.hasMatricesIndices) {
  18349. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18350. }
  18351. if (parsedMesh.hasMatricesWeights) {
  18352. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18353. }
  18354. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18355. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18356. mesh._checkDelayState();
  18357. }
  18358. }
  18359. else {
  18360. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18361. }
  18362. // Material
  18363. if (parsedMesh.materialId) {
  18364. mesh.setMaterialByID(parsedMesh.materialId);
  18365. }
  18366. else {
  18367. mesh.material = null;
  18368. }
  18369. // Skeleton
  18370. if (parsedMesh.skeletonId > -1) {
  18371. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18372. if (parsedMesh.numBoneInfluencers) {
  18373. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18374. }
  18375. }
  18376. // Animations
  18377. if (parsedMesh.animations) {
  18378. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18379. var parsedAnimation = parsedMesh.animations[animationIndex];
  18380. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18381. }
  18382. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18383. }
  18384. if (parsedMesh.autoAnimate) {
  18385. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18386. }
  18387. // Layer Mask
  18388. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18389. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18390. }
  18391. else {
  18392. mesh.layerMask = 0x0FFFFFFF;
  18393. }
  18394. //(Deprecated) physics
  18395. if (parsedMesh.physicsImpostor) {
  18396. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18397. mass: parsedMesh.physicsMass,
  18398. friction: parsedMesh.physicsFriction,
  18399. restitution: parsedMesh.physicsRestitution
  18400. }, scene);
  18401. }
  18402. // Instances
  18403. if (parsedMesh.instances) {
  18404. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18405. var parsedInstance = parsedMesh.instances[index];
  18406. var instance = mesh.createInstance(parsedInstance.name);
  18407. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18408. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18409. if (parsedInstance.rotationQuaternion) {
  18410. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18411. }
  18412. else if (parsedInstance.rotation) {
  18413. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18414. }
  18415. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18416. instance.checkCollisions = mesh.checkCollisions;
  18417. if (parsedMesh.animations) {
  18418. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18419. parsedAnimation = parsedMesh.animations[animationIndex];
  18420. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18421. }
  18422. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18423. }
  18424. }
  18425. }
  18426. return mesh;
  18427. };
  18428. /**
  18429. * Creates a ribbon mesh.
  18430. * Please consider using the same method from the `MeshBuilder` class instead.
  18431. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18432. *
  18433. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18434. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18435. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18436. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18437. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  18438. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  18439. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  18440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18443. */
  18444. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18445. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18446. pathArray: pathArray,
  18447. closeArray: closeArray,
  18448. closePath: closePath,
  18449. offset: offset,
  18450. updatable: updatable,
  18451. sideOrientation: sideOrientation,
  18452. instance: instance
  18453. }, scene);
  18454. };
  18455. /**
  18456. * Creates a plane polygonal mesh. By default, this is a disc.
  18457. * Please consider using the same method from the `MeshBuilder` class instead.
  18458. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18459. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  18460. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18461. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18463. */
  18464. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18465. var options = {
  18466. radius: radius,
  18467. tessellation: tessellation,
  18468. sideOrientation: sideOrientation,
  18469. updatable: updatable
  18470. };
  18471. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18472. };
  18473. /**
  18474. * Creates a box mesh.
  18475. * Please consider using the same method from the `MeshBuilder` class instead.
  18476. * The parameter `size` sets the size (float) of each box side (default 1).
  18477. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18478. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18480. */
  18481. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18482. var options = {
  18483. size: size,
  18484. sideOrientation: sideOrientation,
  18485. updatable: updatable
  18486. };
  18487. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18488. };
  18489. /**
  18490. * Creates a sphere mesh.
  18491. * Please consider using the same method from the `MeshBuilder` class instead.
  18492. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18493. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18497. */
  18498. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18499. var options = {
  18500. segments: segments,
  18501. diameterX: diameter,
  18502. diameterY: diameter,
  18503. diameterZ: diameter,
  18504. sideOrientation: sideOrientation,
  18505. updatable: updatable
  18506. };
  18507. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18508. };
  18509. /**
  18510. * Creates a cylinder or a cone mesh.
  18511. * Please consider using the same method from the `MeshBuilder` class instead.
  18512. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18513. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18514. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  18515. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18516. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18520. */
  18521. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18522. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18523. if (scene !== undefined) {
  18524. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18525. updatable = scene;
  18526. }
  18527. scene = subdivisions;
  18528. subdivisions = 1;
  18529. }
  18530. var options = {
  18531. height: height,
  18532. diameterTop: diameterTop,
  18533. diameterBottom: diameterBottom,
  18534. tessellation: tessellation,
  18535. subdivisions: subdivisions,
  18536. sideOrientation: sideOrientation,
  18537. updatable: updatable
  18538. };
  18539. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18540. };
  18541. // Torus (Code from SharpDX.org)
  18542. /**
  18543. * Creates a torus mesh.
  18544. * Please consider using the same method from the `MeshBuilder` class instead.
  18545. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18546. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18547. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18548. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18549. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18550. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18551. */
  18552. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18553. var options = {
  18554. diameter: diameter,
  18555. thickness: thickness,
  18556. tessellation: tessellation,
  18557. sideOrientation: sideOrientation,
  18558. updatable: updatable
  18559. };
  18560. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18561. };
  18562. /**
  18563. * Creates a torus knot mesh.
  18564. * Please consider using the same method from the `MeshBuilder` class instead.
  18565. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18566. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18567. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18568. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18569. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18570. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18571. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18572. */
  18573. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18574. var options = {
  18575. radius: radius,
  18576. tube: tube,
  18577. radialSegments: radialSegments,
  18578. tubularSegments: tubularSegments,
  18579. p: p,
  18580. q: q,
  18581. sideOrientation: sideOrientation,
  18582. updatable: updatable
  18583. };
  18584. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18585. };
  18586. /**
  18587. * Creates a line mesh.
  18588. * Please consider using the same method from the `MeshBuilder` class instead.
  18589. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18590. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18591. * The parameter `points` is an array successive Vector3.
  18592. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18593. * When updating an instance, remember that only point positions can change, not the number of points.
  18594. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18595. */
  18596. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18597. var options = {
  18598. points: points,
  18599. updatable: updatable,
  18600. instance: instance
  18601. };
  18602. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18603. };
  18604. /**
  18605. * Creates a dashed line mesh.
  18606. * Please consider using the same method from the `MeshBuilder` class instead.
  18607. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18608. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18609. * The parameter `points` is an array successive Vector3.
  18610. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18611. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18612. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18613. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18614. * When updating an instance, remember that only point positions can change, not the number of points.
  18615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18616. */
  18617. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18618. var options = {
  18619. points: points,
  18620. dashSize: dashSize,
  18621. gapSize: gapSize,
  18622. dashNb: dashNb,
  18623. updatable: updatable
  18624. };
  18625. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18626. };
  18627. /**
  18628. * Creates an extruded shape mesh.
  18629. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18630. * Please consider using the same method from the `MeshBuilder` class instead.
  18631. *
  18632. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18633. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18634. * extruded along the Z axis.
  18635. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18636. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  18637. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18638. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18639. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18640. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18641. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18642. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18644. */
  18645. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18646. var options = {
  18647. shape: shape,
  18648. path: path,
  18649. scale: scale,
  18650. rotation: rotation,
  18651. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18652. sideOrientation: sideOrientation,
  18653. instance: instance,
  18654. updatable: updatable
  18655. };
  18656. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18657. };
  18658. /**
  18659. * Creates an custom extruded shape mesh.
  18660. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18661. * Please consider using the same method from the `MeshBuilder` class instead.
  18662. *
  18663. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18664. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18665. * extruded along the Z axis.
  18666. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18667. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18668. * and the distance of this point from the begining of the path :
  18669. * ```rotationFunction = function(i, distance) {
  18670. * // do things
  18671. * return rotationValue; }```
  18672. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18673. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18674. * and the distance of this point from the begining of the path :
  18675. * ````scaleFunction = function(i, distance) {
  18676. * // do things
  18677. * return scaleValue;}```
  18678. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18679. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18680. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18681. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18682. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18683. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18685. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18687. */
  18688. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18689. var options = {
  18690. shape: shape,
  18691. path: path,
  18692. scaleFunction: scaleFunction,
  18693. rotationFunction: rotationFunction,
  18694. ribbonCloseArray: ribbonCloseArray,
  18695. ribbonClosePath: ribbonClosePath,
  18696. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18697. sideOrientation: sideOrientation,
  18698. instance: instance,
  18699. updatable: updatable
  18700. };
  18701. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18702. };
  18703. /**
  18704. * Creates lathe mesh.
  18705. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18706. * Please consider using the same method from the `MeshBuilder` class instead.
  18707. *
  18708. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  18709. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18710. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18711. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18715. */
  18716. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18717. var options = {
  18718. shape: shape,
  18719. radius: radius,
  18720. tessellation: tessellation,
  18721. sideOrientation: sideOrientation,
  18722. updatable: updatable
  18723. };
  18724. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18725. };
  18726. /**
  18727. * Creates a plane mesh.
  18728. * Please consider using the same method from the `MeshBuilder` class instead.
  18729. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18731. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18733. */
  18734. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18735. var options = {
  18736. size: size,
  18737. width: size,
  18738. height: size,
  18739. sideOrientation: sideOrientation,
  18740. updatable: updatable
  18741. };
  18742. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18743. };
  18744. /**
  18745. * Creates a ground mesh.
  18746. * Please consider using the same method from the `MeshBuilder` class instead.
  18747. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18748. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18750. */
  18751. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18752. var options = {
  18753. width: width,
  18754. height: height,
  18755. subdivisions: subdivisions,
  18756. updatable: updatable
  18757. };
  18758. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18759. };
  18760. /**
  18761. * Creates a tiled ground mesh.
  18762. * Please consider using the same method from the `MeshBuilder` class instead.
  18763. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18764. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18765. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18766. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18767. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18768. * numbers of subdivisions on the ground width and height of each tile.
  18769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18770. */
  18771. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18772. var options = {
  18773. xmin: xmin,
  18774. zmin: zmin,
  18775. xmax: xmax,
  18776. zmax: zmax,
  18777. subdivisions: subdivisions,
  18778. precision: precision,
  18779. updatable: updatable
  18780. };
  18781. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18782. };
  18783. /**
  18784. * Creates a ground mesh from a height map.
  18785. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18786. * Please consider using the same method from the `MeshBuilder` class instead.
  18787. * The parameter `url` sets the URL of the height map image resource.
  18788. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18789. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18790. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18791. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18792. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  18793. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18794. * return; }```
  18795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18796. */
  18797. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18798. var options = {
  18799. width: width,
  18800. height: height,
  18801. subdivisions: subdivisions,
  18802. minHeight: minHeight,
  18803. maxHeight: maxHeight,
  18804. updatable: updatable,
  18805. onReady: onReady
  18806. };
  18807. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18808. };
  18809. /**
  18810. * Creates a tube mesh.
  18811. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18812. *
  18813. * Please consider using the same method from the `MeshBuilder` class instead.
  18814. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18815. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18816. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18817. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18818. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  18819. * It must return a radius value (positive float) :
  18820. * ```var radiusFunction = function(i, distance) {
  18821. * // do things
  18822. * return radius; }```
  18823. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18824. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  18825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18828. */
  18829. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18830. var options = {
  18831. path: path,
  18832. radius: radius,
  18833. tessellation: tessellation,
  18834. radiusFunction: radiusFunction,
  18835. arc: 1,
  18836. cap: cap,
  18837. updatable: updatable,
  18838. sideOrientation: sideOrientation,
  18839. instance: instance
  18840. };
  18841. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18842. };
  18843. /**
  18844. * Creates a polyhedron mesh.
  18845. *
  18846. * Please consider using the same method from the `MeshBuilder` class instead.
  18847. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  18848. * to choose the wanted type.
  18849. * The parameter `size` (positive float, default 1) sets the polygon size.
  18850. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18851. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  18852. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  18853. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  18854. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  18855. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  18856. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18857. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18859. */
  18860. Mesh.CreatePolyhedron = function (name, options, scene) {
  18861. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18862. };
  18863. /**
  18864. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18865. * Please consider using the same method from the `MeshBuilder` class instead.
  18866. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18867. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  18868. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18869. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  18870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18873. */
  18874. Mesh.CreateIcoSphere = function (name, options, scene) {
  18875. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18876. };
  18877. /**
  18878. * Creates a decal mesh.
  18879. * Please consider using the same method from the `MeshBuilder` class instead.
  18880. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  18881. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18882. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18883. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18884. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18885. */
  18886. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18887. var options = {
  18888. position: position,
  18889. normal: normal,
  18890. size: size,
  18891. angle: angle
  18892. };
  18893. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18894. };
  18895. // Skeletons
  18896. /**
  18897. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18898. */
  18899. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18900. var source;
  18901. if (!this._sourcePositions) {
  18902. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18903. this._sourcePositions = new Float32Array(source);
  18904. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18905. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18906. }
  18907. }
  18908. return this._sourcePositions;
  18909. };
  18910. /**
  18911. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18912. */
  18913. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18914. var source;
  18915. if (!this._sourceNormals) {
  18916. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18917. this._sourceNormals = new Float32Array(source);
  18918. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18919. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18920. }
  18921. }
  18922. return this._sourceNormals;
  18923. };
  18924. /**
  18925. * Update the vertex buffers by applying transformation from the bones
  18926. * @param {skeleton} skeleton to apply
  18927. */
  18928. Mesh.prototype.applySkeleton = function (skeleton) {
  18929. if (!this.geometry) {
  18930. return;
  18931. }
  18932. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18933. return;
  18934. }
  18935. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18936. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18937. return this;
  18938. }
  18939. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18940. return this;
  18941. }
  18942. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18943. return this;
  18944. }
  18945. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18946. return this;
  18947. }
  18948. if (!this._sourcePositions) {
  18949. this.setPositionsForCPUSkinning();
  18950. }
  18951. if (!this._sourceNormals) {
  18952. this.setNormalsForCPUSkinning();
  18953. }
  18954. // positionsData checks for not being Float32Array will only pass at most once
  18955. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18956. if (!(positionsData instanceof Float32Array)) {
  18957. positionsData = new Float32Array(positionsData);
  18958. }
  18959. // normalsData checks for not being Float32Array will only pass at most once
  18960. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18961. if (!(normalsData instanceof Float32Array)) {
  18962. normalsData = new Float32Array(normalsData);
  18963. }
  18964. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18965. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18966. var needExtras = this.numBoneInfluencers > 4;
  18967. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18968. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18969. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18970. var tempVector3 = BABYLON.Vector3.Zero();
  18971. var finalMatrix = new BABYLON.Matrix();
  18972. var tempMatrix = new BABYLON.Matrix();
  18973. var matWeightIdx = 0;
  18974. var inf;
  18975. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18976. var weight;
  18977. for (inf = 0; inf < 4; inf++) {
  18978. weight = matricesWeightsData[matWeightIdx + inf];
  18979. if (weight > 0) {
  18980. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18981. finalMatrix.addToSelf(tempMatrix);
  18982. }
  18983. else
  18984. break;
  18985. }
  18986. if (needExtras) {
  18987. for (inf = 0; inf < 4; inf++) {
  18988. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18989. if (weight > 0) {
  18990. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18991. finalMatrix.addToSelf(tempMatrix);
  18992. }
  18993. else
  18994. break;
  18995. }
  18996. }
  18997. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18998. tempVector3.toArray(positionsData, index);
  18999. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  19000. tempVector3.toArray(normalsData, index);
  19001. finalMatrix.reset();
  19002. }
  19003. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  19004. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  19005. return this;
  19006. };
  19007. // Tools
  19008. /**
  19009. * Returns an object `{min: Vector3, max: Vector3}`
  19010. * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19011. */
  19012. Mesh.MinMax = function (meshes) {
  19013. var minVector = null;
  19014. var maxVector = null;
  19015. for (var i in meshes) {
  19016. var mesh = meshes[i];
  19017. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19018. if (!minVector) {
  19019. minVector = boundingBox.minimumWorld;
  19020. maxVector = boundingBox.maximumWorld;
  19021. continue;
  19022. }
  19023. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19024. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19025. }
  19026. return {
  19027. min: minVector,
  19028. max: maxVector
  19029. };
  19030. };
  19031. /**
  19032. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  19033. */
  19034. Mesh.Center = function (meshesOrMinMaxVector) {
  19035. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19036. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19037. };
  19038. /**
  19039. * Merge the array of meshes into a single mesh for performance reasons.
  19040. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19041. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19042. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19043. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19044. */
  19045. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19046. if (disposeSource === void 0) { disposeSource = true; }
  19047. var index;
  19048. if (!allow32BitsIndices) {
  19049. var totalVertices = 0;
  19050. // Counting vertices
  19051. for (index = 0; index < meshes.length; index++) {
  19052. if (meshes[index]) {
  19053. totalVertices += meshes[index].getTotalVertices();
  19054. if (totalVertices > 65536) {
  19055. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19056. return null;
  19057. }
  19058. }
  19059. }
  19060. }
  19061. // Merge
  19062. var vertexData;
  19063. var otherVertexData;
  19064. var source;
  19065. for (index = 0; index < meshes.length; index++) {
  19066. if (meshes[index]) {
  19067. meshes[index].computeWorldMatrix(true);
  19068. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19069. otherVertexData.transform(meshes[index].getWorldMatrix());
  19070. if (vertexData) {
  19071. vertexData.merge(otherVertexData);
  19072. }
  19073. else {
  19074. vertexData = otherVertexData;
  19075. source = meshes[index];
  19076. }
  19077. }
  19078. }
  19079. if (!meshSubclass) {
  19080. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19081. }
  19082. vertexData.applyToMesh(meshSubclass);
  19083. // Setting properties
  19084. meshSubclass.material = source.material;
  19085. meshSubclass.checkCollisions = source.checkCollisions;
  19086. // Cleaning
  19087. if (disposeSource) {
  19088. for (index = 0; index < meshes.length; index++) {
  19089. if (meshes[index]) {
  19090. meshes[index].dispose();
  19091. }
  19092. }
  19093. }
  19094. return meshSubclass;
  19095. };
  19096. // Consts
  19097. Mesh._FRONTSIDE = 0;
  19098. Mesh._BACKSIDE = 1;
  19099. Mesh._DOUBLESIDE = 2;
  19100. Mesh._DEFAULTSIDE = 0;
  19101. Mesh._NO_CAP = 0;
  19102. Mesh._CAP_START = 1;
  19103. Mesh._CAP_END = 2;
  19104. Mesh._CAP_ALL = 3;
  19105. return Mesh;
  19106. })(BABYLON.AbstractMesh);
  19107. BABYLON.Mesh = Mesh;
  19108. })(BABYLON || (BABYLON = {}));
  19109. var BABYLON;
  19110. (function (BABYLON) {
  19111. var SubMesh = (function () {
  19112. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19113. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19114. this.materialIndex = materialIndex;
  19115. this.verticesStart = verticesStart;
  19116. this.verticesCount = verticesCount;
  19117. this.indexStart = indexStart;
  19118. this.indexCount = indexCount;
  19119. this._renderId = 0;
  19120. this._mesh = mesh;
  19121. this._renderingMesh = renderingMesh || mesh;
  19122. mesh.subMeshes.push(this);
  19123. this._trianglePlanes = [];
  19124. this._id = mesh.subMeshes.length - 1;
  19125. if (createBoundingBox) {
  19126. this.refreshBoundingInfo();
  19127. mesh.computeWorldMatrix(true);
  19128. }
  19129. }
  19130. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19131. get: function () {
  19132. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19133. },
  19134. enumerable: true,
  19135. configurable: true
  19136. });
  19137. SubMesh.prototype.getBoundingInfo = function () {
  19138. if (this.IsGlobal) {
  19139. return this._mesh.getBoundingInfo();
  19140. }
  19141. return this._boundingInfo;
  19142. };
  19143. SubMesh.prototype.getMesh = function () {
  19144. return this._mesh;
  19145. };
  19146. SubMesh.prototype.getRenderingMesh = function () {
  19147. return this._renderingMesh;
  19148. };
  19149. SubMesh.prototype.getMaterial = function () {
  19150. var rootMaterial = this._renderingMesh.material;
  19151. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19152. var multiMaterial = rootMaterial;
  19153. return multiMaterial.getSubMaterial(this.materialIndex);
  19154. }
  19155. if (!rootMaterial) {
  19156. return this._mesh.getScene().defaultMaterial;
  19157. }
  19158. return rootMaterial;
  19159. };
  19160. // Methods
  19161. SubMesh.prototype.refreshBoundingInfo = function () {
  19162. this._lastColliderWorldVertices = null;
  19163. if (this.IsGlobal) {
  19164. return;
  19165. }
  19166. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19167. if (!data) {
  19168. this._boundingInfo = this._mesh._boundingInfo;
  19169. return;
  19170. }
  19171. var indices = this._renderingMesh.getIndices();
  19172. var extend;
  19173. //is this the only submesh?
  19174. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19175. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19176. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19177. }
  19178. else {
  19179. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19180. }
  19181. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19182. };
  19183. SubMesh.prototype._checkCollision = function (collider) {
  19184. return this.getBoundingInfo()._checkCollision(collider);
  19185. };
  19186. SubMesh.prototype.updateBoundingInfo = function (world) {
  19187. if (!this.getBoundingInfo()) {
  19188. this.refreshBoundingInfo();
  19189. }
  19190. this.getBoundingInfo().update(world);
  19191. };
  19192. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19193. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19194. };
  19195. SubMesh.prototype.render = function (enableAlphaMode) {
  19196. this._renderingMesh.render(this, enableAlphaMode);
  19197. };
  19198. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19199. if (!this._linesIndexBuffer) {
  19200. var linesIndices = [];
  19201. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19202. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19203. }
  19204. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19205. this.linesIndexCount = linesIndices.length;
  19206. }
  19207. return this._linesIndexBuffer;
  19208. };
  19209. SubMesh.prototype.canIntersects = function (ray) {
  19210. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19211. };
  19212. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19213. var intersectInfo = null;
  19214. // LineMesh first as it's also a Mesh...
  19215. if (this._mesh instanceof BABYLON.LinesMesh) {
  19216. var lineMesh = this._mesh;
  19217. // Line test
  19218. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19219. var p0 = positions[indices[index]];
  19220. var p1 = positions[indices[index + 1]];
  19221. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19222. if (length < 0) {
  19223. continue;
  19224. }
  19225. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19226. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19227. if (fastCheck) {
  19228. break;
  19229. }
  19230. }
  19231. }
  19232. }
  19233. else {
  19234. // Triangles test
  19235. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19236. var p0 = positions[indices[index]];
  19237. var p1 = positions[indices[index + 1]];
  19238. var p2 = positions[indices[index + 2]];
  19239. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19240. if (currentIntersectInfo) {
  19241. if (currentIntersectInfo.distance < 0) {
  19242. continue;
  19243. }
  19244. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19245. intersectInfo = currentIntersectInfo;
  19246. intersectInfo.faceId = index / 3;
  19247. if (fastCheck) {
  19248. break;
  19249. }
  19250. }
  19251. }
  19252. }
  19253. }
  19254. return intersectInfo;
  19255. };
  19256. // Clone
  19257. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19258. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19259. if (!this.IsGlobal) {
  19260. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19261. }
  19262. return result;
  19263. };
  19264. // Dispose
  19265. SubMesh.prototype.dispose = function () {
  19266. if (this._linesIndexBuffer) {
  19267. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19268. this._linesIndexBuffer = null;
  19269. }
  19270. // Remove from mesh
  19271. var index = this._mesh.subMeshes.indexOf(this);
  19272. this._mesh.subMeshes.splice(index, 1);
  19273. };
  19274. // Statics
  19275. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19276. var minVertexIndex = Number.MAX_VALUE;
  19277. var maxVertexIndex = -Number.MAX_VALUE;
  19278. renderingMesh = renderingMesh || mesh;
  19279. var indices = renderingMesh.getIndices();
  19280. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19281. var vertexIndex = indices[index];
  19282. if (vertexIndex < minVertexIndex)
  19283. minVertexIndex = vertexIndex;
  19284. if (vertexIndex > maxVertexIndex)
  19285. maxVertexIndex = vertexIndex;
  19286. }
  19287. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19288. };
  19289. return SubMesh;
  19290. })();
  19291. BABYLON.SubMesh = SubMesh;
  19292. })(BABYLON || (BABYLON = {}));
  19293. var BABYLON;
  19294. (function (BABYLON) {
  19295. var MeshBuilder = (function () {
  19296. function MeshBuilder() {
  19297. }
  19298. /**
  19299. * Creates a box mesh.
  19300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19301. * The parameter `size` sets the size (float) of each box side (default 1).
  19302. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19303. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 `Color3` elements) and `faceUV` (an array of 6 `Vector4` elements).
  19304. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19308. */
  19309. MeshBuilder.CreateBox = function (name, options, scene) {
  19310. var box = new BABYLON.Mesh(name, scene);
  19311. var vertexData = BABYLON.VertexData.CreateBox(options);
  19312. vertexData.applyToMesh(box, options.updatable);
  19313. return box;
  19314. };
  19315. /**
  19316. * Creates a sphere mesh.
  19317. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19318. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19319. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  19320. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19321. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  19322. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  19323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19324. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19326. */
  19327. MeshBuilder.CreateSphere = function (name, options, scene) {
  19328. var sphere = new BABYLON.Mesh(name, scene);
  19329. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19330. vertexData.applyToMesh(sphere, options.updatable);
  19331. return sphere;
  19332. };
  19333. /**
  19334. * Creates a plane polygonal mesh. By default, this is a disc.
  19335. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19336. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19337. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  19338. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  19339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19341. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19342. */
  19343. MeshBuilder.CreateDisc = function (name, options, scene) {
  19344. var disc = new BABYLON.Mesh(name, scene);
  19345. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19346. vertexData.applyToMesh(disc, options.updatable);
  19347. return disc;
  19348. };
  19349. /**
  19350. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19351. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19352. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19353. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  19354. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19355. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  19356. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19359. */
  19360. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19361. var sphere = new BABYLON.Mesh(name, scene);
  19362. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19363. vertexData.applyToMesh(sphere, options.updatable);
  19364. return sphere;
  19365. };
  19366. ;
  19367. /**
  19368. * Creates a ribbon mesh.
  19369. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19370. *
  19371. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19372. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19373. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19374. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19375. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  19376. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  19377. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  19378. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19379. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19380. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19381. */
  19382. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19383. var pathArray = options.pathArray;
  19384. var closeArray = options.closeArray;
  19385. var closePath = options.closePath;
  19386. var offset = options.offset;
  19387. var sideOrientation = options.sideOrientation;
  19388. var instance = options.instance;
  19389. var updatable = options.updatable;
  19390. if (instance) {
  19391. // positionFunction : ribbon case
  19392. // only pathArray and sideOrientation parameters are taken into account for positions update
  19393. var positionFunction = function (positions) {
  19394. var minlg = pathArray[0].length;
  19395. var i = 0;
  19396. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19397. for (var si = 1; si <= ns; si++) {
  19398. for (var p = 0; p < pathArray.length; p++) {
  19399. var path = pathArray[p];
  19400. var l = path.length;
  19401. minlg = (minlg < l) ? minlg : l;
  19402. var j = 0;
  19403. while (j < minlg) {
  19404. positions[i] = path[j].x;
  19405. positions[i + 1] = path[j].y;
  19406. positions[i + 2] = path[j].z;
  19407. j++;
  19408. i += 3;
  19409. }
  19410. if (instance._closePath) {
  19411. positions[i] = path[0].x;
  19412. positions[i + 1] = path[0].y;
  19413. positions[i + 2] = path[0].z;
  19414. i += 3;
  19415. }
  19416. }
  19417. }
  19418. };
  19419. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19420. positionFunction(positions);
  19421. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19422. if (!(instance.areNormalsFrozen)) {
  19423. var indices = instance.getIndices();
  19424. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19425. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19426. if (instance._closePath) {
  19427. var indexFirst = 0;
  19428. var indexLast = 0;
  19429. for (var p = 0; p < pathArray.length; p++) {
  19430. indexFirst = instance._idx[p] * 3;
  19431. if (p + 1 < pathArray.length) {
  19432. indexLast = (instance._idx[p + 1] - 1) * 3;
  19433. }
  19434. else {
  19435. indexLast = normals.length - 3;
  19436. }
  19437. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19438. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19439. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19440. normals[indexLast] = normals[indexFirst];
  19441. normals[indexLast + 1] = normals[indexFirst + 1];
  19442. normals[indexLast + 2] = normals[indexFirst + 2];
  19443. }
  19444. }
  19445. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19446. }
  19447. return instance;
  19448. }
  19449. else {
  19450. var ribbon = new BABYLON.Mesh(name, scene);
  19451. ribbon.sideOrientation = sideOrientation;
  19452. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19453. if (closePath) {
  19454. ribbon._idx = vertexData._idx;
  19455. }
  19456. ribbon._closePath = closePath;
  19457. ribbon._closeArray = closeArray;
  19458. vertexData.applyToMesh(ribbon, updatable);
  19459. return ribbon;
  19460. }
  19461. };
  19462. /**
  19463. * Creates a cylinder or a cone mesh.
  19464. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19465. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19466. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19467. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  19468. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19469. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19470. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19471. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19472. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19473. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n `Color3` elements) and `faceUV` (an array of n `Vector4` elements).
  19474. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  19475. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19476. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  19477. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  19478. * If `enclose` is false, a ring surface is one element.
  19479. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19480. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  19481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19482. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19484. */
  19485. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19486. var cylinder = new BABYLON.Mesh(name, scene);
  19487. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19488. vertexData.applyToMesh(cylinder, options.updatable);
  19489. return cylinder;
  19490. };
  19491. /**
  19492. * Creates a torus mesh.
  19493. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19494. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19495. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19496. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19497. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19498. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19500. */
  19501. MeshBuilder.CreateTorus = function (name, options, scene) {
  19502. var torus = new BABYLON.Mesh(name, scene);
  19503. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19504. vertexData.applyToMesh(torus, options.updatable);
  19505. return torus;
  19506. };
  19507. /**
  19508. * Creates a torus knot mesh.
  19509. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19510. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19511. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19512. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19513. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19514. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19517. */
  19518. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19519. var torusKnot = new BABYLON.Mesh(name, scene);
  19520. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19521. vertexData.applyToMesh(torusKnot, options.updatable);
  19522. return torusKnot;
  19523. };
  19524. /**
  19525. * Creates a line system mesh.
  19526. * A line system is a pool of many lines gathered in a single mesh.
  19527. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19528. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  19529. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19530. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19531. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  19532. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19533. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19535. */
  19536. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19537. var instance = options.instance;
  19538. var lines = options.lines;
  19539. if (instance) {
  19540. var positionFunction = function (positions) {
  19541. var i = 0;
  19542. for (var l = 0; l < lines.length; l++) {
  19543. var points = lines[l];
  19544. for (var p = 0; p < points.length; p++) {
  19545. positions[i] = points[p].x;
  19546. positions[i + 1] = points[p].y;
  19547. positions[i + 2] = points[p].z;
  19548. i += 3;
  19549. }
  19550. }
  19551. };
  19552. instance.updateMeshPositions(positionFunction, false);
  19553. return instance;
  19554. }
  19555. // line system creation
  19556. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19557. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19558. vertexData.applyToMesh(lineSystem, options.updatable);
  19559. return lineSystem;
  19560. };
  19561. /**
  19562. * Creates a line mesh.
  19563. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19564. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19565. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19566. * The parameter `points` is an array successive Vector3.
  19567. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19568. * When updating an instance, remember that only point positions can change, not the number of points.
  19569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19570. */
  19571. MeshBuilder.CreateLines = function (name, options, scene) {
  19572. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19573. return lines;
  19574. };
  19575. /**
  19576. * Creates a dashed line mesh.
  19577. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19578. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19579. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19580. * The parameter `points` is an array successive Vector3.
  19581. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19582. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19583. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19584. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19585. * When updating an instance, remember that only point positions can change, not the number of points.
  19586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19587. */
  19588. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19589. var points = options.points;
  19590. var instance = options.instance;
  19591. var gapSize = options.gapSize;
  19592. var dashNb = options.dashNb;
  19593. var dashSize = options.dashSize;
  19594. if (instance) {
  19595. var positionFunction = function (positions) {
  19596. var curvect = BABYLON.Vector3.Zero();
  19597. var nbSeg = positions.length / 6;
  19598. var lg = 0;
  19599. var nb = 0;
  19600. var shft = 0;
  19601. var dashshft = 0;
  19602. var curshft = 0;
  19603. var p = 0;
  19604. var i = 0;
  19605. var j = 0;
  19606. for (i = 0; i < points.length - 1; i++) {
  19607. points[i + 1].subtractToRef(points[i], curvect);
  19608. lg += curvect.length();
  19609. }
  19610. shft = lg / nbSeg;
  19611. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19612. for (i = 0; i < points.length - 1; i++) {
  19613. points[i + 1].subtractToRef(points[i], curvect);
  19614. nb = Math.floor(curvect.length() / shft);
  19615. curvect.normalize();
  19616. j = 0;
  19617. while (j < nb && p < positions.length) {
  19618. curshft = shft * j;
  19619. positions[p] = points[i].x + curshft * curvect.x;
  19620. positions[p + 1] = points[i].y + curshft * curvect.y;
  19621. positions[p + 2] = points[i].z + curshft * curvect.z;
  19622. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19623. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19624. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19625. p += 6;
  19626. j++;
  19627. }
  19628. }
  19629. while (p < positions.length) {
  19630. positions[p] = points[i].x;
  19631. positions[p + 1] = points[i].y;
  19632. positions[p + 2] = points[i].z;
  19633. p += 3;
  19634. }
  19635. };
  19636. instance.updateMeshPositions(positionFunction, false);
  19637. return instance;
  19638. }
  19639. // dashed lines creation
  19640. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19641. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19642. vertexData.applyToMesh(dashedLines, options.updatable);
  19643. dashedLines.dashSize = dashSize;
  19644. dashedLines.gapSize = gapSize;
  19645. return dashedLines;
  19646. };
  19647. /**
  19648. * Creates an extruded shape mesh.
  19649. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19651. *
  19652. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19653. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19654. * extruded along the Z axis.
  19655. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19656. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  19657. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19658. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19659. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19660. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19661. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19664. */
  19665. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19666. var path = options.path;
  19667. var shape = options.shape;
  19668. var scale = options.scale || 1;
  19669. var rotation = options.rotation || 0;
  19670. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19671. var updatable = options.updatable;
  19672. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19673. var instance = options.instance;
  19674. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19675. };
  19676. /**
  19677. * Creates an custom extruded shape mesh.
  19678. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19679. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19680. *
  19681. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19682. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19683. * extruded along the Z axis.
  19684. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19685. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19686. * and the distance of this point from the begining of the path :
  19687. * ```rotationFunction = function(i, distance) {
  19688. * // do things
  19689. * return rotationValue; }```
  19690. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19691. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19692. * and the distance of this point from the begining of the path :
  19693. * ````scaleFunction = function(i, distance) {
  19694. * // do things
  19695. * return scaleValue;}```
  19696. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19697. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19698. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19699. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19700. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19701. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19703. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19705. */
  19706. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19707. var path = options.path;
  19708. var shape = options.shape;
  19709. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19710. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19711. var ribbonCloseArray = options.ribbonCloseArray || false;
  19712. var ribbonClosePath = options.ribbonClosePath || false;
  19713. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19714. var updatable = options.updatable;
  19715. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19716. var instance = options.instance;
  19717. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19718. };
  19719. /**
  19720. * Creates lathe mesh.
  19721. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19722. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19723. *
  19724. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  19725. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19726. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19727. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19728. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  19729. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19730. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19732. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19734. */
  19735. MeshBuilder.CreateLathe = function (name, options, scene) {
  19736. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19737. var closed = (options.closed === undefined) ? true : options.closed;
  19738. var shape = options.shape;
  19739. var radius = options.radius || 1;
  19740. var tessellation = options.tessellation || 64;
  19741. var updatable = options.updatable;
  19742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19743. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19744. var pi2 = Math.PI * 2;
  19745. var paths = new Array();
  19746. var i = 0;
  19747. var p = 0;
  19748. var step = pi2 / tessellation * arc;
  19749. var rotated;
  19750. var path = new Array();
  19751. ;
  19752. for (i = 0; i <= tessellation; i++) {
  19753. var path = [];
  19754. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19755. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19756. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19757. }
  19758. for (p = 0; p < shape.length; p++) {
  19759. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19760. path.push(rotated);
  19761. }
  19762. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19763. 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));
  19764. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19765. }
  19766. paths.push(path);
  19767. }
  19768. // lathe ribbon
  19769. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19770. return lathe;
  19771. };
  19772. /**
  19773. * Creates a plane mesh.
  19774. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19775. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19776. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19777. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19778. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19779. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19781. */
  19782. MeshBuilder.CreatePlane = function (name, options, scene) {
  19783. var plane = new BABYLON.Mesh(name, scene);
  19784. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19785. vertexData.applyToMesh(plane, options.updatable);
  19786. if (options.sourcePlane) {
  19787. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19788. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19789. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19790. plane.rotate(vectorProduct, product);
  19791. }
  19792. return plane;
  19793. };
  19794. /**
  19795. * Creates a ground mesh.
  19796. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19797. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19798. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19799. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19800. */
  19801. MeshBuilder.CreateGround = function (name, options, scene) {
  19802. var ground = new BABYLON.GroundMesh(name, scene);
  19803. ground._setReady(false);
  19804. ground._subdivisions = options.subdivisions || 1;
  19805. ground._width = options.width || 1;
  19806. ground._height = options.height || 1;
  19807. ground._maxX = ground._width / 2;
  19808. ground._maxZ = ground._height / 2;
  19809. ground._minX = -ground._maxX;
  19810. ground._minZ = -ground._maxZ;
  19811. var vertexData = BABYLON.VertexData.CreateGround(options);
  19812. vertexData.applyToMesh(ground, options.updatable);
  19813. ground._setReady(true);
  19814. return ground;
  19815. };
  19816. /**
  19817. * Creates a tiled ground mesh.
  19818. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19819. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19820. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19821. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19822. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19823. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19824. * numbers of subdivisions on the ground width and height of each tile.
  19825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19826. */
  19827. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19828. var tiledGround = new BABYLON.Mesh(name, scene);
  19829. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19830. vertexData.applyToMesh(tiledGround, options.updatable);
  19831. return tiledGround;
  19832. };
  19833. /**
  19834. * Creates a ground mesh from a height map.
  19835. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19837. * The parameter `url` sets the URL of the height map image resource.
  19838. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19839. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19840. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19841. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19842. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  19843. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19844. * return; }```
  19845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19846. */
  19847. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19848. var width = options.width || 10;
  19849. var height = options.height || 10;
  19850. var subdivisions = options.subdivisions || 1;
  19851. var minHeight = options.minHeight;
  19852. var maxHeight = options.maxHeight || 10;
  19853. var updatable = options.updatable;
  19854. var onReady = options.onReady;
  19855. var ground = new BABYLON.GroundMesh(name, scene);
  19856. ground._subdivisions = subdivisions;
  19857. ground._width = width;
  19858. ground._height = height;
  19859. ground._maxX = ground._width / 2;
  19860. ground._maxZ = ground._height / 2;
  19861. ground._minX = -ground._maxX;
  19862. ground._minZ = -ground._maxZ;
  19863. ground._setReady(false);
  19864. var onload = function (img) {
  19865. // Getting height map data
  19866. var canvas = document.createElement("canvas");
  19867. var context = canvas.getContext("2d");
  19868. var bufferWidth = img.width;
  19869. var bufferHeight = img.height;
  19870. canvas.width = bufferWidth;
  19871. canvas.height = bufferHeight;
  19872. context.drawImage(img, 0, 0);
  19873. // Create VertexData from map data
  19874. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19875. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19876. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19877. width: width, height: height,
  19878. subdivisions: subdivisions,
  19879. minHeight: minHeight, maxHeight: maxHeight,
  19880. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19881. });
  19882. vertexData.applyToMesh(ground, updatable);
  19883. ground._setReady(true);
  19884. //execute ready callback, if set
  19885. if (onReady) {
  19886. onReady(ground);
  19887. }
  19888. };
  19889. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19890. return ground;
  19891. };
  19892. /**
  19893. * Creates a tube mesh.
  19894. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19895. *
  19896. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19897. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19898. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19899. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19900. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19901. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  19902. * It must return a radius value (positive float) :
  19903. * ```var radiusFunction = function(i, distance) {
  19904. * // do things
  19905. * return radius; }```
  19906. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19907. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19908. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  19909. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19910. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19912. */
  19913. MeshBuilder.CreateTube = function (name, options, scene) {
  19914. var path = options.path;
  19915. var radius = options.radius || 1;
  19916. var tessellation = options.tessellation || 64;
  19917. var radiusFunction = options.radiusFunction;
  19918. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19919. var updatable = options.updatable;
  19920. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19921. var instance = options.instance;
  19922. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19923. // tube geometry
  19924. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19925. var tangents = path3D.getTangents();
  19926. var normals = path3D.getNormals();
  19927. var distances = path3D.getDistances();
  19928. var pi2 = Math.PI * 2;
  19929. var step = pi2 / tessellation * arc;
  19930. var returnRadius = function () { return radius; };
  19931. var radiusFunctionFinal = radiusFunction || returnRadius;
  19932. var circlePath;
  19933. var rad;
  19934. var normal;
  19935. var rotated;
  19936. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19937. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19938. for (var i = 0; i < path.length; i++) {
  19939. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19940. circlePath = Array(); // current circle array
  19941. normal = normals[i]; // current normal
  19942. for (var t = 0; t < tessellation; t++) {
  19943. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19944. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19945. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19946. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19947. circlePath[t] = rotated;
  19948. }
  19949. circlePaths[index] = circlePath;
  19950. index++;
  19951. }
  19952. // cap
  19953. var capPath = function (nbPoints, pathIndex) {
  19954. var pointCap = Array();
  19955. for (var i = 0; i < nbPoints; i++) {
  19956. pointCap.push(path[pathIndex]);
  19957. }
  19958. return pointCap;
  19959. };
  19960. switch (cap) {
  19961. case BABYLON.Mesh.NO_CAP:
  19962. break;
  19963. case BABYLON.Mesh.CAP_START:
  19964. circlePaths[0] = capPath(tessellation, 0);
  19965. circlePaths[1] = circlePaths[2].slice(0);
  19966. break;
  19967. case BABYLON.Mesh.CAP_END:
  19968. circlePaths[index] = circlePaths[index - 1].slice(0);
  19969. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19970. break;
  19971. case BABYLON.Mesh.CAP_ALL:
  19972. circlePaths[0] = capPath(tessellation, 0);
  19973. circlePaths[1] = circlePaths[2].slice(0);
  19974. circlePaths[index] = circlePaths[index - 1].slice(0);
  19975. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19976. break;
  19977. default:
  19978. break;
  19979. }
  19980. return circlePaths;
  19981. };
  19982. var path3D;
  19983. var pathArray;
  19984. if (instance) {
  19985. var arc = options.arc || instance.arc;
  19986. path3D = (instance.path3D).update(path);
  19987. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19988. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19989. instance.path3D = path3D;
  19990. instance.pathArray = pathArray;
  19991. instance.arc = arc;
  19992. return instance;
  19993. }
  19994. // tube creation
  19995. path3D = new BABYLON.Path3D(path);
  19996. var newPathArray = new Array();
  19997. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19998. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19999. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  20000. tube.pathArray = pathArray;
  20001. tube.path3D = path3D;
  20002. tube.tessellation = tessellation;
  20003. tube.cap = cap;
  20004. tube.arc = options.arc;
  20005. return tube;
  20006. };
  20007. /**
  20008. * Creates a polyhedron mesh.
  20009. *
  20010. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20011. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  20012. * to choose the wanted type.
  20013. * The parameter `size` (positive float, default 1) sets the polygon size.
  20014. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20015. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  20016. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  20017. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  20018. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20019. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  20020. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20021. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20023. */
  20024. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20025. var polyhedron = new BABYLON.Mesh(name, scene);
  20026. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20027. vertexData.applyToMesh(polyhedron, options.updatable);
  20028. return polyhedron;
  20029. };
  20030. /**
  20031. * Creates a decal mesh.
  20032. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  20033. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  20034. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20035. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20036. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  20037. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20038. */
  20039. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20040. var indices = sourceMesh.getIndices();
  20041. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20042. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20043. var position = options.position || BABYLON.Vector3.Zero();
  20044. var normal = options.normal || BABYLON.Vector3.Up();
  20045. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20046. var angle = options.angle || 0;
  20047. // Getting correct rotation
  20048. if (!normal) {
  20049. var target = new BABYLON.Vector3(0, 0, 1);
  20050. var camera = sourceMesh.getScene().activeCamera;
  20051. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20052. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20053. }
  20054. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20055. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20056. var pitch = Math.atan2(normal.y, len);
  20057. // Matrix
  20058. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20059. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20060. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20061. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20062. var vertexData = new BABYLON.VertexData();
  20063. vertexData.indices = [];
  20064. vertexData.positions = [];
  20065. vertexData.normals = [];
  20066. vertexData.uvs = [];
  20067. var currentVertexDataIndex = 0;
  20068. var extractDecalVector3 = function (indexId) {
  20069. var vertexId = indices[indexId];
  20070. var result = new BABYLON.PositionNormalVertex();
  20071. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20072. // Send vector to decal local world
  20073. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20074. // Get normal
  20075. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20076. return result;
  20077. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20078. var clip = function (vertices, axis) {
  20079. if (vertices.length === 0) {
  20080. return vertices;
  20081. }
  20082. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20083. var clipVertices = function (v0, v1) {
  20084. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20085. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20086. };
  20087. var result = new Array();
  20088. for (var index = 0; index < vertices.length; index += 3) {
  20089. var v1Out;
  20090. var v2Out;
  20091. var v3Out;
  20092. var total = 0;
  20093. var nV1, nV2, nV3, nV4;
  20094. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20095. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20096. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20097. v1Out = d1 > 0;
  20098. v2Out = d2 > 0;
  20099. v3Out = d3 > 0;
  20100. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20101. switch (total) {
  20102. case 0:
  20103. result.push(vertices[index]);
  20104. result.push(vertices[index + 1]);
  20105. result.push(vertices[index + 2]);
  20106. break;
  20107. case 1:
  20108. if (v1Out) {
  20109. nV1 = vertices[index + 1];
  20110. nV2 = vertices[index + 2];
  20111. nV3 = clipVertices(vertices[index], nV1);
  20112. nV4 = clipVertices(vertices[index], nV2);
  20113. }
  20114. if (v2Out) {
  20115. nV1 = vertices[index];
  20116. nV2 = vertices[index + 2];
  20117. nV3 = clipVertices(vertices[index + 1], nV1);
  20118. nV4 = clipVertices(vertices[index + 1], nV2);
  20119. result.push(nV3);
  20120. result.push(nV2.clone());
  20121. result.push(nV1.clone());
  20122. result.push(nV2.clone());
  20123. result.push(nV3.clone());
  20124. result.push(nV4);
  20125. break;
  20126. }
  20127. if (v3Out) {
  20128. nV1 = vertices[index];
  20129. nV2 = vertices[index + 1];
  20130. nV3 = clipVertices(vertices[index + 2], nV1);
  20131. nV4 = clipVertices(vertices[index + 2], nV2);
  20132. }
  20133. result.push(nV1.clone());
  20134. result.push(nV2.clone());
  20135. result.push(nV3);
  20136. result.push(nV4);
  20137. result.push(nV3.clone());
  20138. result.push(nV2.clone());
  20139. break;
  20140. case 2:
  20141. if (!v1Out) {
  20142. nV1 = vertices[index].clone();
  20143. nV2 = clipVertices(nV1, vertices[index + 1]);
  20144. nV3 = clipVertices(nV1, vertices[index + 2]);
  20145. result.push(nV1);
  20146. result.push(nV2);
  20147. result.push(nV3);
  20148. }
  20149. if (!v2Out) {
  20150. nV1 = vertices[index + 1].clone();
  20151. nV2 = clipVertices(nV1, vertices[index + 2]);
  20152. nV3 = clipVertices(nV1, vertices[index]);
  20153. result.push(nV1);
  20154. result.push(nV2);
  20155. result.push(nV3);
  20156. }
  20157. if (!v3Out) {
  20158. nV1 = vertices[index + 2].clone();
  20159. nV2 = clipVertices(nV1, vertices[index]);
  20160. nV3 = clipVertices(nV1, vertices[index + 1]);
  20161. result.push(nV1);
  20162. result.push(nV2);
  20163. result.push(nV3);
  20164. }
  20165. break;
  20166. case 3:
  20167. break;
  20168. }
  20169. }
  20170. return result;
  20171. };
  20172. for (var index = 0; index < indices.length; index += 3) {
  20173. var faceVertices = new Array();
  20174. faceVertices.push(extractDecalVector3(index));
  20175. faceVertices.push(extractDecalVector3(index + 1));
  20176. faceVertices.push(extractDecalVector3(index + 2));
  20177. // Clip
  20178. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20179. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20180. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20181. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20182. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20183. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20184. if (faceVertices.length === 0) {
  20185. continue;
  20186. }
  20187. // Add UVs and get back to world
  20188. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20189. var vertex = faceVertices[vIndex];
  20190. //TODO check for Int32Array
  20191. vertexData.indices.push(currentVertexDataIndex);
  20192. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20193. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20194. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20195. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20196. currentVertexDataIndex++;
  20197. }
  20198. }
  20199. // Return mesh
  20200. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20201. vertexData.applyToMesh(decal);
  20202. decal.position = position.clone();
  20203. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20204. return decal;
  20205. };
  20206. // Privates
  20207. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20208. // extrusion geometry
  20209. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20210. var tangents = path3D.getTangents();
  20211. var normals = path3D.getNormals();
  20212. var binormals = path3D.getBinormals();
  20213. var distances = path3D.getDistances();
  20214. var angle = 0;
  20215. var returnScale = function () { return scale; };
  20216. var returnRotation = function () { return rotation; };
  20217. var rotate = custom ? rotateFunction : returnRotation;
  20218. var scl = custom ? scaleFunction : returnScale;
  20219. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20220. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20221. for (var i = 0; i < curve.length; i++) {
  20222. var shapePath = new Array();
  20223. var angleStep = rotate(i, distances[i]);
  20224. var scaleRatio = scl(i, distances[i]);
  20225. for (var p = 0; p < shape.length; p++) {
  20226. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20227. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20228. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20229. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20230. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20231. shapePath[p] = rotated;
  20232. }
  20233. shapePaths[index] = shapePath;
  20234. angle += angleStep;
  20235. index++;
  20236. }
  20237. // cap
  20238. var capPath = function (shapePath) {
  20239. var pointCap = Array();
  20240. var barycenter = BABYLON.Vector3.Zero();
  20241. var i;
  20242. for (i = 0; i < shapePath.length; i++) {
  20243. barycenter.addInPlace(shapePath[i]);
  20244. }
  20245. barycenter.scaleInPlace(1 / shapePath.length);
  20246. for (i = 0; i < shapePath.length; i++) {
  20247. pointCap.push(barycenter);
  20248. }
  20249. return pointCap;
  20250. };
  20251. switch (cap) {
  20252. case BABYLON.Mesh.NO_CAP:
  20253. break;
  20254. case BABYLON.Mesh.CAP_START:
  20255. shapePaths[0] = capPath(shapePaths[2]);
  20256. shapePaths[1] = shapePaths[2].slice(0);
  20257. break;
  20258. case BABYLON.Mesh.CAP_END:
  20259. shapePaths[index] = shapePaths[index - 1];
  20260. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20261. break;
  20262. case BABYLON.Mesh.CAP_ALL:
  20263. shapePaths[0] = capPath(shapePaths[2]);
  20264. shapePaths[1] = shapePaths[2].slice(0);
  20265. shapePaths[index] = shapePaths[index - 1];
  20266. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20267. break;
  20268. default:
  20269. break;
  20270. }
  20271. return shapePaths;
  20272. };
  20273. var path3D;
  20274. var pathArray;
  20275. if (instance) {
  20276. path3D = (instance.path3D).update(curve);
  20277. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20278. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20279. return instance;
  20280. }
  20281. // extruded shape creation
  20282. path3D = new BABYLON.Path3D(curve);
  20283. var newShapePaths = new Array();
  20284. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20285. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20286. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20287. extrudedGeneric.pathArray = pathArray;
  20288. extrudedGeneric.path3D = path3D;
  20289. extrudedGeneric.cap = cap;
  20290. return extrudedGeneric;
  20291. };
  20292. return MeshBuilder;
  20293. })();
  20294. BABYLON.MeshBuilder = MeshBuilder;
  20295. })(BABYLON || (BABYLON = {}));
  20296. var BABYLON;
  20297. (function (BABYLON) {
  20298. var BaseTexture = (function () {
  20299. function BaseTexture(scene) {
  20300. this.hasAlpha = false;
  20301. this.getAlphaFromRGB = false;
  20302. this.level = 1;
  20303. this.coordinatesIndex = 0;
  20304. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20305. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20306. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20307. this.anisotropicFilteringLevel = 4;
  20308. this.isCube = false;
  20309. this.isRenderTarget = false;
  20310. this.animations = new Array();
  20311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20312. this._scene = scene;
  20313. this._scene.textures.push(this);
  20314. }
  20315. BaseTexture.prototype.getScene = function () {
  20316. return this._scene;
  20317. };
  20318. BaseTexture.prototype.getTextureMatrix = function () {
  20319. return null;
  20320. };
  20321. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20322. return null;
  20323. };
  20324. BaseTexture.prototype.getInternalTexture = function () {
  20325. return this._texture;
  20326. };
  20327. BaseTexture.prototype.isReady = function () {
  20328. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20329. return true;
  20330. }
  20331. if (this._texture) {
  20332. return this._texture.isReady;
  20333. }
  20334. return false;
  20335. };
  20336. BaseTexture.prototype.getSize = function () {
  20337. if (this._texture._width) {
  20338. return { width: this._texture._width, height: this._texture._height };
  20339. }
  20340. if (this._texture._size) {
  20341. return { width: this._texture._size, height: this._texture._size };
  20342. }
  20343. return { width: 0, height: 0 };
  20344. };
  20345. BaseTexture.prototype.getBaseSize = function () {
  20346. if (!this.isReady() || !this._texture)
  20347. return { width: 0, height: 0 };
  20348. if (this._texture._size) {
  20349. return { width: this._texture._size, height: this._texture._size };
  20350. }
  20351. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20352. };
  20353. BaseTexture.prototype.scale = function (ratio) {
  20354. };
  20355. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20356. get: function () {
  20357. return false;
  20358. },
  20359. enumerable: true,
  20360. configurable: true
  20361. });
  20362. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20363. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20364. for (var index = 0; index < texturesCache.length; index++) {
  20365. var texturesCacheEntry = texturesCache[index];
  20366. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20367. texturesCache.splice(index, 1);
  20368. return;
  20369. }
  20370. }
  20371. };
  20372. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20373. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20374. for (var index = 0; index < texturesCache.length; index++) {
  20375. var texturesCacheEntry = texturesCache[index];
  20376. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20377. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20378. texturesCacheEntry.references++;
  20379. return texturesCacheEntry;
  20380. }
  20381. }
  20382. }
  20383. return null;
  20384. };
  20385. BaseTexture.prototype.delayLoad = function () {
  20386. };
  20387. BaseTexture.prototype.clone = function () {
  20388. return null;
  20389. };
  20390. BaseTexture.prototype.releaseInternalTexture = function () {
  20391. if (this._texture) {
  20392. this._scene.getEngine().releaseInternalTexture(this._texture);
  20393. delete this._texture;
  20394. }
  20395. };
  20396. BaseTexture.prototype.dispose = function () {
  20397. // Animations
  20398. this.getScene().stopAnimation(this);
  20399. // Remove from scene
  20400. var index = this._scene.textures.indexOf(this);
  20401. if (index >= 0) {
  20402. this._scene.textures.splice(index, 1);
  20403. }
  20404. if (this._texture === undefined) {
  20405. return;
  20406. }
  20407. // Release
  20408. this.releaseInternalTexture();
  20409. // Callback
  20410. if (this.onDispose) {
  20411. this.onDispose();
  20412. }
  20413. };
  20414. BaseTexture.prototype.serialize = function () {
  20415. if (!this.name) {
  20416. return null;
  20417. }
  20418. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20419. // Animations
  20420. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20421. return serializationObject;
  20422. };
  20423. __decorate([
  20424. BABYLON.serialize()
  20425. ], BaseTexture.prototype, "name", void 0);
  20426. __decorate([
  20427. BABYLON.serialize()
  20428. ], BaseTexture.prototype, "hasAlpha", void 0);
  20429. __decorate([
  20430. BABYLON.serialize()
  20431. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20432. __decorate([
  20433. BABYLON.serialize()
  20434. ], BaseTexture.prototype, "level", void 0);
  20435. __decorate([
  20436. BABYLON.serialize()
  20437. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20438. __decorate([
  20439. BABYLON.serialize()
  20440. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20441. __decorate([
  20442. BABYLON.serialize()
  20443. ], BaseTexture.prototype, "wrapU", void 0);
  20444. __decorate([
  20445. BABYLON.serialize()
  20446. ], BaseTexture.prototype, "wrapV", void 0);
  20447. __decorate([
  20448. BABYLON.serialize()
  20449. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20450. __decorate([
  20451. BABYLON.serialize()
  20452. ], BaseTexture.prototype, "isCube", void 0);
  20453. __decorate([
  20454. BABYLON.serialize()
  20455. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20456. return BaseTexture;
  20457. })();
  20458. BABYLON.BaseTexture = BaseTexture;
  20459. })(BABYLON || (BABYLON = {}));
  20460. var BABYLON;
  20461. (function (BABYLON) {
  20462. var Texture = (function (_super) {
  20463. __extends(Texture, _super);
  20464. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20465. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20466. if (onLoad === void 0) { onLoad = null; }
  20467. if (onError === void 0) { onError = null; }
  20468. if (buffer === void 0) { buffer = null; }
  20469. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20470. _super.call(this, scene);
  20471. this.uOffset = 0;
  20472. this.vOffset = 0;
  20473. this.uScale = 1.0;
  20474. this.vScale = 1.0;
  20475. this.uAng = 0;
  20476. this.vAng = 0;
  20477. this.wAng = 0;
  20478. this.name = url;
  20479. this.url = url;
  20480. this._noMipmap = noMipmap;
  20481. this._invertY = invertY;
  20482. this._samplingMode = samplingMode;
  20483. this._buffer = buffer;
  20484. this._deleteBuffer = deleteBuffer;
  20485. if (!url) {
  20486. return;
  20487. }
  20488. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20489. if (!this._texture) {
  20490. if (!scene.useDelayedTextureLoading) {
  20491. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20492. if (deleteBuffer) {
  20493. delete this._buffer;
  20494. }
  20495. }
  20496. else {
  20497. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20498. this._delayedOnLoad = onLoad;
  20499. this._delayedOnError = onError;
  20500. }
  20501. }
  20502. else {
  20503. BABYLON.Tools.SetImmediate(function () {
  20504. if (onLoad) {
  20505. onLoad();
  20506. }
  20507. });
  20508. }
  20509. }
  20510. Texture.prototype.delayLoad = function () {
  20511. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20512. return;
  20513. }
  20514. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20515. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20516. if (!this._texture) {
  20517. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20518. if (this._deleteBuffer) {
  20519. delete this._buffer;
  20520. }
  20521. }
  20522. };
  20523. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20524. if (!this._texture) {
  20525. return;
  20526. }
  20527. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20528. };
  20529. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20530. x *= this.uScale;
  20531. y *= this.vScale;
  20532. x -= 0.5 * this.uScale;
  20533. y -= 0.5 * this.vScale;
  20534. z -= 0.5;
  20535. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20536. t.x += 0.5 * this.uScale + this.uOffset;
  20537. t.y += 0.5 * this.vScale + this.vOffset;
  20538. t.z += 0.5;
  20539. };
  20540. Texture.prototype.getTextureMatrix = function () {
  20541. if (this.uOffset === this._cachedUOffset &&
  20542. this.vOffset === this._cachedVOffset &&
  20543. this.uScale === this._cachedUScale &&
  20544. this.vScale === this._cachedVScale &&
  20545. this.uAng === this._cachedUAng &&
  20546. this.vAng === this._cachedVAng &&
  20547. this.wAng === this._cachedWAng) {
  20548. return this._cachedTextureMatrix;
  20549. }
  20550. this._cachedUOffset = this.uOffset;
  20551. this._cachedVOffset = this.vOffset;
  20552. this._cachedUScale = this.uScale;
  20553. this._cachedVScale = this.vScale;
  20554. this._cachedUAng = this.uAng;
  20555. this._cachedVAng = this.vAng;
  20556. this._cachedWAng = this.wAng;
  20557. if (!this._cachedTextureMatrix) {
  20558. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20559. this._rowGenerationMatrix = new BABYLON.Matrix();
  20560. this._t0 = BABYLON.Vector3.Zero();
  20561. this._t1 = BABYLON.Vector3.Zero();
  20562. this._t2 = BABYLON.Vector3.Zero();
  20563. }
  20564. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20565. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20566. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20567. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20568. this._t1.subtractInPlace(this._t0);
  20569. this._t2.subtractInPlace(this._t0);
  20570. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20571. this._cachedTextureMatrix.m[0] = this._t1.x;
  20572. this._cachedTextureMatrix.m[1] = this._t1.y;
  20573. this._cachedTextureMatrix.m[2] = this._t1.z;
  20574. this._cachedTextureMatrix.m[4] = this._t2.x;
  20575. this._cachedTextureMatrix.m[5] = this._t2.y;
  20576. this._cachedTextureMatrix.m[6] = this._t2.z;
  20577. this._cachedTextureMatrix.m[8] = this._t0.x;
  20578. this._cachedTextureMatrix.m[9] = this._t0.y;
  20579. this._cachedTextureMatrix.m[10] = this._t0.z;
  20580. return this._cachedTextureMatrix;
  20581. };
  20582. Texture.prototype.getReflectionTextureMatrix = function () {
  20583. if (this.uOffset === this._cachedUOffset &&
  20584. this.vOffset === this._cachedVOffset &&
  20585. this.uScale === this._cachedUScale &&
  20586. this.vScale === this._cachedVScale &&
  20587. this.coordinatesMode === this._cachedCoordinatesMode) {
  20588. return this._cachedTextureMatrix;
  20589. }
  20590. if (!this._cachedTextureMatrix) {
  20591. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20592. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20593. }
  20594. this._cachedCoordinatesMode = this.coordinatesMode;
  20595. switch (this.coordinatesMode) {
  20596. case Texture.PLANAR_MODE:
  20597. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20598. this._cachedTextureMatrix[0] = this.uScale;
  20599. this._cachedTextureMatrix[5] = this.vScale;
  20600. this._cachedTextureMatrix[12] = this.uOffset;
  20601. this._cachedTextureMatrix[13] = this.vOffset;
  20602. break;
  20603. case Texture.PROJECTION_MODE:
  20604. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20605. this._projectionModeMatrix.m[0] = 0.5;
  20606. this._projectionModeMatrix.m[5] = -0.5;
  20607. this._projectionModeMatrix.m[10] = 0.0;
  20608. this._projectionModeMatrix.m[12] = 0.5;
  20609. this._projectionModeMatrix.m[13] = 0.5;
  20610. this._projectionModeMatrix.m[14] = 1.0;
  20611. this._projectionModeMatrix.m[15] = 1.0;
  20612. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20613. break;
  20614. default:
  20615. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20616. break;
  20617. }
  20618. return this._cachedTextureMatrix;
  20619. };
  20620. Texture.prototype.clone = function () {
  20621. var _this = this;
  20622. return BABYLON.SerializationHelper.Clone(function () {
  20623. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20624. }, this);
  20625. };
  20626. // Statics
  20627. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20628. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20629. if (onLoad === void 0) { onLoad = null; }
  20630. if (onError === void 0) { onError = null; }
  20631. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20632. };
  20633. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20634. if (parsedTexture.isCube) {
  20635. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20636. }
  20637. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20638. return null;
  20639. }
  20640. var texture = BABYLON.SerializationHelper.Parse(function () {
  20641. if (parsedTexture.mirrorPlane) {
  20642. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20643. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20644. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20645. return mirrorTexture;
  20646. }
  20647. else if (parsedTexture.isRenderTarget) {
  20648. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20649. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20650. return renderTargetTexture;
  20651. }
  20652. else {
  20653. var texture;
  20654. if (parsedTexture.base64String) {
  20655. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20656. }
  20657. else {
  20658. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20659. }
  20660. return texture;
  20661. }
  20662. }, parsedTexture, scene);
  20663. // Animations
  20664. if (parsedTexture.animations) {
  20665. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20666. var parsedAnimation = parsedTexture.animations[animationIndex];
  20667. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20668. }
  20669. }
  20670. return texture;
  20671. };
  20672. // Constants
  20673. Texture.NEAREST_SAMPLINGMODE = 1;
  20674. Texture.BILINEAR_SAMPLINGMODE = 2;
  20675. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20676. Texture.EXPLICIT_MODE = 0;
  20677. Texture.SPHERICAL_MODE = 1;
  20678. Texture.PLANAR_MODE = 2;
  20679. Texture.CUBIC_MODE = 3;
  20680. Texture.PROJECTION_MODE = 4;
  20681. Texture.SKYBOX_MODE = 5;
  20682. Texture.INVCUBIC_MODE = 6;
  20683. Texture.EQUIRECTANGULAR_MODE = 7;
  20684. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20685. Texture.CLAMP_ADDRESSMODE = 0;
  20686. Texture.WRAP_ADDRESSMODE = 1;
  20687. Texture.MIRROR_ADDRESSMODE = 2;
  20688. __decorate([
  20689. BABYLON.serialize()
  20690. ], Texture.prototype, "url", void 0);
  20691. __decorate([
  20692. BABYLON.serialize()
  20693. ], Texture.prototype, "uOffset", void 0);
  20694. __decorate([
  20695. BABYLON.serialize()
  20696. ], Texture.prototype, "vOffset", void 0);
  20697. __decorate([
  20698. BABYLON.serialize()
  20699. ], Texture.prototype, "uScale", void 0);
  20700. __decorate([
  20701. BABYLON.serialize()
  20702. ], Texture.prototype, "vScale", void 0);
  20703. __decorate([
  20704. BABYLON.serialize()
  20705. ], Texture.prototype, "uAng", void 0);
  20706. __decorate([
  20707. BABYLON.serialize()
  20708. ], Texture.prototype, "vAng", void 0);
  20709. __decorate([
  20710. BABYLON.serialize()
  20711. ], Texture.prototype, "wAng", void 0);
  20712. return Texture;
  20713. })(BABYLON.BaseTexture);
  20714. BABYLON.Texture = Texture;
  20715. })(BABYLON || (BABYLON = {}));
  20716. var BABYLON;
  20717. (function (BABYLON) {
  20718. var CubeTexture = (function (_super) {
  20719. __extends(CubeTexture, _super);
  20720. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20721. _super.call(this, scene);
  20722. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20723. this.name = rootUrl;
  20724. this.url = rootUrl;
  20725. this._noMipmap = noMipmap;
  20726. this.hasAlpha = false;
  20727. if (!rootUrl && !files) {
  20728. return;
  20729. }
  20730. this._texture = this._getFromCache(rootUrl, noMipmap);
  20731. if (!files) {
  20732. if (!extensions) {
  20733. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20734. }
  20735. files = [];
  20736. for (var index = 0; index < extensions.length; index++) {
  20737. files.push(rootUrl + extensions[index]);
  20738. }
  20739. this._extensions = extensions;
  20740. }
  20741. this._files = files;
  20742. if (!this._texture) {
  20743. if (!scene.useDelayedTextureLoading) {
  20744. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20745. }
  20746. else {
  20747. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20748. }
  20749. }
  20750. this.isCube = true;
  20751. this._textureMatrix = BABYLON.Matrix.Identity();
  20752. }
  20753. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20754. return new CubeTexture("", scene, null, noMipmap, files);
  20755. };
  20756. // Methods
  20757. CubeTexture.prototype.delayLoad = function () {
  20758. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20759. return;
  20760. }
  20761. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20762. this._texture = this._getFromCache(this.url, this._noMipmap);
  20763. if (!this._texture) {
  20764. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20765. }
  20766. };
  20767. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20768. return this._textureMatrix;
  20769. };
  20770. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20771. var texture = BABYLON.SerializationHelper.Parse(function () {
  20772. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20773. }, parsedTexture, scene);
  20774. // Animations
  20775. if (parsedTexture.animations) {
  20776. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20777. var parsedAnimation = parsedTexture.animations[animationIndex];
  20778. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20779. }
  20780. }
  20781. return texture;
  20782. };
  20783. CubeTexture.prototype.clone = function () {
  20784. var _this = this;
  20785. return BABYLON.SerializationHelper.Clone(function () {
  20786. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20787. }, this);
  20788. };
  20789. return CubeTexture;
  20790. })(BABYLON.BaseTexture);
  20791. BABYLON.CubeTexture = CubeTexture;
  20792. })(BABYLON || (BABYLON = {}));
  20793. var BABYLON;
  20794. (function (BABYLON) {
  20795. var RenderTargetTexture = (function (_super) {
  20796. __extends(RenderTargetTexture, _super);
  20797. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20798. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20799. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20800. if (isCube === void 0) { isCube = false; }
  20801. _super.call(this, null, scene, !generateMipMaps);
  20802. this.isCube = isCube;
  20803. this.renderList = new Array();
  20804. this.renderParticles = true;
  20805. this.renderSprites = false;
  20806. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20807. this._currentRefreshId = -1;
  20808. this._refreshRate = 1;
  20809. this.name = name;
  20810. this.isRenderTarget = true;
  20811. this._size = size;
  20812. this._generateMipMaps = generateMipMaps;
  20813. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20814. if (isCube) {
  20815. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20816. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20817. this._textureMatrix = BABYLON.Matrix.Identity();
  20818. }
  20819. else {
  20820. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20821. }
  20822. // Rendering groups
  20823. this._renderingManager = new BABYLON.RenderingManager(scene);
  20824. }
  20825. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20826. get: function () {
  20827. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20828. },
  20829. enumerable: true,
  20830. configurable: true
  20831. });
  20832. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20833. get: function () {
  20834. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20835. },
  20836. enumerable: true,
  20837. configurable: true
  20838. });
  20839. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20840. get: function () {
  20841. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20842. },
  20843. enumerable: true,
  20844. configurable: true
  20845. });
  20846. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20847. this._currentRefreshId = -1;
  20848. };
  20849. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20850. get: function () {
  20851. return this._refreshRate;
  20852. },
  20853. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20854. set: function (value) {
  20855. this._refreshRate = value;
  20856. this.resetRefreshCounter();
  20857. },
  20858. enumerable: true,
  20859. configurable: true
  20860. });
  20861. RenderTargetTexture.prototype._shouldRender = function () {
  20862. if (this._currentRefreshId === -1) {
  20863. this._currentRefreshId = 1;
  20864. return true;
  20865. }
  20866. if (this.refreshRate === this._currentRefreshId) {
  20867. this._currentRefreshId = 1;
  20868. return true;
  20869. }
  20870. this._currentRefreshId++;
  20871. return false;
  20872. };
  20873. RenderTargetTexture.prototype.isReady = function () {
  20874. if (!this.getScene().renderTargetsEnabled) {
  20875. return false;
  20876. }
  20877. return _super.prototype.isReady.call(this);
  20878. };
  20879. RenderTargetTexture.prototype.getRenderSize = function () {
  20880. return this._size;
  20881. };
  20882. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20883. get: function () {
  20884. return true;
  20885. },
  20886. enumerable: true,
  20887. configurable: true
  20888. });
  20889. RenderTargetTexture.prototype.scale = function (ratio) {
  20890. var newSize = this._size * ratio;
  20891. this.resize(newSize, this._generateMipMaps);
  20892. };
  20893. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20894. if (this.isCube) {
  20895. return this._textureMatrix;
  20896. }
  20897. return _super.prototype.getReflectionTextureMatrix.call(this);
  20898. };
  20899. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20900. this.releaseInternalTexture();
  20901. if (this.isCube) {
  20902. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20903. }
  20904. else {
  20905. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20906. }
  20907. };
  20908. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20909. var scene = this.getScene();
  20910. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20911. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20912. }
  20913. if (this._waitingRenderList) {
  20914. this.renderList = [];
  20915. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20916. var id = this._waitingRenderList[index];
  20917. this.renderList.push(scene.getMeshByID(id));
  20918. }
  20919. delete this._waitingRenderList;
  20920. }
  20921. if (this.renderList && this.renderList.length === 0) {
  20922. return;
  20923. }
  20924. // Prepare renderingManager
  20925. this._renderingManager.reset();
  20926. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20927. var sceneRenderId = scene.getRenderId();
  20928. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20929. var mesh = currentRenderList[meshIndex];
  20930. if (mesh) {
  20931. if (!mesh.isReady()) {
  20932. // Reset _currentRefreshId
  20933. this.resetRefreshCounter();
  20934. continue;
  20935. }
  20936. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20937. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20938. mesh._activate(sceneRenderId);
  20939. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20940. var subMesh = mesh.subMeshes[subIndex];
  20941. scene._activeIndices += subMesh.indexCount;
  20942. this._renderingManager.dispatch(subMesh);
  20943. }
  20944. }
  20945. }
  20946. }
  20947. if (this.isCube) {
  20948. for (var face = 0; face < 6; face++) {
  20949. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20950. scene.incrementRenderId();
  20951. scene.resetCachedMaterial();
  20952. }
  20953. }
  20954. else {
  20955. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20956. }
  20957. if (this.onAfterUnbind) {
  20958. this.onAfterUnbind();
  20959. }
  20960. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20961. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20962. }
  20963. scene.resetCachedMaterial();
  20964. };
  20965. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20966. var scene = this.getScene();
  20967. var engine = scene.getEngine();
  20968. // Bind
  20969. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20970. if (this.isCube) {
  20971. engine.bindFramebuffer(this._texture, faceIndex);
  20972. }
  20973. else {
  20974. engine.bindFramebuffer(this._texture);
  20975. }
  20976. }
  20977. if (this.onBeforeRender) {
  20978. this.onBeforeRender(faceIndex);
  20979. }
  20980. // Clear
  20981. if (this.onClear) {
  20982. this.onClear(engine);
  20983. }
  20984. else {
  20985. engine.clear(scene.clearColor, true, true);
  20986. }
  20987. if (!this._doNotChangeAspectRatio) {
  20988. scene.updateTransformMatrix(true);
  20989. }
  20990. // Render
  20991. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20992. if (useCameraPostProcess) {
  20993. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20994. }
  20995. if (!this._doNotChangeAspectRatio) {
  20996. scene.updateTransformMatrix(true);
  20997. }
  20998. if (this.onAfterRender) {
  20999. this.onAfterRender(faceIndex);
  21000. }
  21001. // Dump ?
  21002. if (dumpForDebug) {
  21003. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  21004. }
  21005. // Unbind
  21006. if (!this.isCube || faceIndex === 5) {
  21007. if (this.isCube) {
  21008. if (faceIndex === 5) {
  21009. engine.generateMipMapsForCubemap(this._texture);
  21010. }
  21011. }
  21012. engine.unBindFramebuffer(this._texture, this.isCube);
  21013. }
  21014. };
  21015. RenderTargetTexture.prototype.clone = function () {
  21016. var textureSize = this.getSize();
  21017. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21018. // Base texture
  21019. newTexture.hasAlpha = this.hasAlpha;
  21020. newTexture.level = this.level;
  21021. // RenderTarget Texture
  21022. newTexture.coordinatesMode = this.coordinatesMode;
  21023. newTexture.renderList = this.renderList.slice(0);
  21024. return newTexture;
  21025. };
  21026. RenderTargetTexture.prototype.serialize = function () {
  21027. if (!this.name) {
  21028. return null;
  21029. }
  21030. var serializationObject = _super.prototype.serialize.call(this);
  21031. serializationObject.renderTargetSize = this.getRenderSize();
  21032. serializationObject.renderList = [];
  21033. for (var index = 0; index < this.renderList.length; index++) {
  21034. serializationObject.renderList.push(this.renderList[index].id);
  21035. }
  21036. return serializationObject;
  21037. };
  21038. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21039. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21040. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21041. return RenderTargetTexture;
  21042. })(BABYLON.Texture);
  21043. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21044. })(BABYLON || (BABYLON = {}));
  21045. var BABYLON;
  21046. (function (BABYLON) {
  21047. var ProceduralTexture = (function (_super) {
  21048. __extends(ProceduralTexture, _super);
  21049. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21050. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21051. if (isCube === void 0) { isCube = false; }
  21052. _super.call(this, null, scene, !generateMipMaps);
  21053. this.isCube = isCube;
  21054. this.isEnabled = true;
  21055. this._currentRefreshId = -1;
  21056. this._refreshRate = 1;
  21057. this._vertexDeclaration = [2];
  21058. this._vertexStrideSize = 2 * 4;
  21059. this._uniforms = new Array();
  21060. this._samplers = new Array();
  21061. this._textures = new Array();
  21062. this._floats = new Array();
  21063. this._floatsArrays = {};
  21064. this._colors3 = new Array();
  21065. this._colors4 = new Array();
  21066. this._vectors2 = new Array();
  21067. this._vectors3 = new Array();
  21068. this._matrices = new Array();
  21069. this._fallbackTextureUsed = false;
  21070. scene._proceduralTextures.push(this);
  21071. this.name = name;
  21072. this.isRenderTarget = true;
  21073. this._size = size;
  21074. this._generateMipMaps = generateMipMaps;
  21075. this.setFragment(fragment);
  21076. this._fallbackTexture = fallbackTexture;
  21077. if (isCube) {
  21078. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21079. this.setFloat("face", 0);
  21080. }
  21081. else {
  21082. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  21083. }
  21084. // VBO
  21085. var vertices = [];
  21086. vertices.push(1, 1);
  21087. vertices.push(-1, 1);
  21088. vertices.push(-1, -1);
  21089. vertices.push(1, -1);
  21090. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21091. // Indices
  21092. var indices = [];
  21093. indices.push(0);
  21094. indices.push(1);
  21095. indices.push(2);
  21096. indices.push(0);
  21097. indices.push(2);
  21098. indices.push(3);
  21099. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21100. }
  21101. ProceduralTexture.prototype.reset = function () {
  21102. if (this._effect === undefined) {
  21103. return;
  21104. }
  21105. var engine = this.getScene().getEngine();
  21106. engine._releaseEffect(this._effect);
  21107. };
  21108. ProceduralTexture.prototype.isReady = function () {
  21109. var _this = this;
  21110. var engine = this.getScene().getEngine();
  21111. var shaders;
  21112. if (!this._fragment) {
  21113. return false;
  21114. }
  21115. if (this._fallbackTextureUsed) {
  21116. return true;
  21117. }
  21118. if (this._fragment.fragmentElement !== undefined) {
  21119. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21120. }
  21121. else {
  21122. shaders = { vertex: "procedural", fragment: this._fragment };
  21123. }
  21124. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  21125. _this.releaseInternalTexture();
  21126. if (_this._fallbackTexture) {
  21127. _this._texture = _this._fallbackTexture._texture;
  21128. _this._texture.references++;
  21129. }
  21130. _this._fallbackTextureUsed = true;
  21131. });
  21132. return this._effect.isReady();
  21133. };
  21134. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21135. this._currentRefreshId = -1;
  21136. };
  21137. ProceduralTexture.prototype.setFragment = function (fragment) {
  21138. this._fragment = fragment;
  21139. };
  21140. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21141. get: function () {
  21142. return this._refreshRate;
  21143. },
  21144. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21145. set: function (value) {
  21146. this._refreshRate = value;
  21147. this.resetRefreshCounter();
  21148. },
  21149. enumerable: true,
  21150. configurable: true
  21151. });
  21152. ProceduralTexture.prototype._shouldRender = function () {
  21153. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21154. return false;
  21155. }
  21156. if (this._fallbackTextureUsed) {
  21157. return false;
  21158. }
  21159. if (this._currentRefreshId === -1) {
  21160. this._currentRefreshId = 1;
  21161. return true;
  21162. }
  21163. if (this.refreshRate === this._currentRefreshId) {
  21164. this._currentRefreshId = 1;
  21165. return true;
  21166. }
  21167. this._currentRefreshId++;
  21168. return false;
  21169. };
  21170. ProceduralTexture.prototype.getRenderSize = function () {
  21171. return this._size;
  21172. };
  21173. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21174. if (this._fallbackTextureUsed) {
  21175. return;
  21176. }
  21177. this.releaseInternalTexture();
  21178. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21179. };
  21180. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21181. if (this._uniforms.indexOf(uniformName) === -1) {
  21182. this._uniforms.push(uniformName);
  21183. }
  21184. };
  21185. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21186. if (this._samplers.indexOf(name) === -1) {
  21187. this._samplers.push(name);
  21188. }
  21189. this._textures[name] = texture;
  21190. return this;
  21191. };
  21192. ProceduralTexture.prototype.setFloat = function (name, value) {
  21193. this._checkUniform(name);
  21194. this._floats[name] = value;
  21195. return this;
  21196. };
  21197. ProceduralTexture.prototype.setFloats = function (name, value) {
  21198. this._checkUniform(name);
  21199. this._floatsArrays[name] = value;
  21200. return this;
  21201. };
  21202. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21203. this._checkUniform(name);
  21204. this._colors3[name] = value;
  21205. return this;
  21206. };
  21207. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21208. this._checkUniform(name);
  21209. this._colors4[name] = value;
  21210. return this;
  21211. };
  21212. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21213. this._checkUniform(name);
  21214. this._vectors2[name] = value;
  21215. return this;
  21216. };
  21217. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21218. this._checkUniform(name);
  21219. this._vectors3[name] = value;
  21220. return this;
  21221. };
  21222. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21223. this._checkUniform(name);
  21224. this._matrices[name] = value;
  21225. return this;
  21226. };
  21227. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21228. var scene = this.getScene();
  21229. var engine = scene.getEngine();
  21230. // Render
  21231. engine.enableEffect(this._effect);
  21232. engine.setState(false);
  21233. // Texture
  21234. for (var name in this._textures) {
  21235. this._effect.setTexture(name, this._textures[name]);
  21236. }
  21237. // Float
  21238. for (name in this._floats) {
  21239. this._effect.setFloat(name, this._floats[name]);
  21240. }
  21241. // Floats
  21242. for (name in this._floatsArrays) {
  21243. this._effect.setArray(name, this._floatsArrays[name]);
  21244. }
  21245. // Color3
  21246. for (name in this._colors3) {
  21247. this._effect.setColor3(name, this._colors3[name]);
  21248. }
  21249. // Color4
  21250. for (name in this._colors4) {
  21251. var color = this._colors4[name];
  21252. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21253. }
  21254. // Vector2
  21255. for (name in this._vectors2) {
  21256. this._effect.setVector2(name, this._vectors2[name]);
  21257. }
  21258. // Vector3
  21259. for (name in this._vectors3) {
  21260. this._effect.setVector3(name, this._vectors3[name]);
  21261. }
  21262. // Matrix
  21263. for (name in this._matrices) {
  21264. this._effect.setMatrix(name, this._matrices[name]);
  21265. }
  21266. // VBOs
  21267. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21268. if (this.isCube) {
  21269. for (var face = 0; face < 6; face++) {
  21270. engine.bindFramebuffer(this._texture, face);
  21271. this._effect.setFloat("face", face);
  21272. // Clear
  21273. engine.clear(scene.clearColor, true, true);
  21274. // Draw order
  21275. engine.draw(true, 0, 6);
  21276. // Mipmaps
  21277. if (face === 5) {
  21278. engine.generateMipMapsForCubemap(this._texture);
  21279. }
  21280. }
  21281. }
  21282. else {
  21283. engine.bindFramebuffer(this._texture);
  21284. // Clear
  21285. engine.clear(scene.clearColor, true, true);
  21286. // Draw order
  21287. engine.draw(true, 0, 6);
  21288. }
  21289. // Unbind
  21290. engine.unBindFramebuffer(this._texture, this.isCube);
  21291. if (this.onGenerated) {
  21292. this.onGenerated();
  21293. }
  21294. };
  21295. ProceduralTexture.prototype.clone = function () {
  21296. var textureSize = this.getSize();
  21297. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21298. // Base texture
  21299. newTexture.hasAlpha = this.hasAlpha;
  21300. newTexture.level = this.level;
  21301. // RenderTarget Texture
  21302. newTexture.coordinatesMode = this.coordinatesMode;
  21303. return newTexture;
  21304. };
  21305. ProceduralTexture.prototype.dispose = function () {
  21306. var index = this.getScene()._proceduralTextures.indexOf(this);
  21307. if (index >= 0) {
  21308. this.getScene()._proceduralTextures.splice(index, 1);
  21309. }
  21310. _super.prototype.dispose.call(this);
  21311. };
  21312. return ProceduralTexture;
  21313. })(BABYLON.Texture);
  21314. BABYLON.ProceduralTexture = ProceduralTexture;
  21315. })(BABYLON || (BABYLON = {}));
  21316. var BABYLON;
  21317. (function (BABYLON) {
  21318. var MirrorTexture = (function (_super) {
  21319. __extends(MirrorTexture, _super);
  21320. function MirrorTexture(name, size, scene, generateMipMaps) {
  21321. var _this = this;
  21322. _super.call(this, name, size, scene, generateMipMaps, true);
  21323. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21324. this._transformMatrix = BABYLON.Matrix.Zero();
  21325. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21326. this.onBeforeRender = function () {
  21327. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21328. _this._savedViewMatrix = scene.getViewMatrix();
  21329. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21330. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21331. scene.clipPlane = _this.mirrorPlane;
  21332. scene.getEngine().cullBackFaces = false;
  21333. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21334. };
  21335. this.onAfterRender = function () {
  21336. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21337. scene.getEngine().cullBackFaces = true;
  21338. scene._mirroredCameraPosition = null;
  21339. delete scene.clipPlane;
  21340. };
  21341. }
  21342. MirrorTexture.prototype.clone = function () {
  21343. var textureSize = this.getSize();
  21344. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21345. // Base texture
  21346. newTexture.hasAlpha = this.hasAlpha;
  21347. newTexture.level = this.level;
  21348. // Mirror Texture
  21349. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21350. newTexture.renderList = this.renderList.slice(0);
  21351. return newTexture;
  21352. };
  21353. MirrorTexture.prototype.serialize = function () {
  21354. if (!this.name) {
  21355. return null;
  21356. }
  21357. var serializationObject = _super.prototype.serialize.call(this);
  21358. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21359. return serializationObject;
  21360. };
  21361. return MirrorTexture;
  21362. })(BABYLON.RenderTargetTexture);
  21363. BABYLON.MirrorTexture = MirrorTexture;
  21364. })(BABYLON || (BABYLON = {}));
  21365. var BABYLON;
  21366. (function (BABYLON) {
  21367. /**
  21368. * Creates a refraction texture used by refraction channel of the standard material.
  21369. * @param name the texture name
  21370. * @param size size of the underlying texture
  21371. * @param scene root scene
  21372. */
  21373. var RefractionTexture = (function (_super) {
  21374. __extends(RefractionTexture, _super);
  21375. function RefractionTexture(name, size, scene, generateMipMaps) {
  21376. var _this = this;
  21377. _super.call(this, name, size, scene, generateMipMaps, true);
  21378. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21379. this.depth = 2.0;
  21380. this.onBeforeRender = function () {
  21381. scene.clipPlane = _this.refractionPlane;
  21382. };
  21383. this.onAfterRender = function () {
  21384. delete scene.clipPlane;
  21385. };
  21386. }
  21387. RefractionTexture.prototype.clone = function () {
  21388. var textureSize = this.getSize();
  21389. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21390. // Base texture
  21391. newTexture.hasAlpha = this.hasAlpha;
  21392. newTexture.level = this.level;
  21393. // Refraction Texture
  21394. newTexture.refractionPlane = this.refractionPlane.clone();
  21395. newTexture.renderList = this.renderList.slice(0);
  21396. newTexture.depth = this.depth;
  21397. return newTexture;
  21398. };
  21399. RefractionTexture.prototype.serialize = function () {
  21400. if (!this.name) {
  21401. return null;
  21402. }
  21403. var serializationObject = _super.prototype.serialize.call(this);
  21404. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21405. serializationObject.depth = this.depth;
  21406. return serializationObject;
  21407. };
  21408. return RefractionTexture;
  21409. })(BABYLON.RenderTargetTexture);
  21410. BABYLON.RefractionTexture = RefractionTexture;
  21411. })(BABYLON || (BABYLON = {}));
  21412. var BABYLON;
  21413. (function (BABYLON) {
  21414. var DynamicTexture = (function (_super) {
  21415. __extends(DynamicTexture, _super);
  21416. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21418. _super.call(this, null, scene, !generateMipMaps);
  21419. this.name = name;
  21420. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21421. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21422. this._generateMipMaps = generateMipMaps;
  21423. if (options.getContext) {
  21424. this._canvas = options;
  21425. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21426. }
  21427. else {
  21428. this._canvas = document.createElement("canvas");
  21429. if (options.width) {
  21430. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21431. }
  21432. else {
  21433. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21434. }
  21435. }
  21436. var textureSize = this.getSize();
  21437. this._canvas.width = textureSize.width;
  21438. this._canvas.height = textureSize.height;
  21439. this._context = this._canvas.getContext("2d");
  21440. }
  21441. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21442. get: function () {
  21443. return true;
  21444. },
  21445. enumerable: true,
  21446. configurable: true
  21447. });
  21448. DynamicTexture.prototype.scale = function (ratio) {
  21449. var textureSize = this.getSize();
  21450. textureSize.width *= ratio;
  21451. textureSize.height *= ratio;
  21452. this._canvas.width = textureSize.width;
  21453. this._canvas.height = textureSize.height;
  21454. this.releaseInternalTexture();
  21455. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21456. };
  21457. DynamicTexture.prototype.getContext = function () {
  21458. return this._context;
  21459. };
  21460. DynamicTexture.prototype.clear = function () {
  21461. var size = this.getSize();
  21462. this._context.fillRect(0, 0, size.width, size.height);
  21463. };
  21464. DynamicTexture.prototype.update = function (invertY) {
  21465. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21466. };
  21467. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21468. if (update === void 0) { update = true; }
  21469. var size = this.getSize();
  21470. if (clearColor) {
  21471. this._context.fillStyle = clearColor;
  21472. this._context.fillRect(0, 0, size.width, size.height);
  21473. }
  21474. this._context.font = font;
  21475. if (x === null) {
  21476. var textSize = this._context.measureText(text);
  21477. x = (size.width - textSize.width) / 2;
  21478. }
  21479. this._context.fillStyle = color;
  21480. this._context.fillText(text, x, y);
  21481. if (update) {
  21482. this.update(invertY);
  21483. }
  21484. };
  21485. DynamicTexture.prototype.clone = function () {
  21486. var textureSize = this.getSize();
  21487. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21488. // Base texture
  21489. newTexture.hasAlpha = this.hasAlpha;
  21490. newTexture.level = this.level;
  21491. // Dynamic Texture
  21492. newTexture.wrapU = this.wrapU;
  21493. newTexture.wrapV = this.wrapV;
  21494. return newTexture;
  21495. };
  21496. return DynamicTexture;
  21497. })(BABYLON.Texture);
  21498. BABYLON.DynamicTexture = DynamicTexture;
  21499. })(BABYLON || (BABYLON = {}));
  21500. var BABYLON;
  21501. (function (BABYLON) {
  21502. var VideoTexture = (function (_super) {
  21503. __extends(VideoTexture, _super);
  21504. /**
  21505. * Creates a video texture.
  21506. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21507. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21508. * @param {BABYLON.Scene} scene is obviously the current scene.
  21509. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21510. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21511. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21512. */
  21513. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21514. var _this = this;
  21515. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21516. if (invertY === void 0) { invertY = false; }
  21517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21518. _super.call(this, null, scene, !generateMipMaps, invertY);
  21519. this._autoLaunch = true;
  21520. var urls;
  21521. this.name = name;
  21522. if (urlsOrVideo instanceof HTMLVideoElement) {
  21523. this.video = urlsOrVideo;
  21524. }
  21525. else {
  21526. urls = urlsOrVideo;
  21527. this.video = document.createElement("video");
  21528. this.video.autoplay = false;
  21529. this.video.loop = true;
  21530. }
  21531. this._generateMipMaps = generateMipMaps;
  21532. this._samplingMode = samplingMode;
  21533. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21534. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21535. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21536. }
  21537. else {
  21538. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21539. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21540. this._generateMipMaps = false;
  21541. }
  21542. if (urls) {
  21543. this.video.addEventListener("canplaythrough", function () {
  21544. _this._createTexture();
  21545. });
  21546. urls.forEach(function (url) {
  21547. var source = document.createElement("source");
  21548. source.src = url;
  21549. _this.video.appendChild(source);
  21550. });
  21551. }
  21552. else {
  21553. this._createTexture();
  21554. }
  21555. this._lastUpdate = BABYLON.Tools.Now;
  21556. }
  21557. VideoTexture.prototype._createTexture = function () {
  21558. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21559. this._texture.isReady = true;
  21560. };
  21561. VideoTexture.prototype.update = function () {
  21562. if (this._autoLaunch) {
  21563. this._autoLaunch = false;
  21564. this.video.play();
  21565. }
  21566. var now = BABYLON.Tools.Now;
  21567. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21568. return false;
  21569. }
  21570. this._lastUpdate = now;
  21571. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21572. return true;
  21573. };
  21574. return VideoTexture;
  21575. })(BABYLON.Texture);
  21576. BABYLON.VideoTexture = VideoTexture;
  21577. })(BABYLON || (BABYLON = {}));
  21578. var BABYLON;
  21579. (function (BABYLON) {
  21580. var CustomProceduralTexture = (function (_super) {
  21581. __extends(CustomProceduralTexture, _super);
  21582. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21583. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21584. this._animate = true;
  21585. this._time = 0;
  21586. this._texturePath = texturePath;
  21587. //Try to load json
  21588. this.loadJson(texturePath);
  21589. this.refreshRate = 1;
  21590. }
  21591. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21592. var _this = this;
  21593. var that = this;
  21594. function noConfigFile() {
  21595. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21596. try {
  21597. that.setFragment(that._texturePath);
  21598. }
  21599. catch (ex) {
  21600. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21601. }
  21602. }
  21603. var configFileUrl = jsonUrl + "/config.json";
  21604. var xhr = new XMLHttpRequest();
  21605. xhr.open("GET", configFileUrl, true);
  21606. xhr.addEventListener("load", function () {
  21607. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21608. try {
  21609. _this._config = JSON.parse(xhr.response);
  21610. _this.updateShaderUniforms();
  21611. _this.updateTextures();
  21612. _this.setFragment(_this._texturePath + "/custom");
  21613. _this._animate = _this._config.animate;
  21614. _this.refreshRate = _this._config.refreshrate;
  21615. }
  21616. catch (ex) {
  21617. noConfigFile();
  21618. }
  21619. }
  21620. else {
  21621. noConfigFile();
  21622. }
  21623. }, false);
  21624. xhr.addEventListener("error", function () {
  21625. noConfigFile();
  21626. }, false);
  21627. try {
  21628. xhr.send();
  21629. }
  21630. catch (ex) {
  21631. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21632. }
  21633. };
  21634. CustomProceduralTexture.prototype.isReady = function () {
  21635. if (!_super.prototype.isReady.call(this)) {
  21636. return false;
  21637. }
  21638. for (var name in this._textures) {
  21639. var texture = this._textures[name];
  21640. if (!texture.isReady()) {
  21641. return false;
  21642. }
  21643. }
  21644. return true;
  21645. };
  21646. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21647. if (this._animate) {
  21648. this._time += this.getScene().getAnimationRatio() * 0.03;
  21649. this.updateShaderUniforms();
  21650. }
  21651. _super.prototype.render.call(this, useCameraPostProcess);
  21652. };
  21653. CustomProceduralTexture.prototype.updateTextures = function () {
  21654. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21655. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21656. }
  21657. };
  21658. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21659. if (this._config) {
  21660. for (var j = 0; j < this._config.uniforms.length; j++) {
  21661. var uniform = this._config.uniforms[j];
  21662. switch (uniform.type) {
  21663. case "float":
  21664. this.setFloat(uniform.name, uniform.value);
  21665. break;
  21666. case "color3":
  21667. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21668. break;
  21669. case "color4":
  21670. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21671. break;
  21672. case "vector2":
  21673. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21674. break;
  21675. case "vector3":
  21676. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21677. break;
  21678. }
  21679. }
  21680. }
  21681. this.setFloat("time", this._time);
  21682. };
  21683. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21684. get: function () {
  21685. return this._animate;
  21686. },
  21687. set: function (value) {
  21688. this._animate = value;
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. return CustomProceduralTexture;
  21694. })(BABYLON.ProceduralTexture);
  21695. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21696. })(BABYLON || (BABYLON = {}));
  21697. var BABYLON;
  21698. (function (BABYLON) {
  21699. var EffectFallbacks = (function () {
  21700. function EffectFallbacks() {
  21701. this._defines = {};
  21702. this._currentRank = 32;
  21703. this._maxRank = -1;
  21704. }
  21705. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21706. if (!this._defines[rank]) {
  21707. if (rank < this._currentRank) {
  21708. this._currentRank = rank;
  21709. }
  21710. if (rank > this._maxRank) {
  21711. this._maxRank = rank;
  21712. }
  21713. this._defines[rank] = new Array();
  21714. }
  21715. this._defines[rank].push(define);
  21716. };
  21717. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21718. this._meshRank = rank;
  21719. this._mesh = mesh;
  21720. if (rank > this._maxRank) {
  21721. this._maxRank = rank;
  21722. }
  21723. };
  21724. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21725. get: function () {
  21726. return this._currentRank <= this._maxRank;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21732. var currentFallbacks = this._defines[this._currentRank];
  21733. for (var index = 0; index < currentFallbacks.length; index++) {
  21734. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21735. }
  21736. if (this._mesh && this._currentRank === this._meshRank) {
  21737. this._mesh.computeBonesUsingShaders = false;
  21738. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21739. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21740. }
  21741. this._currentRank++;
  21742. return currentDefines;
  21743. };
  21744. return EffectFallbacks;
  21745. })();
  21746. BABYLON.EffectFallbacks = EffectFallbacks;
  21747. var Effect = (function () {
  21748. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21749. var _this = this;
  21750. this._isReady = false;
  21751. this._compilationError = "";
  21752. this._valueCache = [];
  21753. this._engine = engine;
  21754. this.name = baseName;
  21755. this.defines = defines;
  21756. this._uniformsNames = uniformsNames.concat(samplers);
  21757. this._samplers = samplers;
  21758. this._attributesNames = attributesNames;
  21759. this.onError = onError;
  21760. this.onCompiled = onCompiled;
  21761. this._indexParameters = indexParameters;
  21762. var vertexSource;
  21763. var fragmentSource;
  21764. if (baseName.vertexElement) {
  21765. vertexSource = document.getElementById(baseName.vertexElement);
  21766. if (!vertexSource) {
  21767. vertexSource = baseName.vertexElement;
  21768. }
  21769. }
  21770. else {
  21771. vertexSource = baseName.vertex || baseName;
  21772. }
  21773. if (baseName.fragmentElement) {
  21774. fragmentSource = document.getElementById(baseName.fragmentElement);
  21775. if (!fragmentSource) {
  21776. fragmentSource = baseName.fragmentElement;
  21777. }
  21778. }
  21779. else {
  21780. fragmentSource = baseName.fragment || baseName;
  21781. }
  21782. this._loadVertexShader(vertexSource, function (vertexCode) {
  21783. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21784. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21785. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21786. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21787. });
  21788. });
  21789. });
  21790. });
  21791. }
  21792. // Properties
  21793. Effect.prototype.isReady = function () {
  21794. return this._isReady;
  21795. };
  21796. Effect.prototype.getProgram = function () {
  21797. return this._program;
  21798. };
  21799. Effect.prototype.getAttributesNames = function () {
  21800. return this._attributesNames;
  21801. };
  21802. Effect.prototype.getAttributeLocation = function (index) {
  21803. return this._attributes[index];
  21804. };
  21805. Effect.prototype.getAttributeLocationByName = function (name) {
  21806. var index = this._attributesNames.indexOf(name);
  21807. return this._attributes[index];
  21808. };
  21809. Effect.prototype.getAttributesCount = function () {
  21810. return this._attributes.length;
  21811. };
  21812. Effect.prototype.getUniformIndex = function (uniformName) {
  21813. return this._uniformsNames.indexOf(uniformName);
  21814. };
  21815. Effect.prototype.getUniform = function (uniformName) {
  21816. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21817. };
  21818. Effect.prototype.getSamplers = function () {
  21819. return this._samplers;
  21820. };
  21821. Effect.prototype.getCompilationError = function () {
  21822. return this._compilationError;
  21823. };
  21824. // Methods
  21825. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21826. // DOM element ?
  21827. if (vertex instanceof HTMLElement) {
  21828. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21829. callback(vertexCode);
  21830. return;
  21831. }
  21832. // Is in local store ?
  21833. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21834. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21835. return;
  21836. }
  21837. var vertexShaderUrl;
  21838. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21839. vertexShaderUrl = vertex;
  21840. }
  21841. else {
  21842. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21843. }
  21844. // Vertex shader
  21845. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21846. };
  21847. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21848. // DOM element ?
  21849. if (fragment instanceof HTMLElement) {
  21850. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21851. callback(fragmentCode);
  21852. return;
  21853. }
  21854. // Is in local store ?
  21855. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21856. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21857. return;
  21858. }
  21859. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21860. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21861. return;
  21862. }
  21863. var fragmentShaderUrl;
  21864. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21865. fragmentShaderUrl = fragment;
  21866. }
  21867. else {
  21868. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21869. }
  21870. // Fragment shader
  21871. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21872. };
  21873. Effect.prototype._dumpShadersName = function () {
  21874. if (this.name.vertexElement) {
  21875. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21876. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21877. }
  21878. else if (this.name.vertex) {
  21879. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21880. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21881. }
  21882. else {
  21883. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21884. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21885. }
  21886. };
  21887. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21888. var _this = this;
  21889. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21890. var match = regex.exec(sourceCode);
  21891. var returnValue = new String(sourceCode);
  21892. while (match != null) {
  21893. var includeFile = match[1];
  21894. if (Effect.IncludesShadersStore[includeFile]) {
  21895. // Substitution
  21896. var includeContent = Effect.IncludesShadersStore[includeFile];
  21897. if (match[2]) {
  21898. var splits = match[3].split(",");
  21899. for (var index = 0; index < splits.length; index += 2) {
  21900. var source = new RegExp(splits[index], "g");
  21901. var dest = splits[index + 1];
  21902. includeContent = includeContent.replace(source, dest);
  21903. }
  21904. }
  21905. if (match[4]) {
  21906. var indexString = match[5];
  21907. if (indexString.indexOf("..") !== -1) {
  21908. var indexSplits = indexString.split("..");
  21909. var minIndex = parseInt(indexSplits[0]);
  21910. var maxIndex = parseInt(indexSplits[1]);
  21911. var sourceIncludeContent = includeContent.slice(0);
  21912. includeContent = "";
  21913. if (isNaN(maxIndex)) {
  21914. maxIndex = this._indexParameters[indexSplits[1]];
  21915. }
  21916. for (var i = minIndex; i <= maxIndex; i++) {
  21917. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21918. }
  21919. }
  21920. else {
  21921. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21922. }
  21923. }
  21924. // Replace
  21925. returnValue = returnValue.replace(match[0], includeContent);
  21926. }
  21927. else {
  21928. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21929. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21930. Effect.IncludesShadersStore[includeFile] = fileContent;
  21931. _this._processIncludes(returnValue, callback);
  21932. });
  21933. return;
  21934. }
  21935. match = regex.exec(sourceCode);
  21936. }
  21937. callback(returnValue);
  21938. };
  21939. Effect.prototype._processPrecision = function (source) {
  21940. if (source.indexOf("precision highp float") === -1) {
  21941. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21942. source = "precision mediump float;\n" + source;
  21943. }
  21944. else {
  21945. source = "precision highp float;\n" + source;
  21946. }
  21947. }
  21948. else {
  21949. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21950. source = source.replace("precision highp float", "precision mediump float");
  21951. }
  21952. }
  21953. return source;
  21954. };
  21955. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21956. try {
  21957. var engine = this._engine;
  21958. // Precision
  21959. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21960. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21961. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21962. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21963. this._attributes = engine.getAttributes(this._program, attributesNames);
  21964. for (var index = 0; index < this._samplers.length; index++) {
  21965. var sampler = this.getUniform(this._samplers[index]);
  21966. if (sampler == null) {
  21967. this._samplers.splice(index, 1);
  21968. index--;
  21969. }
  21970. }
  21971. engine.bindSamplers(this);
  21972. this._isReady = true;
  21973. if (this.onCompiled) {
  21974. this.onCompiled(this);
  21975. }
  21976. }
  21977. catch (e) {
  21978. // Is it a problem with precision?
  21979. if (e.message.indexOf("highp") !== -1) {
  21980. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21981. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21982. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21983. return;
  21984. }
  21985. // Let's go through fallbacks then
  21986. if (fallbacks && fallbacks.isMoreFallbacks) {
  21987. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21988. this._dumpShadersName();
  21989. defines = fallbacks.reduce(defines);
  21990. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21991. }
  21992. else {
  21993. BABYLON.Tools.Error("Unable to compile effect: ");
  21994. this._dumpShadersName();
  21995. BABYLON.Tools.Error("Defines: " + defines);
  21996. BABYLON.Tools.Error("Error: " + e.message);
  21997. this._compilationError = e.message;
  21998. if (this.onError) {
  21999. this.onError(this, this._compilationError);
  22000. }
  22001. }
  22002. }
  22003. };
  22004. Object.defineProperty(Effect.prototype, "isSupported", {
  22005. get: function () {
  22006. return this._compilationError === "";
  22007. },
  22008. enumerable: true,
  22009. configurable: true
  22010. });
  22011. Effect.prototype._bindTexture = function (channel, texture) {
  22012. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22013. };
  22014. Effect.prototype.setTexture = function (channel, texture) {
  22015. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  22016. };
  22017. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22018. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22019. };
  22020. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22021. if (!this._valueCache[uniformName]) {
  22022. this._valueCache[uniformName] = new BABYLON.Matrix();
  22023. }
  22024. for (var index = 0; index < 16; index++) {
  22025. this._valueCache[uniformName].m[index] = matrix.m[index];
  22026. }
  22027. };
  22028. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22029. if (!this._valueCache[uniformName]) {
  22030. this._valueCache[uniformName] = [x, y];
  22031. return;
  22032. }
  22033. this._valueCache[uniformName][0] = x;
  22034. this._valueCache[uniformName][1] = y;
  22035. };
  22036. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22037. if (!this._valueCache[uniformName]) {
  22038. this._valueCache[uniformName] = [x, y, z];
  22039. return;
  22040. }
  22041. this._valueCache[uniformName][0] = x;
  22042. this._valueCache[uniformName][1] = y;
  22043. this._valueCache[uniformName][2] = z;
  22044. };
  22045. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22046. if (!this._valueCache[uniformName]) {
  22047. this._valueCache[uniformName] = [x, y, z, w];
  22048. return;
  22049. }
  22050. this._valueCache[uniformName][0] = x;
  22051. this._valueCache[uniformName][1] = y;
  22052. this._valueCache[uniformName][2] = z;
  22053. this._valueCache[uniformName][3] = w;
  22054. };
  22055. Effect.prototype.setArray = function (uniformName, array) {
  22056. this._engine.setArray(this.getUniform(uniformName), array);
  22057. return this;
  22058. };
  22059. Effect.prototype.setArray2 = function (uniformName, array) {
  22060. this._engine.setArray2(this.getUniform(uniformName), array);
  22061. return this;
  22062. };
  22063. Effect.prototype.setArray3 = function (uniformName, array) {
  22064. this._engine.setArray3(this.getUniform(uniformName), array);
  22065. return this;
  22066. };
  22067. Effect.prototype.setArray4 = function (uniformName, array) {
  22068. this._engine.setArray4(this.getUniform(uniformName), array);
  22069. return this;
  22070. };
  22071. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22072. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22073. return this;
  22074. };
  22075. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22076. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22077. // return this;
  22078. // this._cacheMatrix(uniformName, matrix);
  22079. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22080. return this;
  22081. };
  22082. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22083. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22084. return this;
  22085. };
  22086. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22087. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22088. return this;
  22089. };
  22090. Effect.prototype.setFloat = function (uniformName, value) {
  22091. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22092. return this;
  22093. this._valueCache[uniformName] = value;
  22094. this._engine.setFloat(this.getUniform(uniformName), value);
  22095. return this;
  22096. };
  22097. Effect.prototype.setBool = function (uniformName, bool) {
  22098. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22099. return this;
  22100. this._valueCache[uniformName] = bool;
  22101. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22102. return this;
  22103. };
  22104. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22105. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22106. return this;
  22107. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22108. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22109. return this;
  22110. };
  22111. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22112. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22113. return this;
  22114. this._cacheFloat2(uniformName, x, y);
  22115. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22116. return this;
  22117. };
  22118. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22119. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22120. return this;
  22121. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22122. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22123. return this;
  22124. };
  22125. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22126. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22127. return this;
  22128. this._cacheFloat3(uniformName, x, y, z);
  22129. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22130. return this;
  22131. };
  22132. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22133. 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)
  22134. return this;
  22135. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22136. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22137. return this;
  22138. };
  22139. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22140. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22141. return this;
  22142. this._cacheFloat4(uniformName, x, y, z, w);
  22143. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22144. return this;
  22145. };
  22146. Effect.prototype.setColor3 = function (uniformName, color3) {
  22147. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22148. return this;
  22149. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22150. this._engine.setColor3(this.getUniform(uniformName), color3);
  22151. return this;
  22152. };
  22153. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22154. 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)
  22155. return this;
  22156. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22157. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22158. return this;
  22159. };
  22160. // Statics
  22161. Effect.ShadersStore = {};
  22162. Effect.IncludesShadersStore = {};
  22163. return Effect;
  22164. })();
  22165. BABYLON.Effect = Effect;
  22166. })(BABYLON || (BABYLON = {}));
  22167. var BABYLON;
  22168. (function (BABYLON) {
  22169. var MaterialHelper = (function () {
  22170. function MaterialHelper() {
  22171. }
  22172. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  22173. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22174. var lightIndex = 0;
  22175. var needNormals = false;
  22176. var needRebuild = false;
  22177. for (var index = 0; index < scene.lights.length; index++) {
  22178. var light = scene.lights[index];
  22179. if (!light.isEnabled()) {
  22180. continue;
  22181. }
  22182. // Excluded check
  22183. if (light._excludedMeshesIds.length > 0) {
  22184. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22185. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22186. if (excludedMesh) {
  22187. light.excludedMeshes.push(excludedMesh);
  22188. }
  22189. }
  22190. light._excludedMeshesIds = [];
  22191. }
  22192. // Included check
  22193. if (light._includedOnlyMeshesIds.length > 0) {
  22194. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22195. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22196. if (includedOnlyMesh) {
  22197. light.includedOnlyMeshes.push(includedOnlyMesh);
  22198. }
  22199. }
  22200. light._includedOnlyMeshesIds = [];
  22201. }
  22202. if (!light.canAffectMesh(mesh)) {
  22203. continue;
  22204. }
  22205. needNormals = true;
  22206. if (defines["LIGHT" + lightIndex] === undefined) {
  22207. needRebuild = true;
  22208. }
  22209. defines["LIGHT" + lightIndex] = true;
  22210. var type;
  22211. if (light instanceof BABYLON.SpotLight) {
  22212. type = "SPOTLIGHT" + lightIndex;
  22213. }
  22214. else if (light instanceof BABYLON.HemisphericLight) {
  22215. type = "HEMILIGHT" + lightIndex;
  22216. }
  22217. else if (light instanceof BABYLON.PointLight) {
  22218. type = "POINTLIGHT" + lightIndex;
  22219. }
  22220. else {
  22221. type = "DIRLIGHT" + lightIndex;
  22222. }
  22223. if (defines[type] === undefined) {
  22224. needRebuild = true;
  22225. }
  22226. defines[type] = true;
  22227. // Specular
  22228. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22229. defines["SPECULARTERM"] = true;
  22230. }
  22231. // Shadows
  22232. if (scene.shadowsEnabled) {
  22233. var shadowGenerator = light.getShadowGenerator();
  22234. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22235. if (defines["SHADOW" + lightIndex] === undefined) {
  22236. needRebuild = true;
  22237. }
  22238. defines["SHADOW" + lightIndex] = true;
  22239. defines["SHADOWS"] = true;
  22240. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22241. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  22242. needRebuild = true;
  22243. }
  22244. defines["SHADOWVSM" + lightIndex] = true;
  22245. }
  22246. if (shadowGenerator.usePoissonSampling) {
  22247. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  22248. needRebuild = true;
  22249. }
  22250. defines["SHADOWPCF" + lightIndex] = true;
  22251. }
  22252. }
  22253. }
  22254. lightIndex++;
  22255. if (lightIndex === maxSimultaneousLights)
  22256. break;
  22257. }
  22258. if (needRebuild) {
  22259. defines.rebuild();
  22260. }
  22261. return needNormals;
  22262. };
  22263. MaterialHelper.PrepareUniformsListForList = function (uniformsList, defines, maxSimultaneousLights) {
  22264. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22265. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22266. if (!defines["LIGHT" + lightIndex]) {
  22267. break;
  22268. }
  22269. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22270. }
  22271. };
  22272. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22273. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22274. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22275. if (!defines["LIGHT" + lightIndex]) {
  22276. break;
  22277. }
  22278. if (lightIndex > 0) {
  22279. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22280. }
  22281. if (defines["SHADOW" + lightIndex]) {
  22282. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22283. }
  22284. if (defines["SHADOWPCF" + lightIndex]) {
  22285. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22286. }
  22287. if (defines["SHADOWVSM" + lightIndex]) {
  22288. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22289. }
  22290. }
  22291. };
  22292. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22293. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22294. fallbacks.addCPUSkinningFallback(0, mesh);
  22295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22297. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22298. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22299. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22300. }
  22301. }
  22302. };
  22303. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22304. if (defines["INSTANCES"]) {
  22305. attribs.push("world0");
  22306. attribs.push("world1");
  22307. attribs.push("world2");
  22308. attribs.push("world3");
  22309. }
  22310. };
  22311. // Bindings
  22312. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22313. var shadowGenerator = light.getShadowGenerator();
  22314. if (mesh.receiveShadows && shadowGenerator) {
  22315. if (!light.needCube()) {
  22316. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22317. }
  22318. else {
  22319. if (!depthValuesAlreadySet) {
  22320. depthValuesAlreadySet = true;
  22321. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22322. }
  22323. }
  22324. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22325. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22326. }
  22327. return depthValuesAlreadySet;
  22328. };
  22329. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22330. if (light instanceof BABYLON.PointLight) {
  22331. // Point Light
  22332. light.transferToEffect(effect, "vLightData" + lightIndex);
  22333. }
  22334. else if (light instanceof BABYLON.DirectionalLight) {
  22335. // Directional Light
  22336. light.transferToEffect(effect, "vLightData" + lightIndex);
  22337. }
  22338. else if (light instanceof BABYLON.SpotLight) {
  22339. // Spot Light
  22340. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22341. }
  22342. else if (light instanceof BABYLON.HemisphericLight) {
  22343. // Hemispheric Light
  22344. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22345. }
  22346. };
  22347. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22348. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22349. var lightIndex = 0;
  22350. var depthValuesAlreadySet = false;
  22351. for (var index = 0; index < scene.lights.length; index++) {
  22352. var light = scene.lights[index];
  22353. if (!light.isEnabled()) {
  22354. continue;
  22355. }
  22356. if (!light.canAffectMesh(mesh)) {
  22357. continue;
  22358. }
  22359. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22360. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22361. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22362. if (defines["SPECULARTERM"]) {
  22363. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22364. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22365. }
  22366. // Shadows
  22367. if (scene.shadowsEnabled) {
  22368. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22369. }
  22370. lightIndex++;
  22371. if (lightIndex === maxSimultaneousLights)
  22372. break;
  22373. }
  22374. };
  22375. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22376. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22377. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22378. effect.setColor3("vFogColor", scene.fogColor);
  22379. }
  22380. };
  22381. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22382. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22383. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22384. }
  22385. };
  22386. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22387. if (defines["LOGARITHMICDEPTH"]) {
  22388. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22389. }
  22390. };
  22391. MaterialHelper.BindClipPlane = function (effect, scene) {
  22392. if (scene.clipPlane) {
  22393. var clipPlane = scene.clipPlane;
  22394. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22395. }
  22396. };
  22397. return MaterialHelper;
  22398. })();
  22399. BABYLON.MaterialHelper = MaterialHelper;
  22400. })(BABYLON || (BABYLON = {}));
  22401. var BABYLON;
  22402. (function (BABYLON) {
  22403. var FresnelParameters = (function () {
  22404. function FresnelParameters() {
  22405. this.isEnabled = true;
  22406. this.leftColor = BABYLON.Color3.White();
  22407. this.rightColor = BABYLON.Color3.Black();
  22408. this.bias = 0;
  22409. this.power = 1;
  22410. }
  22411. FresnelParameters.prototype.clone = function () {
  22412. var newFresnelParameters = new FresnelParameters();
  22413. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22414. return new FresnelParameters;
  22415. };
  22416. FresnelParameters.prototype.serialize = function () {
  22417. var serializationObject = {};
  22418. serializationObject.isEnabled = this.isEnabled;
  22419. serializationObject.leftColor = this.leftColor;
  22420. serializationObject.rightColor = this.rightColor;
  22421. serializationObject.bias = this.bias;
  22422. serializationObject.power = this.power;
  22423. return serializationObject;
  22424. };
  22425. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22426. var fresnelParameters = new FresnelParameters();
  22427. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22428. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22429. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22430. fresnelParameters.bias = parsedFresnelParameters.bias;
  22431. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22432. return fresnelParameters;
  22433. };
  22434. return FresnelParameters;
  22435. })();
  22436. BABYLON.FresnelParameters = FresnelParameters;
  22437. })(BABYLON || (BABYLON = {}));
  22438. var BABYLON;
  22439. (function (BABYLON) {
  22440. var MaterialDefines = (function () {
  22441. function MaterialDefines() {
  22442. }
  22443. MaterialDefines.prototype.rebuild = function () {
  22444. if (this._keys) {
  22445. delete this._keys;
  22446. }
  22447. this._keys = Object.keys(this);
  22448. };
  22449. MaterialDefines.prototype.isEqual = function (other) {
  22450. if (this._keys.length !== other._keys.length) {
  22451. return false;
  22452. }
  22453. for (var index = 0; index < this._keys.length; index++) {
  22454. var prop = this._keys[index];
  22455. if (this[prop] !== other[prop]) {
  22456. return false;
  22457. }
  22458. }
  22459. return true;
  22460. };
  22461. MaterialDefines.prototype.cloneTo = function (other) {
  22462. if (this._keys.length !== other._keys.length) {
  22463. other._keys = this._keys.slice(0);
  22464. }
  22465. for (var index = 0; index < this._keys.length; index++) {
  22466. var prop = this._keys[index];
  22467. other[prop] = this[prop];
  22468. }
  22469. };
  22470. MaterialDefines.prototype.reset = function () {
  22471. for (var index = 0; index < this._keys.length; index++) {
  22472. var prop = this._keys[index];
  22473. if (typeof (this[prop]) === "number") {
  22474. this[prop] = 0;
  22475. }
  22476. else {
  22477. this[prop] = false;
  22478. }
  22479. }
  22480. };
  22481. MaterialDefines.prototype.toString = function () {
  22482. var result = "";
  22483. for (var index = 0; index < this._keys.length; index++) {
  22484. var prop = this._keys[index];
  22485. if (typeof (this[prop]) === "number") {
  22486. result += "#define " + prop + " " + this[prop] + "\n";
  22487. }
  22488. else if (this[prop]) {
  22489. result += "#define " + prop + "\n";
  22490. }
  22491. }
  22492. return result;
  22493. };
  22494. return MaterialDefines;
  22495. })();
  22496. BABYLON.MaterialDefines = MaterialDefines;
  22497. var Material = (function () {
  22498. function Material(name, scene, doNotAdd) {
  22499. this.name = name;
  22500. this.checkReadyOnEveryCall = false;
  22501. this.checkReadyOnlyOnce = false;
  22502. this.state = "";
  22503. this.alpha = 1.0;
  22504. this.backFaceCulling = true;
  22505. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22506. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22507. this.disableDepthWrite = false;
  22508. this.fogEnabled = true;
  22509. this.pointSize = 1.0;
  22510. this.zOffset = 0;
  22511. this._wasPreviouslyReady = false;
  22512. this._fillMode = Material.TriangleFillMode;
  22513. this.id = name;
  22514. this._scene = scene;
  22515. if (!doNotAdd) {
  22516. scene.materials.push(this);
  22517. }
  22518. }
  22519. Object.defineProperty(Material, "TriangleFillMode", {
  22520. get: function () {
  22521. return Material._TriangleFillMode;
  22522. },
  22523. enumerable: true,
  22524. configurable: true
  22525. });
  22526. Object.defineProperty(Material, "WireFrameFillMode", {
  22527. get: function () {
  22528. return Material._WireFrameFillMode;
  22529. },
  22530. enumerable: true,
  22531. configurable: true
  22532. });
  22533. Object.defineProperty(Material, "PointFillMode", {
  22534. get: function () {
  22535. return Material._PointFillMode;
  22536. },
  22537. enumerable: true,
  22538. configurable: true
  22539. });
  22540. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22541. get: function () {
  22542. return Material._ClockWiseSideOrientation;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22548. get: function () {
  22549. return Material._CounterClockWiseSideOrientation;
  22550. },
  22551. enumerable: true,
  22552. configurable: true
  22553. });
  22554. Object.defineProperty(Material.prototype, "wireframe", {
  22555. get: function () {
  22556. return this._fillMode === Material.WireFrameFillMode;
  22557. },
  22558. set: function (value) {
  22559. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22560. },
  22561. enumerable: true,
  22562. configurable: true
  22563. });
  22564. Object.defineProperty(Material.prototype, "pointsCloud", {
  22565. get: function () {
  22566. return this._fillMode === Material.PointFillMode;
  22567. },
  22568. set: function (value) {
  22569. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22570. },
  22571. enumerable: true,
  22572. configurable: true
  22573. });
  22574. Object.defineProperty(Material.prototype, "fillMode", {
  22575. get: function () {
  22576. return this._fillMode;
  22577. },
  22578. set: function (value) {
  22579. this._fillMode = value;
  22580. },
  22581. enumerable: true,
  22582. configurable: true
  22583. });
  22584. /**
  22585. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22586. * subclasses should override adding information pertainent to themselves
  22587. */
  22588. Material.prototype.toString = function (fullDetails) {
  22589. var ret = "Name: " + this.name;
  22590. if (fullDetails) {
  22591. }
  22592. return ret;
  22593. };
  22594. Object.defineProperty(Material.prototype, "isFrozen", {
  22595. get: function () {
  22596. return this.checkReadyOnlyOnce;
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. Material.prototype.freeze = function () {
  22602. this.checkReadyOnlyOnce = true;
  22603. };
  22604. Material.prototype.unfreeze = function () {
  22605. this.checkReadyOnlyOnce = false;
  22606. };
  22607. Material.prototype.isReady = function (mesh, useInstances) {
  22608. return true;
  22609. };
  22610. Material.prototype.getEffect = function () {
  22611. return this._effect;
  22612. };
  22613. Material.prototype.getScene = function () {
  22614. return this._scene;
  22615. };
  22616. Material.prototype.needAlphaBlending = function () {
  22617. return (this.alpha < 1.0);
  22618. };
  22619. Material.prototype.needAlphaTesting = function () {
  22620. return false;
  22621. };
  22622. Material.prototype.getAlphaTestTexture = function () {
  22623. return null;
  22624. };
  22625. Material.prototype.trackCreation = function (onCompiled, onError) {
  22626. };
  22627. Material.prototype.markDirty = function () {
  22628. this._wasPreviouslyReady = false;
  22629. };
  22630. Material.prototype._preBind = function () {
  22631. var engine = this._scene.getEngine();
  22632. engine.enableEffect(this._effect);
  22633. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22634. };
  22635. Material.prototype.bind = function (world, mesh) {
  22636. this._scene._cachedMaterial = this;
  22637. if (this.onBind) {
  22638. this.onBind(this, mesh);
  22639. }
  22640. if (this.disableDepthWrite) {
  22641. var engine = this._scene.getEngine();
  22642. this._cachedDepthWriteState = engine.getDepthWrite();
  22643. engine.setDepthWrite(false);
  22644. }
  22645. };
  22646. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22647. };
  22648. Material.prototype.unbind = function () {
  22649. if (this.disableDepthWrite) {
  22650. var engine = this._scene.getEngine();
  22651. engine.setDepthWrite(this._cachedDepthWriteState);
  22652. }
  22653. };
  22654. Material.prototype.clone = function (name) {
  22655. return null;
  22656. };
  22657. Material.prototype.getBindedMeshes = function () {
  22658. var result = new Array();
  22659. for (var index = 0; index < this._scene.meshes.length; index++) {
  22660. var mesh = this._scene.meshes[index];
  22661. if (mesh.material === this) {
  22662. result.push(mesh);
  22663. }
  22664. }
  22665. return result;
  22666. };
  22667. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22668. // Animations
  22669. this.getScene().stopAnimation(this);
  22670. // Remove from scene
  22671. var index = this._scene.materials.indexOf(this);
  22672. if (index >= 0) {
  22673. this._scene.materials.splice(index, 1);
  22674. }
  22675. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22676. if (forceDisposeEffect && this._effect) {
  22677. this._scene.getEngine()._releaseEffect(this._effect);
  22678. this._effect = null;
  22679. }
  22680. // Remove from meshes
  22681. for (index = 0; index < this._scene.meshes.length; index++) {
  22682. var mesh = this._scene.meshes[index];
  22683. if (mesh.material === this) {
  22684. mesh.material = null;
  22685. }
  22686. }
  22687. // Callback
  22688. if (this.onDispose) {
  22689. this.onDispose();
  22690. }
  22691. };
  22692. Material.prototype.serialize = function () {
  22693. return BABYLON.SerializationHelper.Serialize(this);
  22694. };
  22695. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22696. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22697. multiMaterial.id = parsedMultiMaterial.id;
  22698. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22699. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22700. var subMatId = parsedMultiMaterial.materials[matIndex];
  22701. if (subMatId) {
  22702. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22703. }
  22704. else {
  22705. multiMaterial.subMaterials.push(null);
  22706. }
  22707. }
  22708. return multiMaterial;
  22709. };
  22710. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22711. if (!parsedMaterial.customType) {
  22712. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22713. }
  22714. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22715. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22716. ;
  22717. };
  22718. Material._TriangleFillMode = 0;
  22719. Material._WireFrameFillMode = 1;
  22720. Material._PointFillMode = 2;
  22721. Material._ClockWiseSideOrientation = 0;
  22722. Material._CounterClockWiseSideOrientation = 1;
  22723. __decorate([
  22724. BABYLON.serialize()
  22725. ], Material.prototype, "id", void 0);
  22726. __decorate([
  22727. BABYLON.serialize()
  22728. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22729. __decorate([
  22730. BABYLON.serialize()
  22731. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22732. __decorate([
  22733. BABYLON.serialize()
  22734. ], Material.prototype, "state", void 0);
  22735. __decorate([
  22736. BABYLON.serialize()
  22737. ], Material.prototype, "alpha", void 0);
  22738. __decorate([
  22739. BABYLON.serialize()
  22740. ], Material.prototype, "backFaceCulling", void 0);
  22741. __decorate([
  22742. BABYLON.serialize()
  22743. ], Material.prototype, "sideOrientation", void 0);
  22744. __decorate([
  22745. BABYLON.serialize()
  22746. ], Material.prototype, "alphaMode", void 0);
  22747. __decorate([
  22748. BABYLON.serialize()
  22749. ], Material.prototype, "disableDepthWrite", void 0);
  22750. __decorate([
  22751. BABYLON.serialize()
  22752. ], Material.prototype, "fogEnabled", void 0);
  22753. __decorate([
  22754. BABYLON.serialize()
  22755. ], Material.prototype, "pointSize", void 0);
  22756. __decorate([
  22757. BABYLON.serialize()
  22758. ], Material.prototype, "zOffset", void 0);
  22759. __decorate([
  22760. BABYLON.serialize()
  22761. ], Material.prototype, "wireframe", null);
  22762. __decorate([
  22763. BABYLON.serialize()
  22764. ], Material.prototype, "pointsCloud", null);
  22765. __decorate([
  22766. BABYLON.serialize()
  22767. ], Material.prototype, "fillMode", null);
  22768. return Material;
  22769. })();
  22770. BABYLON.Material = Material;
  22771. })(BABYLON || (BABYLON = {}));
  22772. var BABYLON;
  22773. (function (BABYLON) {
  22774. var StandardMaterialDefines = (function (_super) {
  22775. __extends(StandardMaterialDefines, _super);
  22776. function StandardMaterialDefines() {
  22777. _super.call(this);
  22778. this.DIFFUSE = false;
  22779. this.AMBIENT = false;
  22780. this.OPACITY = false;
  22781. this.OPACITYRGB = false;
  22782. this.REFLECTION = false;
  22783. this.EMISSIVE = false;
  22784. this.SPECULAR = false;
  22785. this.BUMP = false;
  22786. this.PARALLAX = false;
  22787. this.PARALLAXOCCLUSION = false;
  22788. this.SPECULAROVERALPHA = false;
  22789. this.CLIPPLANE = false;
  22790. this.ALPHATEST = false;
  22791. this.ALPHAFROMDIFFUSE = false;
  22792. this.POINTSIZE = false;
  22793. this.FOG = false;
  22794. this.SPECULARTERM = false;
  22795. this.DIFFUSEFRESNEL = false;
  22796. this.OPACITYFRESNEL = false;
  22797. this.REFLECTIONFRESNEL = false;
  22798. this.REFRACTIONFRESNEL = false;
  22799. this.EMISSIVEFRESNEL = false;
  22800. this.FRESNEL = false;
  22801. this.NORMAL = false;
  22802. this.UV1 = false;
  22803. this.UV2 = false;
  22804. this.VERTEXCOLOR = false;
  22805. this.VERTEXALPHA = false;
  22806. this.NUM_BONE_INFLUENCERS = 0;
  22807. this.BonesPerMesh = 0;
  22808. this.INSTANCES = false;
  22809. this.GLOSSINESS = false;
  22810. this.ROUGHNESS = false;
  22811. this.EMISSIVEASILLUMINATION = false;
  22812. this.LINKEMISSIVEWITHDIFFUSE = false;
  22813. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22814. this.LIGHTMAP = false;
  22815. this.USELIGHTMAPASSHADOWMAP = false;
  22816. this.REFLECTIONMAP_3D = false;
  22817. this.REFLECTIONMAP_SPHERICAL = false;
  22818. this.REFLECTIONMAP_PLANAR = false;
  22819. this.REFLECTIONMAP_CUBIC = false;
  22820. this.REFLECTIONMAP_PROJECTION = false;
  22821. this.REFLECTIONMAP_SKYBOX = false;
  22822. this.REFLECTIONMAP_EXPLICIT = false;
  22823. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22824. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22825. this.INVERTCUBICMAP = false;
  22826. this.LOGARITHMICDEPTH = false;
  22827. this.REFRACTION = false;
  22828. this.REFRACTIONMAP_3D = false;
  22829. this.REFLECTIONOVERALPHA = false;
  22830. this.rebuild();
  22831. }
  22832. return StandardMaterialDefines;
  22833. })(BABYLON.MaterialDefines);
  22834. var StandardMaterial = (function (_super) {
  22835. __extends(StandardMaterial, _super);
  22836. function StandardMaterial(name, scene) {
  22837. var _this = this;
  22838. _super.call(this, name, scene);
  22839. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22840. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22841. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22842. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22843. this.specularPower = 64;
  22844. this.useAlphaFromDiffuseTexture = false;
  22845. this.useEmissiveAsIllumination = false;
  22846. this.linkEmissiveWithDiffuse = false;
  22847. this.useReflectionFresnelFromSpecular = false;
  22848. this.useSpecularOverAlpha = false;
  22849. this.useReflectionOverAlpha = false;
  22850. this.disableLighting = false;
  22851. this.useParallax = false;
  22852. this.useParallaxOcclusion = false;
  22853. this.parallaxScaleBias = 0.05;
  22854. this.roughness = 0;
  22855. this.indexOfRefraction = 0.98;
  22856. this.invertRefractionY = true;
  22857. this.useLightmapAsShadowmap = false;
  22858. this.useGlossinessFromSpecularMapAlpha = false;
  22859. this.maxSimultaneousLights = 4;
  22860. this._renderTargets = new BABYLON.SmartArray(16);
  22861. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22862. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22863. this._defines = new StandardMaterialDefines();
  22864. this._cachedDefines = new StandardMaterialDefines();
  22865. this._cachedDefines.BonesPerMesh = -1;
  22866. this.getRenderTargetTextures = function () {
  22867. _this._renderTargets.reset();
  22868. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22869. _this._renderTargets.push(_this.reflectionTexture);
  22870. }
  22871. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22872. _this._renderTargets.push(_this.refractionTexture);
  22873. }
  22874. return _this._renderTargets;
  22875. };
  22876. }
  22877. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22878. get: function () {
  22879. return this._useLogarithmicDepth;
  22880. },
  22881. set: function (value) {
  22882. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22883. },
  22884. enumerable: true,
  22885. configurable: true
  22886. });
  22887. StandardMaterial.prototype.needAlphaBlending = function () {
  22888. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22889. };
  22890. StandardMaterial.prototype.needAlphaTesting = function () {
  22891. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22892. };
  22893. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22894. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22895. };
  22896. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22897. return this.diffuseTexture;
  22898. };
  22899. // Methods
  22900. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22901. if (!mesh) {
  22902. return true;
  22903. }
  22904. if (this._defines.INSTANCES !== useInstances) {
  22905. return false;
  22906. }
  22907. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22908. return true;
  22909. }
  22910. return false;
  22911. };
  22912. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22913. if (this.isFrozen) {
  22914. if (this._wasPreviouslyReady) {
  22915. return true;
  22916. }
  22917. }
  22918. var scene = this.getScene();
  22919. if (!this.checkReadyOnEveryCall) {
  22920. if (this._renderId === scene.getRenderId()) {
  22921. if (this._checkCache(scene, mesh, useInstances)) {
  22922. return true;
  22923. }
  22924. }
  22925. }
  22926. var engine = scene.getEngine();
  22927. var needNormals = false;
  22928. var needUVs = false;
  22929. this._defines.reset();
  22930. // Textures
  22931. if (scene.texturesEnabled) {
  22932. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22933. if (!this.diffuseTexture.isReady()) {
  22934. return false;
  22935. }
  22936. else {
  22937. needUVs = true;
  22938. this._defines.DIFFUSE = true;
  22939. }
  22940. }
  22941. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22942. if (!this.ambientTexture.isReady()) {
  22943. return false;
  22944. }
  22945. else {
  22946. needUVs = true;
  22947. this._defines.AMBIENT = true;
  22948. }
  22949. }
  22950. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22951. if (!this.opacityTexture.isReady()) {
  22952. return false;
  22953. }
  22954. else {
  22955. needUVs = true;
  22956. this._defines.OPACITY = true;
  22957. if (this.opacityTexture.getAlphaFromRGB) {
  22958. this._defines.OPACITYRGB = true;
  22959. }
  22960. }
  22961. }
  22962. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22963. if (!this.reflectionTexture.isReady()) {
  22964. return false;
  22965. }
  22966. else {
  22967. needNormals = true;
  22968. this._defines.REFLECTION = true;
  22969. if (this.roughness > 0) {
  22970. this._defines.ROUGHNESS = true;
  22971. }
  22972. if (this.useReflectionOverAlpha) {
  22973. this._defines.REFLECTIONOVERALPHA = true;
  22974. }
  22975. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22976. this._defines.INVERTCUBICMAP = true;
  22977. }
  22978. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22979. switch (this.reflectionTexture.coordinatesMode) {
  22980. case BABYLON.Texture.CUBIC_MODE:
  22981. case BABYLON.Texture.INVCUBIC_MODE:
  22982. this._defines.REFLECTIONMAP_CUBIC = true;
  22983. break;
  22984. case BABYLON.Texture.EXPLICIT_MODE:
  22985. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22986. break;
  22987. case BABYLON.Texture.PLANAR_MODE:
  22988. this._defines.REFLECTIONMAP_PLANAR = true;
  22989. break;
  22990. case BABYLON.Texture.PROJECTION_MODE:
  22991. this._defines.REFLECTIONMAP_PROJECTION = true;
  22992. break;
  22993. case BABYLON.Texture.SKYBOX_MODE:
  22994. this._defines.REFLECTIONMAP_SKYBOX = true;
  22995. break;
  22996. case BABYLON.Texture.SPHERICAL_MODE:
  22997. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22998. break;
  22999. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  23000. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  23001. break;
  23002. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  23003. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  23004. break;
  23005. }
  23006. }
  23007. }
  23008. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23009. if (!this.emissiveTexture.isReady()) {
  23010. return false;
  23011. }
  23012. else {
  23013. needUVs = true;
  23014. this._defines.EMISSIVE = true;
  23015. }
  23016. }
  23017. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23018. if (!this.lightmapTexture.isReady()) {
  23019. return false;
  23020. }
  23021. else {
  23022. needUVs = true;
  23023. this._defines.LIGHTMAP = true;
  23024. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  23025. }
  23026. }
  23027. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23028. if (!this.specularTexture.isReady()) {
  23029. return false;
  23030. }
  23031. else {
  23032. needUVs = true;
  23033. this._defines.SPECULAR = true;
  23034. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  23035. }
  23036. }
  23037. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  23038. if (!this.bumpTexture.isReady()) {
  23039. return false;
  23040. }
  23041. else {
  23042. needUVs = true;
  23043. this._defines.BUMP = true;
  23044. if (this.useParallax) {
  23045. this._defines.PARALLAX = true;
  23046. if (this.useParallaxOcclusion) {
  23047. this._defines.PARALLAXOCCLUSION = true;
  23048. }
  23049. }
  23050. }
  23051. }
  23052. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23053. if (!this.refractionTexture.isReady()) {
  23054. return false;
  23055. }
  23056. else {
  23057. needUVs = true;
  23058. this._defines.REFRACTION = true;
  23059. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  23060. }
  23061. }
  23062. }
  23063. // Effect
  23064. if (scene.clipPlane) {
  23065. this._defines.CLIPPLANE = true;
  23066. }
  23067. if (engine.getAlphaTesting()) {
  23068. this._defines.ALPHATEST = true;
  23069. }
  23070. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23071. this._defines.ALPHAFROMDIFFUSE = true;
  23072. }
  23073. if (this.useEmissiveAsIllumination) {
  23074. this._defines.EMISSIVEASILLUMINATION = true;
  23075. }
  23076. if (this.linkEmissiveWithDiffuse) {
  23077. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23078. }
  23079. if (this.useLogarithmicDepth) {
  23080. this._defines.LOGARITHMICDEPTH = true;
  23081. }
  23082. // Point size
  23083. if (this.pointsCloud || scene.forcePointsCloud) {
  23084. this._defines.POINTSIZE = true;
  23085. }
  23086. // Fog
  23087. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23088. this._defines.FOG = true;
  23089. }
  23090. if (scene.lightsEnabled && !this.disableLighting) {
  23091. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  23092. }
  23093. if (StandardMaterial.FresnelEnabled) {
  23094. // Fresnel
  23095. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23096. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23097. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23098. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23099. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23100. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23101. this._defines.DIFFUSEFRESNEL = true;
  23102. }
  23103. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23104. this._defines.OPACITYFRESNEL = true;
  23105. }
  23106. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23107. this._defines.REFLECTIONFRESNEL = true;
  23108. if (this.useReflectionFresnelFromSpecular) {
  23109. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23110. }
  23111. }
  23112. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23113. this._defines.REFRACTIONFRESNEL = true;
  23114. }
  23115. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23116. this._defines.EMISSIVEFRESNEL = true;
  23117. }
  23118. needNormals = true;
  23119. this._defines.FRESNEL = true;
  23120. }
  23121. }
  23122. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23123. this._defines.SPECULAROVERALPHA = true;
  23124. }
  23125. // Attribs
  23126. if (mesh) {
  23127. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23128. this._defines.NORMAL = true;
  23129. }
  23130. if (needUVs) {
  23131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23132. this._defines.UV1 = true;
  23133. }
  23134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23135. this._defines.UV2 = true;
  23136. }
  23137. }
  23138. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23139. this._defines.VERTEXCOLOR = true;
  23140. if (mesh.hasVertexAlpha) {
  23141. this._defines.VERTEXALPHA = true;
  23142. }
  23143. }
  23144. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23145. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23146. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23147. }
  23148. // Instances
  23149. if (useInstances) {
  23150. this._defines.INSTANCES = true;
  23151. }
  23152. }
  23153. // Get correct effect
  23154. if (!this._defines.isEqual(this._cachedDefines)) {
  23155. this._defines.cloneTo(this._cachedDefines);
  23156. scene.resetCachedMaterial();
  23157. // Fallbacks
  23158. var fallbacks = new BABYLON.EffectFallbacks();
  23159. if (this._defines.REFLECTION) {
  23160. fallbacks.addFallback(0, "REFLECTION");
  23161. }
  23162. if (this._defines.SPECULAR) {
  23163. fallbacks.addFallback(0, "SPECULAR");
  23164. }
  23165. if (this._defines.BUMP) {
  23166. fallbacks.addFallback(0, "BUMP");
  23167. }
  23168. if (this._defines.PARALLAX) {
  23169. fallbacks.addFallback(1, "PARALLAX");
  23170. }
  23171. if (this._defines.PARALLAXOCCLUSION) {
  23172. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23173. }
  23174. if (this._defines.SPECULAROVERALPHA) {
  23175. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23176. }
  23177. if (this._defines.FOG) {
  23178. fallbacks.addFallback(1, "FOG");
  23179. }
  23180. if (this._defines.POINTSIZE) {
  23181. fallbacks.addFallback(0, "POINTSIZE");
  23182. }
  23183. if (this._defines.LOGARITHMICDEPTH) {
  23184. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23185. }
  23186. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  23187. if (this._defines.SPECULARTERM) {
  23188. fallbacks.addFallback(0, "SPECULARTERM");
  23189. }
  23190. if (this._defines.DIFFUSEFRESNEL) {
  23191. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23192. }
  23193. if (this._defines.OPACITYFRESNEL) {
  23194. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23195. }
  23196. if (this._defines.REFLECTIONFRESNEL) {
  23197. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23198. }
  23199. if (this._defines.EMISSIVEFRESNEL) {
  23200. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23201. }
  23202. if (this._defines.FRESNEL) {
  23203. fallbacks.addFallback(4, "FRESNEL");
  23204. }
  23205. //Attributes
  23206. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23207. if (this._defines.NORMAL) {
  23208. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23209. }
  23210. if (this._defines.UV1) {
  23211. attribs.push(BABYLON.VertexBuffer.UVKind);
  23212. }
  23213. if (this._defines.UV2) {
  23214. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23215. }
  23216. if (this._defines.VERTEXCOLOR) {
  23217. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23218. }
  23219. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23220. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23221. // Legacy browser patch
  23222. var shaderName = "default";
  23223. if (!scene.getEngine().getCaps().standardDerivatives) {
  23224. shaderName = "legacydefault";
  23225. }
  23226. var join = this._defines.toString();
  23227. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23228. "vFogInfos", "vFogColor", "pointSize",
  23229. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23230. "mBones",
  23231. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23232. "depthValues",
  23233. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23234. "logarithmicDepthConstant"
  23235. ];
  23236. BABYLON.MaterialHelper.PrepareUniformsListForList(uniforms, this._defines, this.maxSimultaneousLights);
  23237. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  23238. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  23239. ], join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  23240. }
  23241. if (!this._effect.isReady()) {
  23242. return false;
  23243. }
  23244. this._renderId = scene.getRenderId();
  23245. this._wasPreviouslyReady = true;
  23246. if (mesh) {
  23247. if (!mesh._materialDefines) {
  23248. mesh._materialDefines = new StandardMaterialDefines();
  23249. }
  23250. this._defines.cloneTo(mesh._materialDefines);
  23251. }
  23252. return true;
  23253. };
  23254. StandardMaterial.prototype.unbind = function () {
  23255. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23256. this._effect.setTexture("reflection2DSampler", null);
  23257. }
  23258. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23259. this._effect.setTexture("refraction2DSampler", null);
  23260. }
  23261. _super.prototype.unbind.call(this);
  23262. };
  23263. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23264. this._effect.setMatrix("world", world);
  23265. };
  23266. StandardMaterial.prototype.bind = function (world, mesh) {
  23267. var scene = this.getScene();
  23268. // Matrices
  23269. this.bindOnlyWorldMatrix(world);
  23270. // Bones
  23271. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23272. if (scene.getCachedMaterial() !== this) {
  23273. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23274. if (StandardMaterial.FresnelEnabled) {
  23275. // Fresnel
  23276. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23277. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23278. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23279. }
  23280. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23281. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23282. }
  23283. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23284. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23285. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23286. }
  23287. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23288. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23289. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23290. }
  23291. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23292. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23293. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23294. }
  23295. }
  23296. // Textures
  23297. if (scene.texturesEnabled) {
  23298. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23299. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23300. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23301. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23302. }
  23303. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23304. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23305. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23306. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23307. }
  23308. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23309. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23310. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23311. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23312. }
  23313. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23314. if (this.reflectionTexture.isCube) {
  23315. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23316. }
  23317. else {
  23318. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23319. }
  23320. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23321. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23322. }
  23323. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23324. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23325. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23326. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23327. }
  23328. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23329. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23330. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23331. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23332. }
  23333. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23334. this._effect.setTexture("specularSampler", this.specularTexture);
  23335. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23336. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23337. }
  23338. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23339. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23340. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23341. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23342. }
  23343. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23344. var depth = 1.0;
  23345. if (this.refractionTexture.isCube) {
  23346. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23347. }
  23348. else {
  23349. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23350. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23351. if (this.refractionTexture.depth) {
  23352. depth = this.refractionTexture.depth;
  23353. }
  23354. }
  23355. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23356. }
  23357. }
  23358. // Clip plane
  23359. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23360. // Point size
  23361. if (this.pointsCloud) {
  23362. this._effect.setFloat("pointSize", this.pointSize);
  23363. }
  23364. // Colors
  23365. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23366. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23367. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23368. if (this._defines.SPECULARTERM) {
  23369. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23370. }
  23371. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23372. }
  23373. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23374. // Diffuse
  23375. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23376. // Lights
  23377. if (scene.lightsEnabled && !this.disableLighting) {
  23378. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  23379. }
  23380. // View
  23381. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23382. this._effect.setMatrix("view", scene.getViewMatrix());
  23383. }
  23384. // Fog
  23385. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23386. // Log. depth
  23387. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23388. }
  23389. _super.prototype.bind.call(this, world, mesh);
  23390. };
  23391. StandardMaterial.prototype.getAnimatables = function () {
  23392. var results = [];
  23393. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23394. results.push(this.diffuseTexture);
  23395. }
  23396. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23397. results.push(this.ambientTexture);
  23398. }
  23399. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23400. results.push(this.opacityTexture);
  23401. }
  23402. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23403. results.push(this.reflectionTexture);
  23404. }
  23405. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23406. results.push(this.emissiveTexture);
  23407. }
  23408. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23409. results.push(this.specularTexture);
  23410. }
  23411. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23412. results.push(this.bumpTexture);
  23413. }
  23414. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23415. results.push(this.lightmapTexture);
  23416. }
  23417. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23418. results.push(this.refractionTexture);
  23419. }
  23420. return results;
  23421. };
  23422. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23423. if (forceDisposeTextures) {
  23424. if (this.diffuseTexture) {
  23425. this.diffuseTexture.dispose();
  23426. }
  23427. if (this.ambientTexture) {
  23428. this.ambientTexture.dispose();
  23429. }
  23430. if (this.opacityTexture) {
  23431. this.opacityTexture.dispose();
  23432. }
  23433. if (this.reflectionTexture) {
  23434. this.reflectionTexture.dispose();
  23435. }
  23436. if (this.emissiveTexture) {
  23437. this.emissiveTexture.dispose();
  23438. }
  23439. if (this.specularTexture) {
  23440. this.specularTexture.dispose();
  23441. }
  23442. if (this.bumpTexture) {
  23443. this.bumpTexture.dispose();
  23444. }
  23445. if (this.lightmapTexture) {
  23446. this.lightmapTexture.dispose();
  23447. }
  23448. if (this.refractionTexture) {
  23449. this.refractionTexture.dispose();
  23450. }
  23451. }
  23452. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  23453. };
  23454. StandardMaterial.prototype.clone = function (name) {
  23455. var _this = this;
  23456. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23457. };
  23458. StandardMaterial.prototype.serialize = function () {
  23459. return BABYLON.SerializationHelper.Serialize(this);
  23460. };
  23461. // Statics
  23462. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23463. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23464. };
  23465. // Flags used to enable or disable a type of texture for all Standard Materials
  23466. StandardMaterial.DiffuseTextureEnabled = true;
  23467. StandardMaterial.AmbientTextureEnabled = true;
  23468. StandardMaterial.OpacityTextureEnabled = true;
  23469. StandardMaterial.ReflectionTextureEnabled = true;
  23470. StandardMaterial.EmissiveTextureEnabled = true;
  23471. StandardMaterial.SpecularTextureEnabled = true;
  23472. StandardMaterial.BumpTextureEnabled = true;
  23473. StandardMaterial.FresnelEnabled = true;
  23474. StandardMaterial.LightmapTextureEnabled = true;
  23475. StandardMaterial.RefractionTextureEnabled = true;
  23476. __decorate([
  23477. BABYLON.serializeAsTexture()
  23478. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23479. __decorate([
  23480. BABYLON.serializeAsTexture()
  23481. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23482. __decorate([
  23483. BABYLON.serializeAsTexture()
  23484. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23485. __decorate([
  23486. BABYLON.serializeAsTexture()
  23487. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23488. __decorate([
  23489. BABYLON.serializeAsTexture()
  23490. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23491. __decorate([
  23492. BABYLON.serializeAsTexture()
  23493. ], StandardMaterial.prototype, "specularTexture", void 0);
  23494. __decorate([
  23495. BABYLON.serializeAsTexture()
  23496. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23497. __decorate([
  23498. BABYLON.serializeAsTexture()
  23499. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23500. __decorate([
  23501. BABYLON.serializeAsTexture()
  23502. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23503. __decorate([
  23504. BABYLON.serializeAsColor3("ambient")
  23505. ], StandardMaterial.prototype, "ambientColor", void 0);
  23506. __decorate([
  23507. BABYLON.serializeAsColor3("diffuse")
  23508. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23509. __decorate([
  23510. BABYLON.serializeAsColor3("specular")
  23511. ], StandardMaterial.prototype, "specularColor", void 0);
  23512. __decorate([
  23513. BABYLON.serializeAsColor3("emissive")
  23514. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23515. __decorate([
  23516. BABYLON.serialize()
  23517. ], StandardMaterial.prototype, "specularPower", void 0);
  23518. __decorate([
  23519. BABYLON.serialize()
  23520. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23521. __decorate([
  23522. BABYLON.serialize()
  23523. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23524. __decorate([
  23525. BABYLON.serialize()
  23526. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23527. __decorate([
  23528. BABYLON.serialize()
  23529. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23530. __decorate([
  23531. BABYLON.serialize()
  23532. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23533. __decorate([
  23534. BABYLON.serialize()
  23535. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23536. __decorate([
  23537. BABYLON.serialize()
  23538. ], StandardMaterial.prototype, "disableLighting", void 0);
  23539. __decorate([
  23540. BABYLON.serialize()
  23541. ], StandardMaterial.prototype, "useParallax", void 0);
  23542. __decorate([
  23543. BABYLON.serialize()
  23544. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23545. __decorate([
  23546. BABYLON.serialize()
  23547. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23548. __decorate([
  23549. BABYLON.serialize()
  23550. ], StandardMaterial.prototype, "roughness", void 0);
  23551. __decorate([
  23552. BABYLON.serialize()
  23553. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23554. __decorate([
  23555. BABYLON.serialize()
  23556. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23557. __decorate([
  23558. BABYLON.serialize()
  23559. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23560. __decorate([
  23561. BABYLON.serializeAsFresnelParameters()
  23562. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23563. __decorate([
  23564. BABYLON.serializeAsFresnelParameters()
  23565. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23566. __decorate([
  23567. BABYLON.serializeAsFresnelParameters()
  23568. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23569. __decorate([
  23570. BABYLON.serializeAsFresnelParameters()
  23571. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23572. __decorate([
  23573. BABYLON.serializeAsFresnelParameters()
  23574. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23575. __decorate([
  23576. BABYLON.serialize()
  23577. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23578. __decorate([
  23579. BABYLON.serialize()
  23580. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  23581. __decorate([
  23582. BABYLON.serialize()
  23583. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23584. return StandardMaterial;
  23585. })(BABYLON.Material);
  23586. BABYLON.StandardMaterial = StandardMaterial;
  23587. })(BABYLON || (BABYLON = {}));
  23588. var BABYLON;
  23589. (function (BABYLON) {
  23590. var MultiMaterial = (function (_super) {
  23591. __extends(MultiMaterial, _super);
  23592. function MultiMaterial(name, scene) {
  23593. _super.call(this, name, scene, true);
  23594. this.subMaterials = new Array();
  23595. scene.multiMaterials.push(this);
  23596. }
  23597. // Properties
  23598. MultiMaterial.prototype.getSubMaterial = function (index) {
  23599. if (index < 0 || index >= this.subMaterials.length) {
  23600. return this.getScene().defaultMaterial;
  23601. }
  23602. return this.subMaterials[index];
  23603. };
  23604. // Methods
  23605. MultiMaterial.prototype.isReady = function (mesh) {
  23606. for (var index = 0; index < this.subMaterials.length; index++) {
  23607. var subMaterial = this.subMaterials[index];
  23608. if (subMaterial) {
  23609. if (!this.subMaterials[index].isReady(mesh)) {
  23610. return false;
  23611. }
  23612. }
  23613. }
  23614. return true;
  23615. };
  23616. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23617. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23618. for (var index = 0; index < this.subMaterials.length; index++) {
  23619. var subMaterial = null;
  23620. if (cloneChildren) {
  23621. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23622. }
  23623. else {
  23624. subMaterial = this.subMaterials[index];
  23625. }
  23626. newMultiMaterial.subMaterials.push(subMaterial);
  23627. }
  23628. return newMultiMaterial;
  23629. };
  23630. MultiMaterial.prototype.serialize = function () {
  23631. var serializationObject = {};
  23632. serializationObject.name = this.name;
  23633. serializationObject.id = this.id;
  23634. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23635. serializationObject.materials = [];
  23636. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23637. var subMat = this.subMaterials[matIndex];
  23638. if (subMat) {
  23639. serializationObject.materials.push(subMat.id);
  23640. }
  23641. else {
  23642. serializationObject.materials.push(null);
  23643. }
  23644. }
  23645. return serializationObject;
  23646. };
  23647. return MultiMaterial;
  23648. })(BABYLON.Material);
  23649. BABYLON.MultiMaterial = MultiMaterial;
  23650. })(BABYLON || (BABYLON = {}));
  23651. var BABYLON;
  23652. (function (BABYLON) {
  23653. var SceneLoader = (function () {
  23654. function SceneLoader() {
  23655. }
  23656. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23657. get: function () {
  23658. return 0;
  23659. },
  23660. enumerable: true,
  23661. configurable: true
  23662. });
  23663. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23664. get: function () {
  23665. return 1;
  23666. },
  23667. enumerable: true,
  23668. configurable: true
  23669. });
  23670. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23671. get: function () {
  23672. return 2;
  23673. },
  23674. enumerable: true,
  23675. configurable: true
  23676. });
  23677. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23678. get: function () {
  23679. return 3;
  23680. },
  23681. enumerable: true,
  23682. configurable: true
  23683. });
  23684. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23685. get: function () {
  23686. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23687. },
  23688. set: function (value) {
  23689. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23690. },
  23691. enumerable: true,
  23692. configurable: true
  23693. });
  23694. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23695. get: function () {
  23696. return SceneLoader._ShowLoadingScreen;
  23697. },
  23698. set: function (value) {
  23699. SceneLoader._ShowLoadingScreen = value;
  23700. },
  23701. enumerable: true,
  23702. configurable: true
  23703. });
  23704. Object.defineProperty(SceneLoader, "loggingLevel", {
  23705. get: function () {
  23706. return SceneLoader._loggingLevel;
  23707. },
  23708. set: function (value) {
  23709. SceneLoader._loggingLevel = value;
  23710. },
  23711. enumerable: true,
  23712. configurable: true
  23713. });
  23714. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23715. var dotPosition = sceneFilename.lastIndexOf(".");
  23716. var queryStringPosition = sceneFilename.indexOf("?");
  23717. if (queryStringPosition === -1) {
  23718. queryStringPosition = sceneFilename.length;
  23719. }
  23720. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23721. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23722. var plugin = this._registeredPlugins[index];
  23723. if (plugin.extensions.indexOf(extension) !== -1) {
  23724. return plugin;
  23725. }
  23726. }
  23727. return this._registeredPlugins[0];
  23728. };
  23729. // Public functions
  23730. SceneLoader.GetPluginForExtension = function (extension) {
  23731. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23732. var plugin = this._registeredPlugins[index];
  23733. if (plugin.extensions.indexOf(extension) !== -1) {
  23734. return plugin;
  23735. }
  23736. }
  23737. return null;
  23738. };
  23739. SceneLoader.RegisterPlugin = function (plugin) {
  23740. plugin.extensions = plugin.extensions.toLowerCase();
  23741. SceneLoader._registeredPlugins.push(plugin);
  23742. };
  23743. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23744. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23745. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23746. return;
  23747. }
  23748. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23749. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23750. return;
  23751. }
  23752. var loadingToken = {};
  23753. scene._addPendingData(loadingToken);
  23754. var manifestChecked = function (success) {
  23755. scene.database = database;
  23756. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23757. var importMeshFromData = function (data) {
  23758. var meshes = [];
  23759. var particleSystems = [];
  23760. var skeletons = [];
  23761. try {
  23762. if (plugin.importMesh) {
  23763. var syncedPlugin = plugin;
  23764. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23765. if (onerror) {
  23766. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23767. }
  23768. scene._removePendingData(loadingToken);
  23769. return;
  23770. }
  23771. if (onsuccess) {
  23772. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23773. onsuccess(meshes, particleSystems, skeletons);
  23774. scene._removePendingData(loadingToken);
  23775. }
  23776. }
  23777. else {
  23778. var asyncedPlugin = plugin;
  23779. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23780. if (onsuccess) {
  23781. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23782. onsuccess(meshes, particleSystems, skeletons);
  23783. scene._removePendingData(loadingToken);
  23784. }
  23785. }, function () {
  23786. if (onerror) {
  23787. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23788. }
  23789. scene._removePendingData(loadingToken);
  23790. });
  23791. }
  23792. }
  23793. catch (e) {
  23794. if (onerror) {
  23795. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  23796. }
  23797. scene._removePendingData(loadingToken);
  23798. }
  23799. };
  23800. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23801. // Direct load
  23802. importMeshFromData(sceneFilename.substr(5));
  23803. return;
  23804. }
  23805. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23806. importMeshFromData(data);
  23807. }, progressCallBack, database);
  23808. };
  23809. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23810. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23811. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23812. }
  23813. else {
  23814. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23815. manifestChecked(true);
  23816. }
  23817. };
  23818. /**
  23819. * Load a scene
  23820. * @param rootUrl a string that defines the root url for scene and resources
  23821. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23822. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23823. */
  23824. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23825. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23826. };
  23827. /**
  23828. * Append a scene
  23829. * @param rootUrl a string that defines the root url for scene and resources
  23830. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23831. * @param scene is the instance of BABYLON.Scene to append to
  23832. */
  23833. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23834. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23835. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23836. return;
  23837. }
  23838. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23839. var database;
  23840. var loadingToken = {};
  23841. scene._addPendingData(loadingToken);
  23842. if (SceneLoader.ShowLoadingScreen) {
  23843. scene.getEngine().displayLoadingUI();
  23844. }
  23845. var loadSceneFromData = function (data) {
  23846. scene.database = database;
  23847. if (plugin.load) {
  23848. var syncedPlugin = plugin;
  23849. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23850. if (onerror) {
  23851. onerror(scene);
  23852. }
  23853. scene._removePendingData(loadingToken);
  23854. scene.getEngine().hideLoadingUI();
  23855. return;
  23856. }
  23857. if (onsuccess) {
  23858. onsuccess(scene);
  23859. }
  23860. scene._removePendingData(loadingToken);
  23861. }
  23862. else {
  23863. var asyncedPlugin = plugin;
  23864. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23865. if (onsuccess) {
  23866. onsuccess(scene);
  23867. }
  23868. }, function () {
  23869. if (onerror) {
  23870. onerror(scene);
  23871. }
  23872. scene._removePendingData(loadingToken);
  23873. scene.getEngine().hideLoadingUI();
  23874. });
  23875. }
  23876. if (SceneLoader.ShowLoadingScreen) {
  23877. scene.executeWhenReady(function () {
  23878. scene.getEngine().hideLoadingUI();
  23879. });
  23880. }
  23881. };
  23882. var manifestChecked = function (success) {
  23883. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23884. };
  23885. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23886. // Direct load
  23887. loadSceneFromData(sceneFilename.substr(5));
  23888. return;
  23889. }
  23890. if (rootUrl.indexOf("file:") === -1) {
  23891. if (scene.getEngine().enableOfflineSupport) {
  23892. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23893. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23894. }
  23895. else {
  23896. manifestChecked(true);
  23897. }
  23898. }
  23899. else {
  23900. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23901. }
  23902. };
  23903. // Flags
  23904. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23905. SceneLoader._ShowLoadingScreen = true;
  23906. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23907. // Members
  23908. SceneLoader._registeredPlugins = new Array();
  23909. return SceneLoader;
  23910. })();
  23911. BABYLON.SceneLoader = SceneLoader;
  23912. ;
  23913. })(BABYLON || (BABYLON = {}));
  23914. var BABYLON;
  23915. (function (BABYLON) {
  23916. var Internals;
  23917. (function (Internals) {
  23918. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23919. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23920. var parsedMaterial = parsedData.materials[index];
  23921. if (parsedMaterial.id === id) {
  23922. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23923. }
  23924. }
  23925. return null;
  23926. };
  23927. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23928. names = (names instanceof Array) ? names : [names];
  23929. for (var i in names) {
  23930. if (mesh.name === names[i]) {
  23931. hierarchyIds.push(mesh.id);
  23932. return true;
  23933. }
  23934. }
  23935. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23936. hierarchyIds.push(mesh.id);
  23937. return true;
  23938. }
  23939. return false;
  23940. };
  23941. var logOperation = function (operation, producer) {
  23942. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23943. };
  23944. BABYLON.SceneLoader.RegisterPlugin({
  23945. extensions: ".babylon",
  23946. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23947. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23948. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23949. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23950. // and avoid problems with multiple concurrent .babylon loads.
  23951. var log = "importMesh has failed JSON parse";
  23952. try {
  23953. var parsedData = JSON.parse(data);
  23954. log = "";
  23955. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23956. var loadedSkeletonsIds = [];
  23957. var loadedMaterialsIds = [];
  23958. var hierarchyIds = [];
  23959. var index;
  23960. var cache;
  23961. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23962. var parsedMesh = parsedData.meshes[index];
  23963. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23964. if (meshesNames instanceof Array) {
  23965. // Remove found mesh name from list.
  23966. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23967. }
  23968. //Geometry?
  23969. if (parsedMesh.geometryId) {
  23970. //does the file contain geometries?
  23971. if (parsedData.geometries) {
  23972. //find the correct geometry and add it to the scene
  23973. var found = false;
  23974. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23975. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23976. return;
  23977. }
  23978. else {
  23979. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23980. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23981. switch (geometryType) {
  23982. case "boxes":
  23983. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23984. break;
  23985. case "spheres":
  23986. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23987. break;
  23988. case "cylinders":
  23989. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23990. break;
  23991. case "toruses":
  23992. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23993. break;
  23994. case "grounds":
  23995. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23996. break;
  23997. case "planes":
  23998. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23999. break;
  24000. case "torusKnots":
  24001. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  24002. break;
  24003. case "vertexData":
  24004. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  24005. break;
  24006. }
  24007. found = true;
  24008. }
  24009. });
  24010. }
  24011. });
  24012. if (!found) {
  24013. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  24014. }
  24015. }
  24016. }
  24017. // Material ?
  24018. if (parsedMesh.materialId) {
  24019. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  24020. if (!materialFound && parsedData.multiMaterials) {
  24021. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  24022. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  24023. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  24024. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  24025. var subMatId = parsedMultiMaterial.materials[matIndex];
  24026. loadedMaterialsIds.push(subMatId);
  24027. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  24028. log += "\n\tMaterial " + mat.toString(fullDetails);
  24029. }
  24030. loadedMaterialsIds.push(parsedMultiMaterial.id);
  24031. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24032. materialFound = true;
  24033. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  24034. break;
  24035. }
  24036. }
  24037. }
  24038. if (!materialFound) {
  24039. loadedMaterialsIds.push(parsedMesh.materialId);
  24040. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  24041. if (!mat) {
  24042. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  24043. }
  24044. else {
  24045. log += "\n\tMaterial " + mat.toString(fullDetails);
  24046. }
  24047. }
  24048. }
  24049. // Skeleton ?
  24050. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  24051. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  24052. if (!skeletonAlreadyLoaded) {
  24053. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  24054. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  24055. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  24056. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24057. skeletons.push(skeleton);
  24058. loadedSkeletonsIds.push(parsedSkeleton.id);
  24059. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  24060. }
  24061. }
  24062. }
  24063. }
  24064. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24065. meshes.push(mesh);
  24066. log += "\n\tMesh " + mesh.toString(fullDetails);
  24067. }
  24068. }
  24069. // Connecting parents
  24070. var currentMesh;
  24071. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24072. currentMesh = scene.meshes[index];
  24073. if (currentMesh._waitingParentId) {
  24074. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24075. currentMesh._waitingParentId = undefined;
  24076. }
  24077. }
  24078. // freeze and compute world matrix application
  24079. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24080. currentMesh = scene.meshes[index];
  24081. if (currentMesh._waitingFreezeWorldMatrix) {
  24082. currentMesh.freezeWorldMatrix();
  24083. currentMesh._waitingFreezeWorldMatrix = undefined;
  24084. }
  24085. else {
  24086. currentMesh.computeWorldMatrix(true);
  24087. }
  24088. }
  24089. // Particles
  24090. if (parsedData.particleSystems) {
  24091. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24092. var parsedParticleSystem = parsedData.particleSystems[index];
  24093. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24094. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24095. }
  24096. }
  24097. }
  24098. return true;
  24099. }
  24100. catch (err) {
  24101. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24102. log = null;
  24103. throw err;
  24104. }
  24105. finally {
  24106. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24107. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24108. }
  24109. }
  24110. },
  24111. load: function (scene, data, rootUrl) {
  24112. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24113. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24114. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24115. // and avoid problems with multiple concurrent .babylon loads.
  24116. var log = "importScene has failed JSON parse";
  24117. try {
  24118. var parsedData = JSON.parse(data);
  24119. log = "";
  24120. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24121. // Scene
  24122. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24123. scene.autoClear = parsedData.autoClear;
  24124. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24125. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24126. if (parsedData.gravity) {
  24127. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24128. }
  24129. // Fog
  24130. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24131. scene.fogMode = parsedData.fogMode;
  24132. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24133. scene.fogStart = parsedData.fogStart;
  24134. scene.fogEnd = parsedData.fogEnd;
  24135. scene.fogDensity = parsedData.fogDensity;
  24136. log += "\tFog mode for scene: ";
  24137. switch (scene.fogMode) {
  24138. // getters not compiling, so using hardcoded
  24139. case 1:
  24140. log += "exp\n";
  24141. break;
  24142. case 2:
  24143. log += "exp2\n";
  24144. break;
  24145. case 3:
  24146. log += "linear\n";
  24147. break;
  24148. }
  24149. }
  24150. //Physics
  24151. if (parsedData.physicsEnabled) {
  24152. var physicsPlugin;
  24153. if (parsedData.physicsEngine === "cannon") {
  24154. physicsPlugin = new BABYLON.CannonJSPlugin();
  24155. }
  24156. else if (parsedData.physicsEngine === "oimo") {
  24157. physicsPlugin = new BABYLON.OimoJSPlugin();
  24158. }
  24159. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24160. //else - default engine, which is currently oimo
  24161. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24162. scene.enablePhysics(physicsGravity, physicsPlugin);
  24163. }
  24164. //collisions, if defined. otherwise, default is true
  24165. if (parsedData.collisionsEnabled != undefined) {
  24166. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24167. }
  24168. scene.workerCollisions = !!parsedData.workerCollisions;
  24169. var index;
  24170. var cache;
  24171. // Lights
  24172. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24173. var parsedLight = parsedData.lights[index];
  24174. var light = BABYLON.Light.Parse(parsedLight, scene);
  24175. log += (index === 0 ? "\n\tLights:" : "");
  24176. log += "\n\t\t" + light.toString(fullDetails);
  24177. }
  24178. // Animations
  24179. if (parsedData.animations) {
  24180. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24181. var parsedAnimation = parsedData.animations[index];
  24182. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24183. scene.animations.push(animation);
  24184. log += (index === 0 ? "\n\tAnimations:" : "");
  24185. log += "\n\t\t" + animation.toString(fullDetails);
  24186. }
  24187. }
  24188. if (parsedData.autoAnimate) {
  24189. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  24190. }
  24191. // Materials
  24192. if (parsedData.materials) {
  24193. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24194. var parsedMaterial = parsedData.materials[index];
  24195. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24196. log += (index === 0 ? "\n\tMaterials:" : "");
  24197. log += "\n\t\t" + mat.toString(fullDetails);
  24198. }
  24199. }
  24200. if (parsedData.multiMaterials) {
  24201. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24202. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24203. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24204. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24205. log += "\n\t\t" + mmat.toString(fullDetails);
  24206. }
  24207. }
  24208. // Skeletons
  24209. if (parsedData.skeletons) {
  24210. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24211. var parsedSkeleton = parsedData.skeletons[index];
  24212. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24213. log += (index === 0 ? "\n\tSkeletons:" : "");
  24214. log += "\n\t\t" + skeleton.toString(fullDetails);
  24215. }
  24216. }
  24217. // Geometries
  24218. var geometries = parsedData.geometries;
  24219. if (geometries) {
  24220. // Boxes
  24221. var boxes = geometries.boxes;
  24222. if (boxes) {
  24223. for (index = 0, cache = boxes.length; index < cache; index++) {
  24224. var parsedBox = boxes[index];
  24225. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24226. }
  24227. }
  24228. // Spheres
  24229. var spheres = geometries.spheres;
  24230. if (spheres) {
  24231. for (index = 0, cache = spheres.length; index < cache; index++) {
  24232. var parsedSphere = spheres[index];
  24233. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24234. }
  24235. }
  24236. // Cylinders
  24237. var cylinders = geometries.cylinders;
  24238. if (cylinders) {
  24239. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24240. var parsedCylinder = cylinders[index];
  24241. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24242. }
  24243. }
  24244. // Toruses
  24245. var toruses = geometries.toruses;
  24246. if (toruses) {
  24247. for (index = 0, cache = toruses.length; index < cache; index++) {
  24248. var parsedTorus = toruses[index];
  24249. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24250. }
  24251. }
  24252. // Grounds
  24253. var grounds = geometries.grounds;
  24254. if (grounds) {
  24255. for (index = 0, cache = grounds.length; index < cache; index++) {
  24256. var parsedGround = grounds[index];
  24257. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24258. }
  24259. }
  24260. // Planes
  24261. var planes = geometries.planes;
  24262. if (planes) {
  24263. for (index = 0, cache = planes.length; index < cache; index++) {
  24264. var parsedPlane = planes[index];
  24265. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24266. }
  24267. }
  24268. // TorusKnots
  24269. var torusKnots = geometries.torusKnots;
  24270. if (torusKnots) {
  24271. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24272. var parsedTorusKnot = torusKnots[index];
  24273. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24274. }
  24275. }
  24276. // VertexData
  24277. var vertexData = geometries.vertexData;
  24278. if (vertexData) {
  24279. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24280. var parsedVertexData = vertexData[index];
  24281. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24282. }
  24283. }
  24284. }
  24285. // Meshes
  24286. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24287. var parsedMesh = parsedData.meshes[index];
  24288. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24289. log += (index === 0 ? "\n\tMeshes:" : "");
  24290. log += "\n\t\t" + mesh.toString(fullDetails);
  24291. }
  24292. // Cameras
  24293. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24294. var parsedCamera = parsedData.cameras[index];
  24295. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24296. log += (index === 0 ? "\n\tCameras:" : "");
  24297. log += "\n\t\t" + camera.toString(fullDetails);
  24298. }
  24299. if (parsedData.activeCameraID) {
  24300. scene.setActiveCameraByID(parsedData.activeCameraID);
  24301. }
  24302. // Browsing all the graph to connect the dots
  24303. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24304. var camera = scene.cameras[index];
  24305. if (camera._waitingParentId) {
  24306. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24307. camera._waitingParentId = undefined;
  24308. }
  24309. }
  24310. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24311. var light = scene.lights[index];
  24312. if (light._waitingParentId) {
  24313. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24314. light._waitingParentId = undefined;
  24315. }
  24316. }
  24317. // Sounds
  24318. var loadedSounds = [];
  24319. var loadedSound;
  24320. if (BABYLON.AudioEngine && parsedData.sounds) {
  24321. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24322. var parsedSound = parsedData.sounds[index];
  24323. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24324. if (!parsedSound.url)
  24325. parsedSound.url = parsedSound.name;
  24326. if (!loadedSounds[parsedSound.url]) {
  24327. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24328. loadedSounds[parsedSound.url] = loadedSound;
  24329. }
  24330. else {
  24331. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24332. }
  24333. }
  24334. else {
  24335. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24336. }
  24337. }
  24338. }
  24339. loadedSounds = [];
  24340. // Connect parents & children and parse actions
  24341. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24342. var mesh = scene.meshes[index];
  24343. if (mesh._waitingParentId) {
  24344. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24345. mesh._waitingParentId = undefined;
  24346. }
  24347. if (mesh._waitingActions) {
  24348. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24349. mesh._waitingActions = undefined;
  24350. }
  24351. }
  24352. // freeze world matrix application
  24353. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24354. var currentMesh = scene.meshes[index];
  24355. if (currentMesh._waitingFreezeWorldMatrix) {
  24356. currentMesh.freezeWorldMatrix();
  24357. currentMesh._waitingFreezeWorldMatrix = undefined;
  24358. }
  24359. else {
  24360. currentMesh.computeWorldMatrix(true);
  24361. }
  24362. }
  24363. // Particles Systems
  24364. if (parsedData.particleSystems) {
  24365. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24366. var parsedParticleSystem = parsedData.particleSystems[index];
  24367. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24368. }
  24369. }
  24370. // Lens flares
  24371. if (parsedData.lensFlareSystems) {
  24372. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24373. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24374. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24375. }
  24376. }
  24377. // Shadows
  24378. if (parsedData.shadowGenerators) {
  24379. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24380. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24381. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24382. }
  24383. }
  24384. // Actions (scene)
  24385. if (parsedData.actions) {
  24386. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24387. }
  24388. // Finish
  24389. return true;
  24390. }
  24391. catch (err) {
  24392. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24393. log = null;
  24394. throw err;
  24395. }
  24396. finally {
  24397. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24398. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24399. }
  24400. }
  24401. }
  24402. });
  24403. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24404. })(BABYLON || (BABYLON = {}));
  24405. var BABYLON;
  24406. (function (BABYLON) {
  24407. var SpriteManager = (function () {
  24408. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24410. this.name = name;
  24411. this.cellSize = cellSize;
  24412. this.sprites = new Array();
  24413. this.renderingGroupId = 0;
  24414. this.layerMask = 0x0FFFFFFF;
  24415. this.fogEnabled = true;
  24416. this.isPickable = false;
  24417. this._vertexDeclaration = [4, 4, 4, 4];
  24418. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24419. this._capacity = capacity;
  24420. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24421. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24422. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24423. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24424. this._scene = scene;
  24425. this._scene.spriteManagers.push(this);
  24426. // VBO
  24427. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24428. var indices = [];
  24429. var index = 0;
  24430. for (var count = 0; count < capacity; count++) {
  24431. indices.push(index);
  24432. indices.push(index + 1);
  24433. indices.push(index + 2);
  24434. indices.push(index);
  24435. indices.push(index + 2);
  24436. indices.push(index + 3);
  24437. index += 4;
  24438. }
  24439. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24440. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24441. // Effects
  24442. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24443. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24444. }
  24445. Object.defineProperty(SpriteManager.prototype, "texture", {
  24446. get: function () {
  24447. return this._spriteTexture;
  24448. },
  24449. set: function (value) {
  24450. this._spriteTexture = value;
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24456. var arrayOffset = index * 16;
  24457. if (offsetX === 0)
  24458. offsetX = this._epsilon;
  24459. else if (offsetX === 1)
  24460. offsetX = 1 - this._epsilon;
  24461. if (offsetY === 0)
  24462. offsetY = this._epsilon;
  24463. else if (offsetY === 1)
  24464. offsetY = 1 - this._epsilon;
  24465. this._vertices[arrayOffset] = sprite.position.x;
  24466. this._vertices[arrayOffset + 1] = sprite.position.y;
  24467. this._vertices[arrayOffset + 2] = sprite.position.z;
  24468. this._vertices[arrayOffset + 3] = sprite.angle;
  24469. this._vertices[arrayOffset + 4] = sprite.width;
  24470. this._vertices[arrayOffset + 5] = sprite.height;
  24471. this._vertices[arrayOffset + 6] = offsetX;
  24472. this._vertices[arrayOffset + 7] = offsetY;
  24473. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24474. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24475. var offset = (sprite.cellIndex / rowSize) >> 0;
  24476. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24477. this._vertices[arrayOffset + 11] = offset;
  24478. // Color
  24479. this._vertices[arrayOffset + 12] = sprite.color.r;
  24480. this._vertices[arrayOffset + 13] = sprite.color.g;
  24481. this._vertices[arrayOffset + 14] = sprite.color.b;
  24482. this._vertices[arrayOffset + 15] = sprite.color.a;
  24483. };
  24484. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24485. var count = Math.min(this._capacity, this.sprites.length);
  24486. var min = BABYLON.Vector3.Zero();
  24487. var max = BABYLON.Vector3.Zero();
  24488. var distance = Number.MAX_VALUE;
  24489. var currentSprite;
  24490. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24491. var cameraView = camera.getViewMatrix();
  24492. for (var index = 0; index < count; index++) {
  24493. var sprite = this.sprites[index];
  24494. if (!sprite) {
  24495. continue;
  24496. }
  24497. if (predicate) {
  24498. if (!predicate(sprite)) {
  24499. continue;
  24500. }
  24501. }
  24502. else if (!sprite.isPickable) {
  24503. continue;
  24504. }
  24505. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24506. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24507. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24508. if (ray.intersectsBoxMinMax(min, max)) {
  24509. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24510. if (distance > currentDistance) {
  24511. distance = currentDistance;
  24512. currentSprite = sprite;
  24513. if (fastCheck) {
  24514. break;
  24515. }
  24516. }
  24517. }
  24518. }
  24519. if (currentSprite) {
  24520. var result = new BABYLON.PickingInfo();
  24521. result.hit = true;
  24522. result.pickedSprite = currentSprite;
  24523. result.distance = distance;
  24524. return result;
  24525. }
  24526. return null;
  24527. };
  24528. SpriteManager.prototype.render = function () {
  24529. // Check
  24530. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24531. return;
  24532. var engine = this._scene.getEngine();
  24533. var baseSize = this._spriteTexture.getBaseSize();
  24534. // Sprites
  24535. var deltaTime = engine.getDeltaTime();
  24536. var max = Math.min(this._capacity, this.sprites.length);
  24537. var rowSize = baseSize.width / this.cellSize;
  24538. var offset = 0;
  24539. for (var index = 0; index < max; index++) {
  24540. var sprite = this.sprites[index];
  24541. if (!sprite) {
  24542. continue;
  24543. }
  24544. sprite._animate(deltaTime);
  24545. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24546. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24547. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24548. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24549. }
  24550. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24551. // Render
  24552. var effect = this._effectBase;
  24553. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24554. effect = this._effectFog;
  24555. }
  24556. engine.enableEffect(effect);
  24557. var viewMatrix = this._scene.getViewMatrix();
  24558. effect.setTexture("diffuseSampler", this._spriteTexture);
  24559. effect.setMatrix("view", viewMatrix);
  24560. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24561. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24562. // Fog
  24563. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24564. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24565. effect.setColor3("vFogColor", this._scene.fogColor);
  24566. }
  24567. // VBOs
  24568. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24569. // Draw order
  24570. engine.setDepthFunctionToLessOrEqual();
  24571. effect.setBool("alphaTest", true);
  24572. engine.setColorWrite(false);
  24573. engine.draw(true, 0, max * 6);
  24574. engine.setColorWrite(true);
  24575. effect.setBool("alphaTest", false);
  24576. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24577. engine.draw(true, 0, max * 6);
  24578. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24579. };
  24580. SpriteManager.prototype.dispose = function () {
  24581. if (this._vertexBuffer) {
  24582. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24583. this._vertexBuffer = null;
  24584. }
  24585. if (this._indexBuffer) {
  24586. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24587. this._indexBuffer = null;
  24588. }
  24589. if (this._spriteTexture) {
  24590. this._spriteTexture.dispose();
  24591. this._spriteTexture = null;
  24592. }
  24593. // Remove from scene
  24594. var index = this._scene.spriteManagers.indexOf(this);
  24595. this._scene.spriteManagers.splice(index, 1);
  24596. // Callback
  24597. if (this.onDispose) {
  24598. this.onDispose();
  24599. }
  24600. };
  24601. return SpriteManager;
  24602. })();
  24603. BABYLON.SpriteManager = SpriteManager;
  24604. })(BABYLON || (BABYLON = {}));
  24605. var BABYLON;
  24606. (function (BABYLON) {
  24607. var Sprite = (function () {
  24608. function Sprite(name, manager) {
  24609. this.name = name;
  24610. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24611. this.width = 1.0;
  24612. this.height = 1.0;
  24613. this.angle = 0;
  24614. this.cellIndex = 0;
  24615. this.invertU = 0;
  24616. this.invertV = 0;
  24617. this.animations = new Array();
  24618. this.isPickable = false;
  24619. this._animationStarted = false;
  24620. this._loopAnimation = false;
  24621. this._fromIndex = 0;
  24622. this._toIndex = 0;
  24623. this._delay = 0;
  24624. this._direction = 1;
  24625. this._frameCount = 0;
  24626. this._time = 0;
  24627. this._manager = manager;
  24628. this._manager.sprites.push(this);
  24629. this.position = BABYLON.Vector3.Zero();
  24630. }
  24631. Object.defineProperty(Sprite.prototype, "size", {
  24632. get: function () {
  24633. return this.width;
  24634. },
  24635. set: function (value) {
  24636. this.width = value;
  24637. this.height = value;
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24643. this._fromIndex = from;
  24644. this._toIndex = to;
  24645. this._loopAnimation = loop;
  24646. this._delay = delay;
  24647. this._animationStarted = true;
  24648. this._direction = from < to ? 1 : -1;
  24649. this.cellIndex = from;
  24650. this._time = 0;
  24651. };
  24652. Sprite.prototype.stopAnimation = function () {
  24653. this._animationStarted = false;
  24654. };
  24655. Sprite.prototype._animate = function (deltaTime) {
  24656. if (!this._animationStarted)
  24657. return;
  24658. this._time += deltaTime;
  24659. if (this._time > this._delay) {
  24660. this._time = this._time % this._delay;
  24661. this.cellIndex += this._direction;
  24662. if (this.cellIndex == this._toIndex) {
  24663. if (this._loopAnimation) {
  24664. this.cellIndex = this._fromIndex;
  24665. }
  24666. else {
  24667. this._animationStarted = false;
  24668. if (this.disposeWhenFinishedAnimating) {
  24669. this.dispose();
  24670. }
  24671. }
  24672. }
  24673. }
  24674. };
  24675. Sprite.prototype.dispose = function () {
  24676. for (var i = 0; i < this._manager.sprites.length; i++) {
  24677. if (this._manager.sprites[i] == this) {
  24678. this._manager.sprites.splice(i, 1);
  24679. }
  24680. }
  24681. };
  24682. return Sprite;
  24683. })();
  24684. BABYLON.Sprite = Sprite;
  24685. })(BABYLON || (BABYLON = {}));
  24686. var BABYLON;
  24687. (function (BABYLON) {
  24688. var Layer = (function () {
  24689. function Layer(name, imgUrl, scene, isBackground, color) {
  24690. this.name = name;
  24691. this.scale = new BABYLON.Vector2(1, 1);
  24692. this.offset = new BABYLON.Vector2(0, 0);
  24693. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24694. this._vertexDeclaration = [2];
  24695. this._vertexStrideSize = 2 * 4;
  24696. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24697. this.isBackground = isBackground === undefined ? true : isBackground;
  24698. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24699. this._scene = scene;
  24700. this._scene.layers.push(this);
  24701. // VBO
  24702. var vertices = [];
  24703. vertices.push(1, 1);
  24704. vertices.push(-1, 1);
  24705. vertices.push(-1, -1);
  24706. vertices.push(1, -1);
  24707. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24708. // Indices
  24709. var indices = [];
  24710. indices.push(0);
  24711. indices.push(1);
  24712. indices.push(2);
  24713. indices.push(0);
  24714. indices.push(2);
  24715. indices.push(3);
  24716. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24717. // Effects
  24718. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24719. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24720. }
  24721. Layer.prototype.render = function () {
  24722. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24723. // Check
  24724. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24725. return;
  24726. var engine = this._scene.getEngine();
  24727. if (this.onBeforeRender) {
  24728. this.onBeforeRender();
  24729. }
  24730. // Render
  24731. engine.enableEffect(currentEffect);
  24732. engine.setState(false);
  24733. // Texture
  24734. currentEffect.setTexture("textureSampler", this.texture);
  24735. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24736. // Color
  24737. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24738. // Scale / offset
  24739. currentEffect.setVector2("offset", this.offset);
  24740. currentEffect.setVector2("scale", this.scale);
  24741. // VBOs
  24742. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24743. // Draw order
  24744. if (!this._alphaTestEffect) {
  24745. engine.setAlphaMode(this.alphaBlendingMode);
  24746. engine.draw(true, 0, 6);
  24747. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24748. }
  24749. else {
  24750. engine.draw(true, 0, 6);
  24751. }
  24752. if (this.onAfterRender) {
  24753. this.onAfterRender();
  24754. }
  24755. };
  24756. Layer.prototype.dispose = function () {
  24757. if (this._vertexBuffer) {
  24758. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24759. this._vertexBuffer = null;
  24760. }
  24761. if (this._indexBuffer) {
  24762. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24763. this._indexBuffer = null;
  24764. }
  24765. if (this.texture) {
  24766. this.texture.dispose();
  24767. this.texture = null;
  24768. }
  24769. // Remove from scene
  24770. var index = this._scene.layers.indexOf(this);
  24771. this._scene.layers.splice(index, 1);
  24772. // Callback
  24773. if (this.onDispose) {
  24774. this.onDispose();
  24775. }
  24776. };
  24777. return Layer;
  24778. })();
  24779. BABYLON.Layer = Layer;
  24780. })(BABYLON || (BABYLON = {}));
  24781. var BABYLON;
  24782. (function (BABYLON) {
  24783. var Particle = (function () {
  24784. function Particle() {
  24785. this.position = BABYLON.Vector3.Zero();
  24786. this.direction = BABYLON.Vector3.Zero();
  24787. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24788. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24789. this.lifeTime = 1.0;
  24790. this.age = 0;
  24791. this.size = 0;
  24792. this.angle = 0;
  24793. this.angularSpeed = 0;
  24794. }
  24795. Particle.prototype.copyTo = function (other) {
  24796. other.position.copyFrom(this.position);
  24797. other.direction.copyFrom(this.direction);
  24798. other.color.copyFrom(this.color);
  24799. other.colorStep.copyFrom(this.colorStep);
  24800. other.lifeTime = this.lifeTime;
  24801. other.age = this.age;
  24802. other.size = this.size;
  24803. other.angle = this.angle;
  24804. other.angularSpeed = this.angularSpeed;
  24805. };
  24806. return Particle;
  24807. })();
  24808. BABYLON.Particle = Particle;
  24809. })(BABYLON || (BABYLON = {}));
  24810. var BABYLON;
  24811. (function (BABYLON) {
  24812. var randomNumber = function (min, max) {
  24813. if (min === max) {
  24814. return (min);
  24815. }
  24816. var random = Math.random();
  24817. return ((random * (max - min)) + min);
  24818. };
  24819. var ParticleSystem = (function () {
  24820. function ParticleSystem(name, capacity, scene, customEffect) {
  24821. var _this = this;
  24822. this.name = name;
  24823. // Members
  24824. this.animations = [];
  24825. this.renderingGroupId = 0;
  24826. this.emitter = null;
  24827. this.emitRate = 10;
  24828. this.manualEmitCount = -1;
  24829. this.updateSpeed = 0.01;
  24830. this.targetStopDuration = 0;
  24831. this.disposeOnStop = false;
  24832. this.minEmitPower = 1;
  24833. this.maxEmitPower = 1;
  24834. this.minLifeTime = 1;
  24835. this.maxLifeTime = 1;
  24836. this.minSize = 1;
  24837. this.maxSize = 1;
  24838. this.minAngularSpeed = 0;
  24839. this.maxAngularSpeed = 0;
  24840. this.layerMask = 0x0FFFFFFF;
  24841. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24842. this.forceDepthWrite = false;
  24843. this.gravity = BABYLON.Vector3.Zero();
  24844. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24845. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24846. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24847. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24848. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24849. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24850. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24851. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24852. this.particles = new Array();
  24853. this._vertexDeclaration = [3, 4, 4];
  24854. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24855. this._stockParticles = new Array();
  24856. this._newPartsExcess = 0;
  24857. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24858. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24859. this._scaledDirection = BABYLON.Vector3.Zero();
  24860. this._scaledGravity = BABYLON.Vector3.Zero();
  24861. this._currentRenderId = -1;
  24862. this._started = false;
  24863. this._stopped = false;
  24864. this._actualFrame = 0;
  24865. this.id = name;
  24866. this._capacity = capacity;
  24867. this._scene = scene;
  24868. this._customEffect = customEffect;
  24869. scene.particleSystems.push(this);
  24870. // VBO
  24871. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24872. var indices = [];
  24873. var index = 0;
  24874. for (var count = 0; count < capacity; count++) {
  24875. indices.push(index);
  24876. indices.push(index + 1);
  24877. indices.push(index + 2);
  24878. indices.push(index);
  24879. indices.push(index + 2);
  24880. indices.push(index + 3);
  24881. index += 4;
  24882. }
  24883. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24884. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24885. // Default behaviors
  24886. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24887. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24888. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24889. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24890. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24891. };
  24892. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24893. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24894. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24895. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24896. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24897. };
  24898. this.updateFunction = function (particles) {
  24899. for (var index = 0; index < particles.length; index++) {
  24900. var particle = particles[index];
  24901. particle.age += _this._scaledUpdateSpeed;
  24902. if (particle.age >= particle.lifeTime) {
  24903. _this.recycleParticle(particle);
  24904. index--;
  24905. continue;
  24906. }
  24907. else {
  24908. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24909. particle.color.addInPlace(_this._scaledColorStep);
  24910. if (particle.color.a < 0)
  24911. particle.color.a = 0;
  24912. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24913. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24914. particle.position.addInPlace(_this._scaledDirection);
  24915. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24916. particle.direction.addInPlace(_this._scaledGravity);
  24917. }
  24918. }
  24919. };
  24920. }
  24921. ParticleSystem.prototype.recycleParticle = function (particle) {
  24922. var lastParticle = this.particles.pop();
  24923. if (lastParticle !== particle) {
  24924. lastParticle.copyTo(particle);
  24925. this._stockParticles.push(lastParticle);
  24926. }
  24927. };
  24928. ParticleSystem.prototype.getCapacity = function () {
  24929. return this._capacity;
  24930. };
  24931. ParticleSystem.prototype.isAlive = function () {
  24932. return this._alive;
  24933. };
  24934. ParticleSystem.prototype.isStarted = function () {
  24935. return this._started;
  24936. };
  24937. ParticleSystem.prototype.start = function () {
  24938. this._started = true;
  24939. this._stopped = false;
  24940. this._actualFrame = 0;
  24941. };
  24942. ParticleSystem.prototype.stop = function () {
  24943. this._stopped = true;
  24944. };
  24945. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24946. var offset = index * 11;
  24947. this._vertices[offset] = particle.position.x;
  24948. this._vertices[offset + 1] = particle.position.y;
  24949. this._vertices[offset + 2] = particle.position.z;
  24950. this._vertices[offset + 3] = particle.color.r;
  24951. this._vertices[offset + 4] = particle.color.g;
  24952. this._vertices[offset + 5] = particle.color.b;
  24953. this._vertices[offset + 6] = particle.color.a;
  24954. this._vertices[offset + 7] = particle.angle;
  24955. this._vertices[offset + 8] = particle.size;
  24956. this._vertices[offset + 9] = offsetX;
  24957. this._vertices[offset + 10] = offsetY;
  24958. };
  24959. ParticleSystem.prototype._update = function (newParticles) {
  24960. // Update current
  24961. this._alive = this.particles.length > 0;
  24962. this.updateFunction(this.particles);
  24963. // Add new ones
  24964. var worldMatrix;
  24965. if (this.emitter.position) {
  24966. worldMatrix = this.emitter.getWorldMatrix();
  24967. }
  24968. else {
  24969. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24970. }
  24971. var particle;
  24972. for (var index = 0; index < newParticles; index++) {
  24973. if (this.particles.length === this._capacity) {
  24974. break;
  24975. }
  24976. if (this._stockParticles.length !== 0) {
  24977. particle = this._stockParticles.pop();
  24978. particle.age = 0;
  24979. }
  24980. else {
  24981. particle = new BABYLON.Particle();
  24982. }
  24983. this.particles.push(particle);
  24984. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24985. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24986. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24987. particle.size = randomNumber(this.minSize, this.maxSize);
  24988. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24989. this.startPositionFunction(worldMatrix, particle.position, particle);
  24990. var step = randomNumber(0, 1.0);
  24991. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24992. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24993. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24994. }
  24995. };
  24996. ParticleSystem.prototype._getEffect = function () {
  24997. if (this._customEffect) {
  24998. return this._customEffect;
  24999. }
  25000. ;
  25001. var defines = [];
  25002. if (this._scene.clipPlane) {
  25003. defines.push("#define CLIPPLANE");
  25004. }
  25005. // Effect
  25006. var join = defines.join("\n");
  25007. if (this._cachedDefines !== join) {
  25008. this._cachedDefines = join;
  25009. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  25010. }
  25011. return this._effect;
  25012. };
  25013. ParticleSystem.prototype.animate = function () {
  25014. if (!this._started)
  25015. return;
  25016. var effect = this._getEffect();
  25017. // Check
  25018. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  25019. return;
  25020. if (this._currentRenderId === this._scene.getRenderId()) {
  25021. return;
  25022. }
  25023. this._currentRenderId = this._scene.getRenderId();
  25024. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  25025. // determine the number of particles we need to create
  25026. var newParticles;
  25027. if (this.manualEmitCount > -1) {
  25028. newParticles = this.manualEmitCount;
  25029. this._newPartsExcess = 0;
  25030. this.manualEmitCount = 0;
  25031. }
  25032. else {
  25033. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  25034. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  25035. }
  25036. if (this._newPartsExcess > 1.0) {
  25037. newParticles += this._newPartsExcess >> 0;
  25038. this._newPartsExcess -= this._newPartsExcess >> 0;
  25039. }
  25040. this._alive = false;
  25041. if (!this._stopped) {
  25042. this._actualFrame += this._scaledUpdateSpeed;
  25043. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  25044. this.stop();
  25045. }
  25046. else {
  25047. newParticles = 0;
  25048. }
  25049. this._update(newParticles);
  25050. // Stopped?
  25051. if (this._stopped) {
  25052. if (!this._alive) {
  25053. this._started = false;
  25054. if (this.disposeOnStop) {
  25055. this._scene._toBeDisposed.push(this);
  25056. }
  25057. }
  25058. }
  25059. // Update VBO
  25060. var offset = 0;
  25061. for (var index = 0; index < this.particles.length; index++) {
  25062. var particle = this.particles[index];
  25063. this._appendParticleVertex(offset++, particle, 0, 0);
  25064. this._appendParticleVertex(offset++, particle, 1, 0);
  25065. this._appendParticleVertex(offset++, particle, 1, 1);
  25066. this._appendParticleVertex(offset++, particle, 0, 1);
  25067. }
  25068. var engine = this._scene.getEngine();
  25069. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25070. };
  25071. ParticleSystem.prototype.render = function () {
  25072. var effect = this._getEffect();
  25073. // Check
  25074. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25075. return 0;
  25076. var engine = this._scene.getEngine();
  25077. // Render
  25078. engine.enableEffect(effect);
  25079. engine.setState(false);
  25080. var viewMatrix = this._scene.getViewMatrix();
  25081. effect.setTexture("diffuseSampler", this.particleTexture);
  25082. effect.setMatrix("view", viewMatrix);
  25083. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25084. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25085. if (this._scene.clipPlane) {
  25086. var clipPlane = this._scene.clipPlane;
  25087. var invView = viewMatrix.clone();
  25088. invView.invert();
  25089. effect.setMatrix("invView", invView);
  25090. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25091. }
  25092. // VBOs
  25093. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25094. // Draw order
  25095. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25096. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25097. }
  25098. else {
  25099. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25100. }
  25101. if (this.forceDepthWrite) {
  25102. engine.setDepthWrite(true);
  25103. }
  25104. engine.draw(true, 0, this.particles.length * 6);
  25105. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25106. return this.particles.length;
  25107. };
  25108. ParticleSystem.prototype.dispose = function () {
  25109. if (this._vertexBuffer) {
  25110. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25111. this._vertexBuffer = null;
  25112. }
  25113. if (this._indexBuffer) {
  25114. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25115. this._indexBuffer = null;
  25116. }
  25117. if (this.particleTexture) {
  25118. this.particleTexture.dispose();
  25119. this.particleTexture = null;
  25120. }
  25121. // Remove from scene
  25122. var index = this._scene.particleSystems.indexOf(this);
  25123. this._scene.particleSystems.splice(index, 1);
  25124. // Callback
  25125. if (this.onDispose) {
  25126. this.onDispose();
  25127. }
  25128. };
  25129. // Clone
  25130. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25131. var result = new ParticleSystem(name, this._capacity, this._scene);
  25132. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  25133. if (newEmitter === undefined) {
  25134. newEmitter = this.emitter;
  25135. }
  25136. result.emitter = newEmitter;
  25137. if (this.particleTexture) {
  25138. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25139. }
  25140. result.start();
  25141. return result;
  25142. };
  25143. ParticleSystem.prototype.serialize = function () {
  25144. var serializationObject = {};
  25145. serializationObject.name = this.name;
  25146. serializationObject.id = this.id;
  25147. // Emitter
  25148. if (this.emitter.position) {
  25149. serializationObject.emitterId = this.emitter.id;
  25150. }
  25151. else {
  25152. serializationObject.emitter = this.emitter.asArray();
  25153. }
  25154. serializationObject.capacity = this.getCapacity();
  25155. if (this.particleTexture) {
  25156. serializationObject.textureName = this.particleTexture.name;
  25157. }
  25158. // Animations
  25159. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25160. // Particle system
  25161. serializationObject.minAngularSpeed = this.minAngularSpeed;
  25162. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  25163. serializationObject.minSize = this.minSize;
  25164. serializationObject.maxSize = this.maxSize;
  25165. serializationObject.minEmitPower = this.minEmitPower;
  25166. serializationObject.maxEmitPower = this.maxEmitPower;
  25167. serializationObject.minLifeTime = this.minLifeTime;
  25168. serializationObject.maxLifeTime = this.maxLifeTime;
  25169. serializationObject.emitRate = this.emitRate;
  25170. serializationObject.minEmitBox = this.minEmitBox.asArray();
  25171. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  25172. serializationObject.gravity = this.gravity.asArray();
  25173. serializationObject.direction1 = this.direction1.asArray();
  25174. serializationObject.direction2 = this.direction2.asArray();
  25175. serializationObject.color1 = this.color1.asArray();
  25176. serializationObject.color2 = this.color2.asArray();
  25177. serializationObject.colorDead = this.colorDead.asArray();
  25178. serializationObject.updateSpeed = this.updateSpeed;
  25179. serializationObject.targetStopDuration = this.targetStopDuration;
  25180. serializationObject.textureMask = this.textureMask.asArray();
  25181. serializationObject.blendMode = this.blendMode;
  25182. return serializationObject;
  25183. };
  25184. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  25185. var name = parsedParticleSystem.name;
  25186. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  25187. if (parsedParticleSystem.id) {
  25188. particleSystem.id = parsedParticleSystem.id;
  25189. }
  25190. // Texture
  25191. if (parsedParticleSystem.textureName) {
  25192. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  25193. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  25194. }
  25195. // Emitter
  25196. if (parsedParticleSystem.emitterId) {
  25197. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  25198. }
  25199. else {
  25200. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  25201. }
  25202. // Animations
  25203. if (parsedParticleSystem.animations) {
  25204. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  25205. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  25206. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25207. }
  25208. }
  25209. if (parsedParticleSystem.autoAnimate) {
  25210. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  25211. }
  25212. // Particle system
  25213. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25214. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25215. particleSystem.minSize = parsedParticleSystem.minSize;
  25216. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25217. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25218. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25219. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25220. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25221. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25222. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25223. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25224. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25225. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25226. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25227. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25228. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25229. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25230. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25231. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25232. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25233. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25234. if (!parsedParticleSystem.preventAutoStart) {
  25235. particleSystem.start();
  25236. }
  25237. return particleSystem;
  25238. };
  25239. // Statics
  25240. ParticleSystem.BLENDMODE_ONEONE = 0;
  25241. ParticleSystem.BLENDMODE_STANDARD = 1;
  25242. return ParticleSystem;
  25243. })();
  25244. BABYLON.ParticleSystem = ParticleSystem;
  25245. })(BABYLON || (BABYLON = {}));
  25246. var BABYLON;
  25247. (function (BABYLON) {
  25248. var AnimationRange = (function () {
  25249. function AnimationRange(name, from, to) {
  25250. this.name = name;
  25251. this.from = from;
  25252. this.to = to;
  25253. }
  25254. AnimationRange.prototype.clone = function () {
  25255. return new AnimationRange(this.name, this.from, this.to);
  25256. };
  25257. return AnimationRange;
  25258. })();
  25259. BABYLON.AnimationRange = AnimationRange;
  25260. /**
  25261. * Composed of a frame, and an action function
  25262. */
  25263. var AnimationEvent = (function () {
  25264. function AnimationEvent(frame, action, onlyOnce) {
  25265. this.frame = frame;
  25266. this.action = action;
  25267. this.onlyOnce = onlyOnce;
  25268. this.isDone = false;
  25269. }
  25270. return AnimationEvent;
  25271. })();
  25272. BABYLON.AnimationEvent = AnimationEvent;
  25273. var PathCursor = (function () {
  25274. function PathCursor(path) {
  25275. this.path = path;
  25276. this._onchange = new Array();
  25277. this.value = 0;
  25278. this.animations = new Array();
  25279. }
  25280. PathCursor.prototype.getPoint = function () {
  25281. var point = this.path.getPointAtLengthPosition(this.value);
  25282. return new BABYLON.Vector3(point.x, 0, point.y);
  25283. };
  25284. PathCursor.prototype.moveAhead = function (step) {
  25285. if (step === void 0) { step = 0.002; }
  25286. this.move(step);
  25287. return this;
  25288. };
  25289. PathCursor.prototype.moveBack = function (step) {
  25290. if (step === void 0) { step = 0.002; }
  25291. this.move(-step);
  25292. return this;
  25293. };
  25294. PathCursor.prototype.move = function (step) {
  25295. if (Math.abs(step) > 1) {
  25296. throw "step size should be less than 1.";
  25297. }
  25298. this.value += step;
  25299. this.ensureLimits();
  25300. this.raiseOnChange();
  25301. return this;
  25302. };
  25303. PathCursor.prototype.ensureLimits = function () {
  25304. while (this.value > 1) {
  25305. this.value -= 1;
  25306. }
  25307. while (this.value < 0) {
  25308. this.value += 1;
  25309. }
  25310. return this;
  25311. };
  25312. // used by animation engine
  25313. PathCursor.prototype.markAsDirty = function (propertyName) {
  25314. this.ensureLimits();
  25315. this.raiseOnChange();
  25316. return this;
  25317. };
  25318. PathCursor.prototype.raiseOnChange = function () {
  25319. var _this = this;
  25320. this._onchange.forEach(function (f) { return f(_this); });
  25321. return this;
  25322. };
  25323. PathCursor.prototype.onchange = function (f) {
  25324. this._onchange.push(f);
  25325. return this;
  25326. };
  25327. return PathCursor;
  25328. })();
  25329. BABYLON.PathCursor = PathCursor;
  25330. var Animation = (function () {
  25331. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25332. this.name = name;
  25333. this.targetProperty = targetProperty;
  25334. this.framePerSecond = framePerSecond;
  25335. this.dataType = dataType;
  25336. this.loopMode = loopMode;
  25337. this.enableBlending = enableBlending;
  25338. this._offsetsCache = {};
  25339. this._highLimitsCache = {};
  25340. this._stopped = false;
  25341. this._blendingFactor = 0;
  25342. // The set of event that will be linked to this animation
  25343. this._events = new Array();
  25344. this.allowMatricesInterpolation = false;
  25345. this.blendingSpeed = 0.01;
  25346. this._ranges = {};
  25347. this.targetPropertyPath = targetProperty.split(".");
  25348. this.dataType = dataType;
  25349. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25350. }
  25351. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25352. var dataType = undefined;
  25353. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25354. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25355. }
  25356. else if (from instanceof BABYLON.Quaternion) {
  25357. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25358. }
  25359. else if (from instanceof BABYLON.Vector3) {
  25360. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25361. }
  25362. else if (from instanceof BABYLON.Vector2) {
  25363. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25364. }
  25365. else if (from instanceof BABYLON.Color3) {
  25366. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25367. }
  25368. if (dataType == undefined) {
  25369. return null;
  25370. }
  25371. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25372. var keys = [];
  25373. keys.push({ frame: 0, value: from });
  25374. keys.push({ frame: totalFrame, value: to });
  25375. animation.setKeys(keys);
  25376. if (easingFunction !== undefined) {
  25377. animation.setEasingFunction(easingFunction);
  25378. }
  25379. return animation;
  25380. };
  25381. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25382. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25383. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25384. };
  25385. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25386. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25387. node.animations.push(animation);
  25388. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25389. };
  25390. // Methods
  25391. /**
  25392. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25393. */
  25394. Animation.prototype.toString = function (fullDetails) {
  25395. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25396. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25397. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25398. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25399. if (fullDetails) {
  25400. ret += ", Ranges: {";
  25401. var first = true;
  25402. for (var name in this._ranges) {
  25403. if (first) {
  25404. ret += ", ";
  25405. first = false;
  25406. }
  25407. ret += name;
  25408. }
  25409. ret += "}";
  25410. }
  25411. return ret;
  25412. };
  25413. /**
  25414. * Add an event to this animation.
  25415. */
  25416. Animation.prototype.addEvent = function (event) {
  25417. this._events.push(event);
  25418. };
  25419. /**
  25420. * Remove all events found at the given frame
  25421. * @param frame
  25422. */
  25423. Animation.prototype.removeEvents = function (frame) {
  25424. for (var index = 0; index < this._events.length; index++) {
  25425. if (this._events[index].frame === frame) {
  25426. this._events.splice(index, 1);
  25427. index--;
  25428. }
  25429. }
  25430. };
  25431. Animation.prototype.createRange = function (name, from, to) {
  25432. // check name not already in use; could happen for bones after serialized
  25433. if (!this._ranges[name]) {
  25434. this._ranges[name] = new AnimationRange(name, from, to);
  25435. }
  25436. };
  25437. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25438. if (deleteFrames === void 0) { deleteFrames = true; }
  25439. if (this._ranges[name]) {
  25440. if (deleteFrames) {
  25441. var from = this._ranges[name].from;
  25442. var to = this._ranges[name].to;
  25443. // this loop MUST go high to low for multiple splices to work
  25444. for (var key = this._keys.length - 1; key >= 0; key--) {
  25445. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25446. this._keys.splice(key, 1);
  25447. }
  25448. }
  25449. }
  25450. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25451. }
  25452. };
  25453. Animation.prototype.getRange = function (name) {
  25454. return this._ranges[name];
  25455. };
  25456. Animation.prototype.reset = function () {
  25457. this._offsetsCache = {};
  25458. this._highLimitsCache = {};
  25459. this.currentFrame = 0;
  25460. this._blendingFactor = 0;
  25461. this._originalBlendValue = null;
  25462. };
  25463. Animation.prototype.isStopped = function () {
  25464. return this._stopped;
  25465. };
  25466. Animation.prototype.getKeys = function () {
  25467. return this._keys;
  25468. };
  25469. Animation.prototype.getHighestFrame = function () {
  25470. var ret = 0;
  25471. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25472. if (ret < this._keys[key].frame) {
  25473. ret = this._keys[key].frame;
  25474. }
  25475. }
  25476. return ret;
  25477. };
  25478. Animation.prototype.getEasingFunction = function () {
  25479. return this._easingFunction;
  25480. };
  25481. Animation.prototype.setEasingFunction = function (easingFunction) {
  25482. this._easingFunction = easingFunction;
  25483. };
  25484. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25485. return startValue + (endValue - startValue) * gradient;
  25486. };
  25487. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25488. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25489. };
  25490. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25491. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25492. };
  25493. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25494. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25495. };
  25496. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25497. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25498. };
  25499. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25500. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25501. };
  25502. Animation.prototype.clone = function () {
  25503. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25504. if (this._keys) {
  25505. clone.setKeys(this._keys);
  25506. }
  25507. if (this._ranges) {
  25508. clone._ranges = {};
  25509. for (var name in this._ranges) {
  25510. clone._ranges[name] = this._ranges[name].clone();
  25511. }
  25512. }
  25513. return clone;
  25514. };
  25515. Animation.prototype.setKeys = function (values) {
  25516. this._keys = values.slice(0);
  25517. this._offsetsCache = {};
  25518. this._highLimitsCache = {};
  25519. };
  25520. Animation.prototype._getKeyValue = function (value) {
  25521. if (typeof value === "function") {
  25522. return value();
  25523. }
  25524. return value;
  25525. };
  25526. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25527. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25528. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25529. }
  25530. this.currentFrame = currentFrame;
  25531. // Try to get a hash to find the right key
  25532. 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));
  25533. if (this._keys[startKey].frame >= currentFrame) {
  25534. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25535. startKey--;
  25536. }
  25537. }
  25538. for (var key = startKey; key < this._keys.length; key++) {
  25539. if (this._keys[key + 1].frame >= currentFrame) {
  25540. var startValue = this._getKeyValue(this._keys[key].value);
  25541. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25542. // gradient : percent of currentFrame between the frame inf and the frame sup
  25543. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25544. // check for easingFunction and correction of gradient
  25545. if (this._easingFunction != null) {
  25546. gradient = this._easingFunction.ease(gradient);
  25547. }
  25548. switch (this.dataType) {
  25549. // Float
  25550. case Animation.ANIMATIONTYPE_FLOAT:
  25551. switch (loopMode) {
  25552. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25553. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25554. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25555. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25556. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25557. }
  25558. break;
  25559. // Quaternion
  25560. case Animation.ANIMATIONTYPE_QUATERNION:
  25561. var quaternion = null;
  25562. switch (loopMode) {
  25563. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25564. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25565. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25566. break;
  25567. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25568. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25569. break;
  25570. }
  25571. return quaternion;
  25572. // Vector3
  25573. case Animation.ANIMATIONTYPE_VECTOR3:
  25574. switch (loopMode) {
  25575. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25576. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25577. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25578. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25579. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25580. }
  25581. // Vector2
  25582. case Animation.ANIMATIONTYPE_VECTOR2:
  25583. switch (loopMode) {
  25584. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25585. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25586. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25587. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25588. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25589. }
  25590. // Color3
  25591. case Animation.ANIMATIONTYPE_COLOR3:
  25592. switch (loopMode) {
  25593. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25594. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25595. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25596. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25597. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25598. }
  25599. // Matrix
  25600. case Animation.ANIMATIONTYPE_MATRIX:
  25601. switch (loopMode) {
  25602. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25603. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25604. if (this.allowMatricesInterpolation) {
  25605. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25606. }
  25607. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25608. return startValue;
  25609. }
  25610. default:
  25611. break;
  25612. }
  25613. break;
  25614. }
  25615. }
  25616. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25617. };
  25618. Animation.prototype.setValue = function (currentValue, blend) {
  25619. if (blend === void 0) { blend = false; }
  25620. // Set value
  25621. var path;
  25622. var destination;
  25623. if (this.targetPropertyPath.length > 1) {
  25624. var property = this._target[this.targetPropertyPath[0]];
  25625. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25626. property = property[this.targetPropertyPath[index]];
  25627. }
  25628. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25629. destination = property;
  25630. }
  25631. else {
  25632. path = this.targetPropertyPath[0];
  25633. destination = this._target;
  25634. }
  25635. // Blending
  25636. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25637. if (!this._originalBlendValue) {
  25638. if (destination[path].clone) {
  25639. this._originalBlendValue = destination[path].clone();
  25640. }
  25641. else {
  25642. this._originalBlendValue = destination[path];
  25643. }
  25644. }
  25645. if (this._originalBlendValue.prototype) {
  25646. if (this._originalBlendValue.prototype.Lerp) {
  25647. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25648. }
  25649. else {
  25650. destination[path] = currentValue;
  25651. }
  25652. }
  25653. else if (this._originalBlendValue.m) {
  25654. destination[path] = BABYLON.Matrix.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25655. }
  25656. else {
  25657. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25658. }
  25659. this._blendingFactor += this.blendingSpeed;
  25660. }
  25661. else {
  25662. destination[path] = currentValue;
  25663. }
  25664. if (this._target.markAsDirty) {
  25665. this._target.markAsDirty(this.targetProperty);
  25666. }
  25667. };
  25668. Animation.prototype.goToFrame = function (frame) {
  25669. if (frame < this._keys[0].frame) {
  25670. frame = this._keys[0].frame;
  25671. }
  25672. else if (frame > this._keys[this._keys.length - 1].frame) {
  25673. frame = this._keys[this._keys.length - 1].frame;
  25674. }
  25675. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25676. this.setValue(currentValue);
  25677. };
  25678. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25679. if (blend === void 0) { blend = false; }
  25680. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25681. this._stopped = true;
  25682. return false;
  25683. }
  25684. var returnValue = true;
  25685. // Adding a start key at frame 0 if missing
  25686. if (this._keys[0].frame !== 0) {
  25687. var newKey = { frame: 0, value: this._keys[0].value };
  25688. this._keys.splice(0, 0, newKey);
  25689. }
  25690. // Check limits
  25691. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25692. from = this._keys[0].frame;
  25693. }
  25694. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25695. to = this._keys[this._keys.length - 1].frame;
  25696. }
  25697. // Compute ratio
  25698. var range = to - from;
  25699. var offsetValue;
  25700. // ratio represents the frame delta between from and to
  25701. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25702. var highLimitValue = 0;
  25703. if (ratio > range && !loop) {
  25704. returnValue = false;
  25705. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25706. }
  25707. else {
  25708. // Get max value if required
  25709. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25710. var keyOffset = to.toString() + from.toString();
  25711. if (!this._offsetsCache[keyOffset]) {
  25712. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25713. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25714. switch (this.dataType) {
  25715. // Float
  25716. case Animation.ANIMATIONTYPE_FLOAT:
  25717. this._offsetsCache[keyOffset] = toValue - fromValue;
  25718. break;
  25719. // Quaternion
  25720. case Animation.ANIMATIONTYPE_QUATERNION:
  25721. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25722. break;
  25723. // Vector3
  25724. case Animation.ANIMATIONTYPE_VECTOR3:
  25725. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25726. // Vector2
  25727. case Animation.ANIMATIONTYPE_VECTOR2:
  25728. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25729. // Color3
  25730. case Animation.ANIMATIONTYPE_COLOR3:
  25731. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25732. default:
  25733. break;
  25734. }
  25735. this._highLimitsCache[keyOffset] = toValue;
  25736. }
  25737. highLimitValue = this._highLimitsCache[keyOffset];
  25738. offsetValue = this._offsetsCache[keyOffset];
  25739. }
  25740. }
  25741. if (offsetValue === undefined) {
  25742. switch (this.dataType) {
  25743. // Float
  25744. case Animation.ANIMATIONTYPE_FLOAT:
  25745. offsetValue = 0;
  25746. break;
  25747. // Quaternion
  25748. case Animation.ANIMATIONTYPE_QUATERNION:
  25749. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25750. break;
  25751. // Vector3
  25752. case Animation.ANIMATIONTYPE_VECTOR3:
  25753. offsetValue = BABYLON.Vector3.Zero();
  25754. break;
  25755. // Vector2
  25756. case Animation.ANIMATIONTYPE_VECTOR2:
  25757. offsetValue = BABYLON.Vector2.Zero();
  25758. break;
  25759. // Color3
  25760. case Animation.ANIMATIONTYPE_COLOR3:
  25761. offsetValue = BABYLON.Color3.Black();
  25762. }
  25763. }
  25764. // Compute value
  25765. var repeatCount = (ratio / range) >> 0;
  25766. var currentFrame = returnValue ? from + ratio % range : to;
  25767. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25768. // Set value
  25769. this.setValue(currentValue);
  25770. // Check events
  25771. for (var index = 0; index < this._events.length; index++) {
  25772. if (currentFrame >= this._events[index].frame) {
  25773. var event = this._events[index];
  25774. if (!event.isDone) {
  25775. // If event should be done only once, remove it.
  25776. if (event.onlyOnce) {
  25777. this._events.splice(index, 1);
  25778. index--;
  25779. }
  25780. event.isDone = true;
  25781. event.action();
  25782. } // Don't do anything if the event has already be done.
  25783. }
  25784. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25785. // reset event, the animation is looping
  25786. this._events[index].isDone = false;
  25787. }
  25788. }
  25789. if (!returnValue) {
  25790. this._stopped = true;
  25791. }
  25792. return returnValue;
  25793. };
  25794. Animation.prototype.serialize = function () {
  25795. var serializationObject = {};
  25796. serializationObject.name = this.name;
  25797. serializationObject.property = this.targetProperty;
  25798. serializationObject.framePerSecond = this.framePerSecond;
  25799. serializationObject.dataType = this.dataType;
  25800. serializationObject.loopBehavior = this.loopMode;
  25801. var dataType = this.dataType;
  25802. serializationObject.keys = [];
  25803. var keys = this.getKeys();
  25804. for (var index = 0; index < keys.length; index++) {
  25805. var animationKey = keys[index];
  25806. var key = {};
  25807. key.frame = animationKey.frame;
  25808. switch (dataType) {
  25809. case Animation.ANIMATIONTYPE_FLOAT:
  25810. key.values = [animationKey.value];
  25811. break;
  25812. case Animation.ANIMATIONTYPE_QUATERNION:
  25813. case Animation.ANIMATIONTYPE_MATRIX:
  25814. case Animation.ANIMATIONTYPE_VECTOR3:
  25815. case Animation.ANIMATIONTYPE_COLOR3:
  25816. key.values = animationKey.value.asArray();
  25817. break;
  25818. }
  25819. serializationObject.keys.push(key);
  25820. }
  25821. serializationObject.ranges = [];
  25822. for (var name in this._ranges) {
  25823. var range = {};
  25824. range.name = name;
  25825. range.from = this._ranges[name].from;
  25826. range.to = this._ranges[name].to;
  25827. serializationObject.ranges.push(range);
  25828. }
  25829. return serializationObject;
  25830. };
  25831. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25832. get: function () {
  25833. return Animation._ANIMATIONTYPE_FLOAT;
  25834. },
  25835. enumerable: true,
  25836. configurable: true
  25837. });
  25838. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25839. get: function () {
  25840. return Animation._ANIMATIONTYPE_VECTOR3;
  25841. },
  25842. enumerable: true,
  25843. configurable: true
  25844. });
  25845. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25846. get: function () {
  25847. return Animation._ANIMATIONTYPE_VECTOR2;
  25848. },
  25849. enumerable: true,
  25850. configurable: true
  25851. });
  25852. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25853. get: function () {
  25854. return Animation._ANIMATIONTYPE_QUATERNION;
  25855. },
  25856. enumerable: true,
  25857. configurable: true
  25858. });
  25859. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25860. get: function () {
  25861. return Animation._ANIMATIONTYPE_MATRIX;
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25867. get: function () {
  25868. return Animation._ANIMATIONTYPE_COLOR3;
  25869. },
  25870. enumerable: true,
  25871. configurable: true
  25872. });
  25873. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25874. get: function () {
  25875. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25881. get: function () {
  25882. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25883. },
  25884. enumerable: true,
  25885. configurable: true
  25886. });
  25887. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25888. get: function () {
  25889. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25890. },
  25891. enumerable: true,
  25892. configurable: true
  25893. });
  25894. Animation.Parse = function (parsedAnimation) {
  25895. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25896. var dataType = parsedAnimation.dataType;
  25897. var keys = [];
  25898. var data;
  25899. var index;
  25900. for (index = 0; index < parsedAnimation.keys.length; index++) {
  25901. var key = parsedAnimation.keys[index];
  25902. switch (dataType) {
  25903. case Animation.ANIMATIONTYPE_FLOAT:
  25904. data = key.values[0];
  25905. break;
  25906. case Animation.ANIMATIONTYPE_QUATERNION:
  25907. data = BABYLON.Quaternion.FromArray(key.values);
  25908. break;
  25909. case Animation.ANIMATIONTYPE_MATRIX:
  25910. data = BABYLON.Matrix.FromArray(key.values);
  25911. break;
  25912. case Animation.ANIMATIONTYPE_COLOR3:
  25913. data = BABYLON.Color3.FromArray(key.values);
  25914. break;
  25915. case Animation.ANIMATIONTYPE_VECTOR3:
  25916. default:
  25917. data = BABYLON.Vector3.FromArray(key.values);
  25918. break;
  25919. }
  25920. keys.push({
  25921. frame: key.frame,
  25922. value: data
  25923. });
  25924. }
  25925. animation.setKeys(keys);
  25926. if (parsedAnimation.ranges) {
  25927. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  25928. data = parsedAnimation.ranges[index];
  25929. animation.createRange(data.name, data.from, data.to);
  25930. }
  25931. }
  25932. return animation;
  25933. };
  25934. Animation.AppendSerializedAnimations = function (source, destination) {
  25935. if (source.animations) {
  25936. destination.animations = [];
  25937. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25938. var animation = source.animations[animationIndex];
  25939. destination.animations.push(animation.serialize());
  25940. }
  25941. }
  25942. };
  25943. // Statics
  25944. Animation._ANIMATIONTYPE_FLOAT = 0;
  25945. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25946. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25947. Animation._ANIMATIONTYPE_MATRIX = 3;
  25948. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25949. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25950. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25951. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25952. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25953. return Animation;
  25954. })();
  25955. BABYLON.Animation = Animation;
  25956. })(BABYLON || (BABYLON = {}));
  25957. var BABYLON;
  25958. (function (BABYLON) {
  25959. var Animatable = (function () {
  25960. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25961. if (fromFrame === void 0) { fromFrame = 0; }
  25962. if (toFrame === void 0) { toFrame = 100; }
  25963. if (loopAnimation === void 0) { loopAnimation = false; }
  25964. if (speedRatio === void 0) { speedRatio = 1.0; }
  25965. this.target = target;
  25966. this.fromFrame = fromFrame;
  25967. this.toFrame = toFrame;
  25968. this.loopAnimation = loopAnimation;
  25969. this.speedRatio = speedRatio;
  25970. this.onAnimationEnd = onAnimationEnd;
  25971. this._animations = new Array();
  25972. this._paused = false;
  25973. this.animationStarted = false;
  25974. if (animations) {
  25975. this.appendAnimations(target, animations);
  25976. }
  25977. this._scene = scene;
  25978. scene._activeAnimatables.push(this);
  25979. }
  25980. // Methods
  25981. Animatable.prototype.getAnimations = function () {
  25982. return this._animations;
  25983. };
  25984. Animatable.prototype.appendAnimations = function (target, animations) {
  25985. for (var index = 0; index < animations.length; index++) {
  25986. var animation = animations[index];
  25987. animation._target = target;
  25988. this._animations.push(animation);
  25989. }
  25990. };
  25991. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25992. var animations = this._animations;
  25993. for (var index = 0; index < animations.length; index++) {
  25994. if (animations[index].targetProperty === property) {
  25995. return animations[index];
  25996. }
  25997. }
  25998. return null;
  25999. };
  26000. Animatable.prototype.reset = function () {
  26001. var animations = this._animations;
  26002. for (var index = 0; index < animations.length; index++) {
  26003. animations[index].reset();
  26004. }
  26005. this._localDelayOffset = null;
  26006. this._pausedDelay = null;
  26007. };
  26008. Animatable.prototype.enableBlending = function (blendingSpeed) {
  26009. var animations = this._animations;
  26010. for (var index = 0; index < animations.length; index++) {
  26011. animations[index].enableBlending = true;
  26012. animations[index].blendingSpeed = blendingSpeed;
  26013. }
  26014. };
  26015. Animatable.prototype.disableBlending = function () {
  26016. var animations = this._animations;
  26017. for (var index = 0; index < animations.length; index++) {
  26018. animations[index].enableBlending = false;
  26019. }
  26020. };
  26021. Animatable.prototype.goToFrame = function (frame) {
  26022. var animations = this._animations;
  26023. for (var index = 0; index < animations.length; index++) {
  26024. animations[index].goToFrame(frame);
  26025. }
  26026. };
  26027. Animatable.prototype.pause = function () {
  26028. if (this._paused) {
  26029. return;
  26030. }
  26031. this._paused = true;
  26032. };
  26033. Animatable.prototype.restart = function () {
  26034. this._paused = false;
  26035. };
  26036. Animatable.prototype.stop = function () {
  26037. var index = this._scene._activeAnimatables.indexOf(this);
  26038. if (index > -1) {
  26039. this._scene._activeAnimatables.splice(index, 1);
  26040. var animations = this._animations;
  26041. for (var index = 0; index < animations.length; index++) {
  26042. animations[index].reset();
  26043. }
  26044. if (this.onAnimationEnd) {
  26045. this.onAnimationEnd();
  26046. }
  26047. }
  26048. };
  26049. Animatable.prototype._animate = function (delay) {
  26050. if (this._paused) {
  26051. this.animationStarted = false;
  26052. if (!this._pausedDelay) {
  26053. this._pausedDelay = delay;
  26054. }
  26055. return true;
  26056. }
  26057. if (!this._localDelayOffset) {
  26058. this._localDelayOffset = delay;
  26059. }
  26060. else if (this._pausedDelay) {
  26061. this._localDelayOffset += delay - this._pausedDelay;
  26062. this._pausedDelay = null;
  26063. }
  26064. // Animating
  26065. var running = false;
  26066. var animations = this._animations;
  26067. var index;
  26068. for (index = 0; index < animations.length; index++) {
  26069. var animation = animations[index];
  26070. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  26071. running = running || isRunning;
  26072. }
  26073. this.animationStarted = running;
  26074. if (!running) {
  26075. // Remove from active animatables
  26076. index = this._scene._activeAnimatables.indexOf(this);
  26077. this._scene._activeAnimatables.splice(index, 1);
  26078. }
  26079. if (!running && this.onAnimationEnd) {
  26080. this.onAnimationEnd();
  26081. this.onAnimationEnd = null;
  26082. }
  26083. return running;
  26084. };
  26085. return Animatable;
  26086. })();
  26087. BABYLON.Animatable = Animatable;
  26088. })(BABYLON || (BABYLON = {}));
  26089. var BABYLON;
  26090. (function (BABYLON) {
  26091. var EasingFunction = (function () {
  26092. function EasingFunction() {
  26093. // Properties
  26094. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26095. }
  26096. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26097. get: function () {
  26098. return EasingFunction._EASINGMODE_EASEIN;
  26099. },
  26100. enumerable: true,
  26101. configurable: true
  26102. });
  26103. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26104. get: function () {
  26105. return EasingFunction._EASINGMODE_EASEOUT;
  26106. },
  26107. enumerable: true,
  26108. configurable: true
  26109. });
  26110. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26111. get: function () {
  26112. return EasingFunction._EASINGMODE_EASEINOUT;
  26113. },
  26114. enumerable: true,
  26115. configurable: true
  26116. });
  26117. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26118. var n = Math.min(Math.max(easingMode, 0), 2);
  26119. this._easingMode = n;
  26120. };
  26121. EasingFunction.prototype.getEasingMode = function () {
  26122. return this._easingMode;
  26123. };
  26124. EasingFunction.prototype.easeInCore = function (gradient) {
  26125. throw new Error('You must implement this method');
  26126. };
  26127. EasingFunction.prototype.ease = function (gradient) {
  26128. switch (this._easingMode) {
  26129. case EasingFunction.EASINGMODE_EASEIN:
  26130. return this.easeInCore(gradient);
  26131. case EasingFunction.EASINGMODE_EASEOUT:
  26132. return (1 - this.easeInCore(1 - gradient));
  26133. }
  26134. if (gradient >= 0.5) {
  26135. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  26136. }
  26137. return (this.easeInCore(gradient * 2) * 0.5);
  26138. };
  26139. //Statics
  26140. EasingFunction._EASINGMODE_EASEIN = 0;
  26141. EasingFunction._EASINGMODE_EASEOUT = 1;
  26142. EasingFunction._EASINGMODE_EASEINOUT = 2;
  26143. return EasingFunction;
  26144. })();
  26145. BABYLON.EasingFunction = EasingFunction;
  26146. var CircleEase = (function (_super) {
  26147. __extends(CircleEase, _super);
  26148. function CircleEase() {
  26149. _super.apply(this, arguments);
  26150. }
  26151. CircleEase.prototype.easeInCore = function (gradient) {
  26152. gradient = Math.max(0, Math.min(1, gradient));
  26153. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  26154. };
  26155. return CircleEase;
  26156. })(EasingFunction);
  26157. BABYLON.CircleEase = CircleEase;
  26158. var BackEase = (function (_super) {
  26159. __extends(BackEase, _super);
  26160. function BackEase(amplitude) {
  26161. if (amplitude === void 0) { amplitude = 1; }
  26162. _super.call(this);
  26163. this.amplitude = amplitude;
  26164. }
  26165. BackEase.prototype.easeInCore = function (gradient) {
  26166. var num = Math.max(0, this.amplitude);
  26167. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  26168. };
  26169. return BackEase;
  26170. })(EasingFunction);
  26171. BABYLON.BackEase = BackEase;
  26172. var BounceEase = (function (_super) {
  26173. __extends(BounceEase, _super);
  26174. function BounceEase(bounces, bounciness) {
  26175. if (bounces === void 0) { bounces = 3; }
  26176. if (bounciness === void 0) { bounciness = 2; }
  26177. _super.call(this);
  26178. this.bounces = bounces;
  26179. this.bounciness = bounciness;
  26180. }
  26181. BounceEase.prototype.easeInCore = function (gradient) {
  26182. var y = Math.max(0.0, this.bounces);
  26183. var bounciness = this.bounciness;
  26184. if (bounciness <= 1.0) {
  26185. bounciness = 1.001;
  26186. }
  26187. var num9 = Math.pow(bounciness, y);
  26188. var num5 = 1.0 - bounciness;
  26189. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  26190. var num15 = gradient * num4;
  26191. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  26192. var num3 = Math.floor(num65);
  26193. var num13 = num3 + 1.0;
  26194. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  26195. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  26196. var num7 = (num8 + num12) * 0.5;
  26197. var num6 = gradient - num7;
  26198. var num2 = num7 - num8;
  26199. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  26200. };
  26201. return BounceEase;
  26202. })(EasingFunction);
  26203. BABYLON.BounceEase = BounceEase;
  26204. var CubicEase = (function (_super) {
  26205. __extends(CubicEase, _super);
  26206. function CubicEase() {
  26207. _super.apply(this, arguments);
  26208. }
  26209. CubicEase.prototype.easeInCore = function (gradient) {
  26210. return (gradient * gradient * gradient);
  26211. };
  26212. return CubicEase;
  26213. })(EasingFunction);
  26214. BABYLON.CubicEase = CubicEase;
  26215. var ElasticEase = (function (_super) {
  26216. __extends(ElasticEase, _super);
  26217. function ElasticEase(oscillations, springiness) {
  26218. if (oscillations === void 0) { oscillations = 3; }
  26219. if (springiness === void 0) { springiness = 3; }
  26220. _super.call(this);
  26221. this.oscillations = oscillations;
  26222. this.springiness = springiness;
  26223. }
  26224. ElasticEase.prototype.easeInCore = function (gradient) {
  26225. var num2;
  26226. var num3 = Math.max(0.0, this.oscillations);
  26227. var num = Math.max(0.0, this.springiness);
  26228. if (num == 0) {
  26229. num2 = gradient;
  26230. }
  26231. else {
  26232. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26233. }
  26234. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26235. };
  26236. return ElasticEase;
  26237. })(EasingFunction);
  26238. BABYLON.ElasticEase = ElasticEase;
  26239. var ExponentialEase = (function (_super) {
  26240. __extends(ExponentialEase, _super);
  26241. function ExponentialEase(exponent) {
  26242. if (exponent === void 0) { exponent = 2; }
  26243. _super.call(this);
  26244. this.exponent = exponent;
  26245. }
  26246. ExponentialEase.prototype.easeInCore = function (gradient) {
  26247. if (this.exponent <= 0) {
  26248. return gradient;
  26249. }
  26250. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26251. };
  26252. return ExponentialEase;
  26253. })(EasingFunction);
  26254. BABYLON.ExponentialEase = ExponentialEase;
  26255. var PowerEase = (function (_super) {
  26256. __extends(PowerEase, _super);
  26257. function PowerEase(power) {
  26258. if (power === void 0) { power = 2; }
  26259. _super.call(this);
  26260. this.power = power;
  26261. }
  26262. PowerEase.prototype.easeInCore = function (gradient) {
  26263. var y = Math.max(0.0, this.power);
  26264. return Math.pow(gradient, y);
  26265. };
  26266. return PowerEase;
  26267. })(EasingFunction);
  26268. BABYLON.PowerEase = PowerEase;
  26269. var QuadraticEase = (function (_super) {
  26270. __extends(QuadraticEase, _super);
  26271. function QuadraticEase() {
  26272. _super.apply(this, arguments);
  26273. }
  26274. QuadraticEase.prototype.easeInCore = function (gradient) {
  26275. return (gradient * gradient);
  26276. };
  26277. return QuadraticEase;
  26278. })(EasingFunction);
  26279. BABYLON.QuadraticEase = QuadraticEase;
  26280. var QuarticEase = (function (_super) {
  26281. __extends(QuarticEase, _super);
  26282. function QuarticEase() {
  26283. _super.apply(this, arguments);
  26284. }
  26285. QuarticEase.prototype.easeInCore = function (gradient) {
  26286. return (gradient * gradient * gradient * gradient);
  26287. };
  26288. return QuarticEase;
  26289. })(EasingFunction);
  26290. BABYLON.QuarticEase = QuarticEase;
  26291. var QuinticEase = (function (_super) {
  26292. __extends(QuinticEase, _super);
  26293. function QuinticEase() {
  26294. _super.apply(this, arguments);
  26295. }
  26296. QuinticEase.prototype.easeInCore = function (gradient) {
  26297. return (gradient * gradient * gradient * gradient * gradient);
  26298. };
  26299. return QuinticEase;
  26300. })(EasingFunction);
  26301. BABYLON.QuinticEase = QuinticEase;
  26302. var SineEase = (function (_super) {
  26303. __extends(SineEase, _super);
  26304. function SineEase() {
  26305. _super.apply(this, arguments);
  26306. }
  26307. SineEase.prototype.easeInCore = function (gradient) {
  26308. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26309. };
  26310. return SineEase;
  26311. })(EasingFunction);
  26312. BABYLON.SineEase = SineEase;
  26313. var BezierCurveEase = (function (_super) {
  26314. __extends(BezierCurveEase, _super);
  26315. function BezierCurveEase(x1, y1, x2, y2) {
  26316. if (x1 === void 0) { x1 = 0; }
  26317. if (y1 === void 0) { y1 = 0; }
  26318. if (x2 === void 0) { x2 = 1; }
  26319. if (y2 === void 0) { y2 = 1; }
  26320. _super.call(this);
  26321. this.x1 = x1;
  26322. this.y1 = y1;
  26323. this.x2 = x2;
  26324. this.y2 = y2;
  26325. }
  26326. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26327. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26328. };
  26329. return BezierCurveEase;
  26330. })(EasingFunction);
  26331. BABYLON.BezierCurveEase = BezierCurveEase;
  26332. })(BABYLON || (BABYLON = {}));
  26333. var BABYLON;
  26334. (function (BABYLON) {
  26335. var Bone = (function (_super) {
  26336. __extends(Bone, _super);
  26337. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26338. _super.call(this, name, skeleton.getScene());
  26339. this.name = name;
  26340. this.children = new Array();
  26341. this.animations = new Array();
  26342. this._worldTransform = new BABYLON.Matrix();
  26343. this._absoluteTransform = new BABYLON.Matrix();
  26344. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26345. this._skeleton = skeleton;
  26346. this._matrix = matrix;
  26347. this._baseMatrix = matrix;
  26348. this._restPose = restPose ? restPose : matrix.clone();
  26349. skeleton.bones.push(this);
  26350. if (parentBone) {
  26351. this._parent = parentBone;
  26352. parentBone.children.push(this);
  26353. }
  26354. else {
  26355. this._parent = null;
  26356. }
  26357. this._updateDifferenceMatrix();
  26358. }
  26359. // Members
  26360. Bone.prototype.getParent = function () {
  26361. return this._parent;
  26362. };
  26363. Bone.prototype.getLocalMatrix = function () {
  26364. return this._matrix;
  26365. };
  26366. Bone.prototype.getBaseMatrix = function () {
  26367. return this._baseMatrix;
  26368. };
  26369. Bone.prototype.getRestPose = function () {
  26370. return this._restPose;
  26371. };
  26372. Bone.prototype.returnToRest = function () {
  26373. this.updateMatrix(this._restPose.clone());
  26374. };
  26375. Bone.prototype.getWorldMatrix = function () {
  26376. return this._worldTransform;
  26377. };
  26378. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26379. return this._invertedAbsoluteTransform;
  26380. };
  26381. Bone.prototype.getAbsoluteTransform = function () {
  26382. return this._absoluteTransform;
  26383. };
  26384. // Methods
  26385. Bone.prototype.updateMatrix = function (matrix) {
  26386. this._baseMatrix = matrix.clone();
  26387. this._matrix = matrix.clone();
  26388. this._skeleton._markAsDirty();
  26389. this._updateDifferenceMatrix();
  26390. };
  26391. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26392. if (!rootMatrix) {
  26393. rootMatrix = this._baseMatrix;
  26394. }
  26395. if (this._parent) {
  26396. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26397. }
  26398. else {
  26399. this._absoluteTransform.copyFrom(rootMatrix);
  26400. }
  26401. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26402. for (var index = 0; index < this.children.length; index++) {
  26403. this.children[index]._updateDifferenceMatrix();
  26404. }
  26405. };
  26406. Bone.prototype.markAsDirty = function () {
  26407. this._currentRenderId++;
  26408. this._skeleton._markAsDirty();
  26409. };
  26410. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26411. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26412. // all animation may be coming from a library skeleton, so may need to create animation
  26413. if (this.animations.length === 0) {
  26414. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26415. this.animations[0].setKeys([]);
  26416. }
  26417. // get animation info / verify there is such a range from the source bone
  26418. var sourceRange = source.animations[0].getRange(rangeName);
  26419. if (!sourceRange) {
  26420. return false;
  26421. }
  26422. var from = sourceRange.from;
  26423. var to = sourceRange.to;
  26424. var sourceKeys = source.animations[0].getKeys();
  26425. // rescaling prep
  26426. var sourceBoneLength = source.length;
  26427. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26428. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26429. var destKeys = this.animations[0].getKeys();
  26430. // loop vars declaration / initialization
  26431. var orig;
  26432. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26433. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26434. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26435. var mat;
  26436. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26437. orig = sourceKeys[key];
  26438. if (orig.frame >= from && orig.frame <= to) {
  26439. if (scalingReqd) {
  26440. orig.value.decompose(origScale, origRotation, origTranslation);
  26441. origTranslation.scaleInPlace(ratio);
  26442. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26443. }
  26444. else {
  26445. mat = orig.value;
  26446. }
  26447. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26448. }
  26449. }
  26450. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26451. return true;
  26452. };
  26453. return Bone;
  26454. })(BABYLON.Node);
  26455. BABYLON.Bone = Bone;
  26456. })(BABYLON || (BABYLON = {}));
  26457. var BABYLON;
  26458. (function (BABYLON) {
  26459. var Skeleton = (function () {
  26460. function Skeleton(name, id, scene) {
  26461. this.name = name;
  26462. this.id = id;
  26463. this.bones = new Array();
  26464. this.needInitialSkinMatrix = false;
  26465. this._isDirty = true;
  26466. this._meshesWithPoseMatrix = new Array();
  26467. this._identity = BABYLON.Matrix.Identity();
  26468. this._ranges = {};
  26469. this.bones = [];
  26470. this._scene = scene;
  26471. scene.skeletons.push(this);
  26472. //make sure it will recalculate the matrix next time prepare is called.
  26473. this._isDirty = true;
  26474. }
  26475. // Members
  26476. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26477. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26478. return mesh._bonesTransformMatrices;
  26479. }
  26480. return this._transformMatrices;
  26481. };
  26482. Skeleton.prototype.getScene = function () {
  26483. return this._scene;
  26484. };
  26485. // Methods
  26486. /**
  26487. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26488. */
  26489. Skeleton.prototype.toString = function (fullDetails) {
  26490. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26491. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26492. if (fullDetails) {
  26493. ret += ", Ranges: {";
  26494. var first = true;
  26495. for (var name_1 in this._ranges) {
  26496. if (first) {
  26497. ret += ", ";
  26498. first = false;
  26499. }
  26500. ret += name_1;
  26501. }
  26502. ret += "}";
  26503. }
  26504. return ret;
  26505. };
  26506. /**
  26507. * Get bone's index searching by name
  26508. * @param {string} name is bone's name to search for
  26509. * @return {number} Indice of the bone. Returns -1 if not found
  26510. */
  26511. Skeleton.prototype.getBoneIndexByName = function (name) {
  26512. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26513. if (this.bones[boneIndex].name === name) {
  26514. return boneIndex;
  26515. }
  26516. }
  26517. return -1;
  26518. };
  26519. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26520. // check name not already in use
  26521. if (!this._ranges[name]) {
  26522. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26523. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26524. if (this.bones[i].animations[0]) {
  26525. this.bones[i].animations[0].createRange(name, from, to);
  26526. }
  26527. }
  26528. }
  26529. };
  26530. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26531. if (deleteFrames === void 0) { deleteFrames = true; }
  26532. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26533. if (this.bones[i].animations[0]) {
  26534. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26535. }
  26536. }
  26537. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26538. };
  26539. Skeleton.prototype.getAnimationRange = function (name) {
  26540. return this._ranges[name];
  26541. };
  26542. /**
  26543. * Returns as an Array, all AnimationRanges defined on this skeleton
  26544. */
  26545. Skeleton.prototype.getAnimationRanges = function () {
  26546. var animationRanges = [];
  26547. var name;
  26548. var i = 0;
  26549. for (name in this._ranges) {
  26550. animationRanges[i] = this._ranges[name];
  26551. i++;
  26552. }
  26553. return animationRanges;
  26554. };
  26555. /**
  26556. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26557. */
  26558. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26559. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26560. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26561. return false;
  26562. }
  26563. var ret = true;
  26564. var frameOffset = this._getHighestAnimationFrame() + 1;
  26565. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26566. var boneDict = {};
  26567. var sourceBones = source.bones;
  26568. var nBones;
  26569. var i;
  26570. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26571. boneDict[sourceBones[i].name] = sourceBones[i];
  26572. }
  26573. if (this.bones.length !== sourceBones.length) {
  26574. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26575. ret = false;
  26576. }
  26577. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  26578. var boneName = this.bones[i].name;
  26579. var sourceBone = boneDict[boneName];
  26580. if (sourceBone) {
  26581. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26582. }
  26583. else {
  26584. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26585. ret = false;
  26586. }
  26587. }
  26588. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26589. var range = source.getAnimationRange(name);
  26590. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26591. return ret;
  26592. };
  26593. Skeleton.prototype.returnToRest = function () {
  26594. for (var index = 0; index < this.bones.length; index++) {
  26595. this.bones[index].returnToRest();
  26596. }
  26597. };
  26598. Skeleton.prototype._getHighestAnimationFrame = function () {
  26599. var ret = 0;
  26600. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26601. if (this.bones[i].animations[0]) {
  26602. var highest = this.bones[i].animations[0].getHighestFrame();
  26603. if (ret < highest) {
  26604. ret = highest;
  26605. }
  26606. }
  26607. }
  26608. return ret;
  26609. };
  26610. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26611. var range = this.getAnimationRange(name);
  26612. if (!range) {
  26613. return null;
  26614. }
  26615. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26616. };
  26617. Skeleton.prototype._markAsDirty = function () {
  26618. this._isDirty = true;
  26619. };
  26620. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26621. this._meshesWithPoseMatrix.push(mesh);
  26622. };
  26623. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26624. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26625. if (index > -1) {
  26626. this._meshesWithPoseMatrix.splice(index, 1);
  26627. }
  26628. };
  26629. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26630. for (var index = 0; index < this.bones.length; index++) {
  26631. var bone = this.bones[index];
  26632. var parentBone = bone.getParent();
  26633. if (parentBone) {
  26634. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26635. }
  26636. else {
  26637. if (initialSkinMatrix) {
  26638. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26639. }
  26640. else {
  26641. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26642. }
  26643. }
  26644. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26645. }
  26646. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26647. };
  26648. Skeleton.prototype.prepare = function () {
  26649. if (!this._isDirty) {
  26650. return;
  26651. }
  26652. if (this.needInitialSkinMatrix) {
  26653. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26654. var mesh = this._meshesWithPoseMatrix[index];
  26655. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26656. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26657. }
  26658. var poseMatrix = mesh.getPoseMatrix();
  26659. // Prepare bones
  26660. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26661. var bone = this.bones[boneIndex];
  26662. if (!bone.getParent()) {
  26663. var matrix = bone.getBaseMatrix();
  26664. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26665. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26666. }
  26667. }
  26668. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26669. }
  26670. }
  26671. else {
  26672. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26673. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26674. }
  26675. this._computeTransformMatrices(this._transformMatrices, null);
  26676. }
  26677. this._isDirty = false;
  26678. this._scene._activeBones += this.bones.length;
  26679. };
  26680. Skeleton.prototype.getAnimatables = function () {
  26681. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26682. this._animatables = [];
  26683. for (var index = 0; index < this.bones.length; index++) {
  26684. this._animatables.push(this.bones[index]);
  26685. }
  26686. }
  26687. return this._animatables;
  26688. };
  26689. Skeleton.prototype.clone = function (name, id) {
  26690. var result = new Skeleton(name, id || name, this._scene);
  26691. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26692. for (var index = 0; index < this.bones.length; index++) {
  26693. var source = this.bones[index];
  26694. var parentBone = null;
  26695. if (source.getParent()) {
  26696. var parentIndex = this.bones.indexOf(source.getParent());
  26697. parentBone = result.bones[parentIndex];
  26698. }
  26699. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26700. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26701. }
  26702. if (this._ranges) {
  26703. result._ranges = {};
  26704. for (var rangeName in this._ranges) {
  26705. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26706. }
  26707. }
  26708. this._isDirty = true;
  26709. return result;
  26710. };
  26711. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  26712. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  26713. this.bones.forEach(function (bone) {
  26714. bone.animations.forEach(function (animation) {
  26715. animation.enableBlending = true;
  26716. animation.blendingSpeed = blendingSpeed;
  26717. });
  26718. });
  26719. };
  26720. Skeleton.prototype.dispose = function () {
  26721. this._meshesWithPoseMatrix = [];
  26722. // Animations
  26723. this.getScene().stopAnimation(this);
  26724. // Remove from scene
  26725. this.getScene().removeSkeleton(this);
  26726. };
  26727. Skeleton.prototype.serialize = function () {
  26728. var serializationObject = {};
  26729. serializationObject.name = this.name;
  26730. serializationObject.id = this.id;
  26731. serializationObject.bones = [];
  26732. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26733. for (var index = 0; index < this.bones.length; index++) {
  26734. var bone = this.bones[index];
  26735. var serializedBone = {
  26736. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26737. name: bone.name,
  26738. matrix: bone.getLocalMatrix().toArray(),
  26739. rest: bone.getRestPose().toArray()
  26740. };
  26741. serializationObject.bones.push(serializedBone);
  26742. if (bone.length) {
  26743. serializedBone.length = bone.length;
  26744. }
  26745. if (bone.animations && bone.animations.length > 0) {
  26746. serializedBone.animation = bone.animations[0].serialize();
  26747. }
  26748. serializationObject.ranges = [];
  26749. for (var name in this._ranges) {
  26750. var range = {};
  26751. range.name = name;
  26752. range.from = this._ranges[name].from;
  26753. range.to = this._ranges[name].to;
  26754. serializationObject.ranges.push(range);
  26755. }
  26756. }
  26757. return serializationObject;
  26758. };
  26759. Skeleton.Parse = function (parsedSkeleton, scene) {
  26760. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26761. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26762. var index;
  26763. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  26764. var parsedBone = parsedSkeleton.bones[index];
  26765. var parentBone = null;
  26766. if (parsedBone.parentBoneIndex > -1) {
  26767. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26768. }
  26769. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26770. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26771. if (parsedBone.length) {
  26772. bone.length = parsedBone.length;
  26773. }
  26774. if (parsedBone.animation) {
  26775. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26776. }
  26777. }
  26778. // placed after bones, so createAnimationRange can cascade down
  26779. if (parsedSkeleton.ranges) {
  26780. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  26781. var data = parsedSkeleton.ranges[index];
  26782. skeleton.createAnimationRange(data.name, data.from, data.to);
  26783. }
  26784. }
  26785. return skeleton;
  26786. };
  26787. return Skeleton;
  26788. })();
  26789. BABYLON.Skeleton = Skeleton;
  26790. })(BABYLON || (BABYLON = {}));
  26791. var BABYLON;
  26792. (function (BABYLON) {
  26793. var PostProcess = (function () {
  26794. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26796. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26797. this.name = name;
  26798. this.width = -1;
  26799. this.height = -1;
  26800. /*
  26801. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  26802. Can only be used on a single postprocess or on the last one of a chain.
  26803. */
  26804. this.enablePixelPerfectMode = false;
  26805. this._reusable = false;
  26806. this._textures = new BABYLON.SmartArray(2);
  26807. this._currentRenderTextureInd = 0;
  26808. this._scaleRatio = new BABYLON.Vector2(1, 1);
  26809. if (camera != null) {
  26810. this._camera = camera;
  26811. this._scene = camera.getScene();
  26812. camera.attachPostProcess(this);
  26813. this._engine = this._scene.getEngine();
  26814. }
  26815. else {
  26816. this._engine = engine;
  26817. }
  26818. this._renderRatio = ratio;
  26819. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26820. this._reusable = reusable || false;
  26821. this._textureType = textureType;
  26822. this._samplers = samplers || [];
  26823. this._samplers.push("textureSampler");
  26824. this._fragmentUrl = fragmentUrl;
  26825. this._parameters = parameters || [];
  26826. this._parameters.push("scale");
  26827. this.updateEffect(defines);
  26828. }
  26829. PostProcess.prototype.updateEffect = function (defines) {
  26830. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26831. };
  26832. PostProcess.prototype.isReusable = function () {
  26833. return this._reusable;
  26834. };
  26835. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26836. camera = camera || this._camera;
  26837. var scene = camera.getScene();
  26838. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26839. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26840. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26841. var desiredWidth = this._renderRatio.width || requiredWidth;
  26842. var desiredHeight = this._renderRatio.height || requiredHeight;
  26843. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  26844. if (!this._renderRatio.width) {
  26845. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26846. }
  26847. if (!this._renderRatio.height) {
  26848. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26849. }
  26850. }
  26851. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26852. if (this._textures.length > 0) {
  26853. for (var i = 0; i < this._textures.length; i++) {
  26854. this._engine._releaseTexture(this._textures.data[i]);
  26855. }
  26856. this._textures.reset();
  26857. }
  26858. this.width = desiredWidth;
  26859. this.height = desiredHeight;
  26860. 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 }));
  26861. if (this._reusable) {
  26862. 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 }));
  26863. }
  26864. if (this.onSizeChanged) {
  26865. this.onSizeChanged();
  26866. }
  26867. }
  26868. if (this.enablePixelPerfectMode) {
  26869. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  26870. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  26871. }
  26872. else {
  26873. this._scaleRatio.copyFromFloats(1, 1);
  26874. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26875. }
  26876. if (this.onActivate) {
  26877. this.onActivate(camera);
  26878. }
  26879. // Clear
  26880. if (this.clearColor) {
  26881. this._engine.clear(this.clearColor, true, true);
  26882. }
  26883. else {
  26884. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26885. }
  26886. if (this._reusable) {
  26887. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26888. }
  26889. };
  26890. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26891. get: function () {
  26892. return this._effect.isSupported;
  26893. },
  26894. enumerable: true,
  26895. configurable: true
  26896. });
  26897. PostProcess.prototype.apply = function () {
  26898. // Check
  26899. if (!this._effect.isReady())
  26900. return null;
  26901. // States
  26902. this._engine.enableEffect(this._effect);
  26903. this._engine.setState(false);
  26904. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26905. this._engine.setDepthBuffer(false);
  26906. this._engine.setDepthWrite(false);
  26907. // Texture
  26908. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26909. // Parameters
  26910. this._effect.setVector2("scale", this._scaleRatio);
  26911. if (this.onApply) {
  26912. this.onApply(this._effect);
  26913. }
  26914. return this._effect;
  26915. };
  26916. PostProcess.prototype.dispose = function (camera) {
  26917. camera = camera || this._camera;
  26918. if (this._textures.length > 0) {
  26919. for (var i = 0; i < this._textures.length; i++) {
  26920. this._engine._releaseTexture(this._textures.data[i]);
  26921. }
  26922. this._textures.reset();
  26923. }
  26924. if (!camera) {
  26925. return;
  26926. }
  26927. camera.detachPostProcess(this);
  26928. var index = camera._postProcesses.indexOf(this);
  26929. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26930. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26931. }
  26932. };
  26933. return PostProcess;
  26934. })();
  26935. BABYLON.PostProcess = PostProcess;
  26936. })(BABYLON || (BABYLON = {}));
  26937. var BABYLON;
  26938. (function (BABYLON) {
  26939. var PostProcessManager = (function () {
  26940. function PostProcessManager(scene) {
  26941. this._vertexDeclaration = [2];
  26942. this._vertexStrideSize = 2 * 4;
  26943. this._scene = scene;
  26944. }
  26945. PostProcessManager.prototype._prepareBuffers = function () {
  26946. if (this._vertexBuffer) {
  26947. return;
  26948. }
  26949. // VBO
  26950. var vertices = [];
  26951. vertices.push(1, 1);
  26952. vertices.push(-1, 1);
  26953. vertices.push(-1, -1);
  26954. vertices.push(1, -1);
  26955. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26956. // Indices
  26957. var indices = [];
  26958. indices.push(0);
  26959. indices.push(1);
  26960. indices.push(2);
  26961. indices.push(0);
  26962. indices.push(2);
  26963. indices.push(3);
  26964. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26965. };
  26966. // Methods
  26967. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26968. var postProcesses = this._scene.activeCamera._postProcesses;
  26969. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26970. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26971. return false;
  26972. }
  26973. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26974. return true;
  26975. };
  26976. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26977. var engine = this._scene.getEngine();
  26978. for (var index = 0; index < postProcesses.length; index++) {
  26979. if (index < postProcesses.length - 1) {
  26980. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26981. }
  26982. else {
  26983. if (targetTexture) {
  26984. engine.bindFramebuffer(targetTexture);
  26985. }
  26986. else {
  26987. engine.restoreDefaultFramebuffer();
  26988. }
  26989. }
  26990. var pp = postProcesses[index];
  26991. var effect = pp.apply();
  26992. if (effect) {
  26993. if (pp.onBeforeRender) {
  26994. pp.onBeforeRender(effect);
  26995. }
  26996. // VBOs
  26997. this._prepareBuffers();
  26998. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26999. // Draw order
  27000. engine.draw(true, 0, 6);
  27001. if (pp.onAfterRender) {
  27002. pp.onAfterRender(effect);
  27003. }
  27004. }
  27005. }
  27006. // Restore depth buffer
  27007. engine.setDepthBuffer(true);
  27008. engine.setDepthWrite(true);
  27009. };
  27010. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27011. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27012. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  27013. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  27014. return;
  27015. }
  27016. var engine = this._scene.getEngine();
  27017. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  27018. if (index < postProcessesTakenIndices.length - 1) {
  27019. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  27020. }
  27021. else {
  27022. if (targetTexture) {
  27023. engine.bindFramebuffer(targetTexture, faceIndex);
  27024. }
  27025. else {
  27026. engine.restoreDefaultFramebuffer();
  27027. }
  27028. }
  27029. if (doNotPresent) {
  27030. break;
  27031. }
  27032. var pp = postProcesses[postProcessesTakenIndices[index]];
  27033. var effect = pp.apply();
  27034. if (effect) {
  27035. if (pp.onBeforeRender) {
  27036. pp.onBeforeRender(effect);
  27037. }
  27038. // VBOs
  27039. this._prepareBuffers();
  27040. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27041. // Draw order
  27042. engine.draw(true, 0, 6);
  27043. if (pp.onAfterRender) {
  27044. pp.onAfterRender(effect);
  27045. }
  27046. }
  27047. }
  27048. // Restore depth buffer
  27049. engine.setDepthBuffer(true);
  27050. engine.setDepthWrite(true);
  27051. };
  27052. PostProcessManager.prototype.dispose = function () {
  27053. if (this._vertexBuffer) {
  27054. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  27055. this._vertexBuffer = null;
  27056. }
  27057. if (this._indexBuffer) {
  27058. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27059. this._indexBuffer = null;
  27060. }
  27061. };
  27062. return PostProcessManager;
  27063. })();
  27064. BABYLON.PostProcessManager = PostProcessManager;
  27065. })(BABYLON || (BABYLON = {}));
  27066. var BABYLON;
  27067. (function (BABYLON) {
  27068. var PassPostProcess = (function (_super) {
  27069. __extends(PassPostProcess, _super);
  27070. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27071. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  27072. }
  27073. return PassPostProcess;
  27074. })(BABYLON.PostProcess);
  27075. BABYLON.PassPostProcess = PassPostProcess;
  27076. })(BABYLON || (BABYLON = {}));
  27077. var BABYLON;
  27078. (function (BABYLON) {
  27079. /**
  27080. * This is a holder class for the physics joint created by the physics plugin.
  27081. * It holds a set of functions to control the underlying joint.
  27082. */
  27083. var PhysicsJoint = (function () {
  27084. function PhysicsJoint(type, jointData) {
  27085. this.type = type;
  27086. this.jointData = jointData;
  27087. jointData.nativeParams = jointData.nativeParams || {};
  27088. }
  27089. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  27090. get: function () {
  27091. return this._physicsJoint;
  27092. },
  27093. set: function (newJoint) {
  27094. if (this._physicsJoint) {
  27095. }
  27096. this._physicsJoint = newJoint;
  27097. },
  27098. enumerable: true,
  27099. configurable: true
  27100. });
  27101. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  27102. set: function (physicsPlugin) {
  27103. this._physicsPlugin = physicsPlugin;
  27104. },
  27105. enumerable: true,
  27106. configurable: true
  27107. });
  27108. /**
  27109. * Execute a function that is physics-plugin specific.
  27110. * @param {Function} func the function that will be executed.
  27111. * It accepts two parameters: the physics world and the physics joint.
  27112. */
  27113. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  27114. func(this._physicsPlugin.world, this._physicsJoint);
  27115. };
  27116. //TODO check if the native joints are the same
  27117. //Joint Types
  27118. PhysicsJoint.DistanceJoint = 0;
  27119. PhysicsJoint.HingeJoint = 1;
  27120. PhysicsJoint.BallAndSocketJoint = 2;
  27121. PhysicsJoint.WheelJoint = 3;
  27122. PhysicsJoint.SliderJoint = 4;
  27123. //OIMO
  27124. PhysicsJoint.PrismaticJoint = 5;
  27125. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  27126. PhysicsJoint.UniversalJoint = 6;
  27127. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  27128. //Cannon
  27129. //Similar to a Ball-Joint. Different in params
  27130. PhysicsJoint.PointToPointJoint = 8;
  27131. //Cannon only at the moment
  27132. PhysicsJoint.SpringJoint = 9;
  27133. return PhysicsJoint;
  27134. })();
  27135. BABYLON.PhysicsJoint = PhysicsJoint;
  27136. /**
  27137. * A class representing a physics distance joint.
  27138. */
  27139. var DistanceJoint = (function (_super) {
  27140. __extends(DistanceJoint, _super);
  27141. function DistanceJoint(jointData) {
  27142. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  27143. }
  27144. /**
  27145. * Update the predefined distance.
  27146. */
  27147. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  27148. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  27149. };
  27150. return DistanceJoint;
  27151. })(PhysicsJoint);
  27152. BABYLON.DistanceJoint = DistanceJoint;
  27153. var MotorEnabledJoint = (function (_super) {
  27154. __extends(MotorEnabledJoint, _super);
  27155. function MotorEnabledJoint(type, jointData) {
  27156. _super.call(this, type, jointData);
  27157. }
  27158. /**
  27159. * Set the motor values.
  27160. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27161. * @param {number} force the force to apply
  27162. * @param {number} maxForce max force for this motor.
  27163. */
  27164. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  27165. this._physicsPlugin.setMotor(this, force, maxForce);
  27166. };
  27167. /**
  27168. * Set the motor's limits.
  27169. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27170. */
  27171. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27172. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27173. };
  27174. return MotorEnabledJoint;
  27175. })(PhysicsJoint);
  27176. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  27177. /**
  27178. * This class represents a single hinge physics joint
  27179. */
  27180. var HingeJoint = (function (_super) {
  27181. __extends(HingeJoint, _super);
  27182. function HingeJoint(jointData) {
  27183. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  27184. }
  27185. /**
  27186. * Set the motor values.
  27187. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27188. * @param {number} force the force to apply
  27189. * @param {number} maxForce max force for this motor.
  27190. */
  27191. HingeJoint.prototype.setMotor = function (force, maxForce) {
  27192. this._physicsPlugin.setMotor(this, force, maxForce);
  27193. };
  27194. /**
  27195. * Set the motor's limits.
  27196. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27197. */
  27198. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27199. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27200. };
  27201. return HingeJoint;
  27202. })(MotorEnabledJoint);
  27203. BABYLON.HingeJoint = HingeJoint;
  27204. /**
  27205. * This class represents a dual hinge physics joint (same as wheel joint)
  27206. */
  27207. var Hinge2Joint = (function (_super) {
  27208. __extends(Hinge2Joint, _super);
  27209. function Hinge2Joint(jointData) {
  27210. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  27211. }
  27212. /**
  27213. * Set the motor values.
  27214. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27215. * @param {number} force the force to apply
  27216. * @param {number} maxForce max force for this motor.
  27217. * @param {motorIndex} the motor's index, 0 or 1.
  27218. */
  27219. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  27220. if (motorIndex === void 0) { motorIndex = 0; }
  27221. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  27222. };
  27223. /**
  27224. * Set the motor limits.
  27225. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27226. * @param {number} upperLimit the upper limit
  27227. * @param {number} lowerLimit lower limit
  27228. * @param {motorIndex} the motor's index, 0 or 1.
  27229. */
  27230. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  27231. if (motorIndex === void 0) { motorIndex = 0; }
  27232. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  27233. };
  27234. return Hinge2Joint;
  27235. })(MotorEnabledJoint);
  27236. BABYLON.Hinge2Joint = Hinge2Joint;
  27237. })(BABYLON || (BABYLON = {}));
  27238. var BABYLON;
  27239. (function (BABYLON) {
  27240. var PhysicsImpostor = (function () {
  27241. function PhysicsImpostor(object, type, _options, _scene) {
  27242. var _this = this;
  27243. if (_options === void 0) { _options = { mass: 0 }; }
  27244. this.object = object;
  27245. this.type = type;
  27246. this._options = _options;
  27247. this._scene = _scene;
  27248. this._bodyUpdateRequired = false;
  27249. this._onBeforePhysicsStepCallbacks = new Array();
  27250. this._onAfterPhysicsStepCallbacks = new Array();
  27251. this._onPhysicsCollideCallbacks = [];
  27252. this._deltaPosition = BABYLON.Vector3.Zero();
  27253. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  27254. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  27255. /**
  27256. * this function is executed by the physics engine.
  27257. */
  27258. this.beforeStep = function () {
  27259. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  27260. //conjugate deltaRotation
  27261. if (_this._deltaRotationConjugated) {
  27262. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  27263. }
  27264. else {
  27265. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  27266. }
  27267. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  27268. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  27269. func(_this);
  27270. });
  27271. };
  27272. /**
  27273. * this function is executed by the physics engine.
  27274. */
  27275. this.afterStep = function () {
  27276. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  27277. func(_this);
  27278. });
  27279. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  27280. _this.object.position.addInPlace(_this._deltaPosition);
  27281. if (_this._deltaRotation) {
  27282. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  27283. }
  27284. };
  27285. //event and body object due to cannon's event-based architecture.
  27286. this.onCollide = function (e) {
  27287. if (!_this._onPhysicsCollideCallbacks.length)
  27288. return;
  27289. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  27290. if (otherImpostor) {
  27291. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  27292. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  27293. }).forEach(function (obj) {
  27294. obj.callback(_this, otherImpostor);
  27295. });
  27296. }
  27297. };
  27298. //sanity check!
  27299. if (!this.object) {
  27300. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  27301. return;
  27302. }
  27303. //legacy support for old syntax.
  27304. if (!this._scene && object.getScene) {
  27305. this._scene = object.getScene();
  27306. }
  27307. this._physicsEngine = this._scene.getPhysicsEngine();
  27308. if (!this._physicsEngine) {
  27309. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  27310. }
  27311. else {
  27312. //set the object's quaternion, if not set
  27313. if (!this.object.rotationQuaternion) {
  27314. if (this.object.rotation) {
  27315. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  27316. }
  27317. else {
  27318. this.object.rotationQuaternion = new BABYLON.Quaternion();
  27319. }
  27320. }
  27321. //default options params
  27322. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27323. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27324. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27325. this._joints = [];
  27326. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27327. if (!this.object.parent) {
  27328. this._init();
  27329. }
  27330. }
  27331. }
  27332. /**
  27333. * This function will completly initialize this impostor.
  27334. * It will create a new body - but only if this mesh has no parent.
  27335. * If it has, this impostor will not be used other than to define the impostor
  27336. * of the child mesh.
  27337. */
  27338. PhysicsImpostor.prototype._init = function () {
  27339. this._physicsEngine.removeImpostor(this);
  27340. this.physicsBody = null;
  27341. this._parent = this._parent || this._getPhysicsParent();
  27342. if (!this.parent) {
  27343. this._physicsEngine.addImpostor(this);
  27344. }
  27345. };
  27346. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27347. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27348. var parentMesh = this.object.parent;
  27349. return parentMesh.physicsImpostor;
  27350. }
  27351. return;
  27352. };
  27353. /**
  27354. * Should a new body be generated.
  27355. */
  27356. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27357. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27358. };
  27359. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27360. this.forceUpdate();
  27361. };
  27362. /**
  27363. * Force a regeneration of this or the parent's impostor's body.
  27364. * Use under cautious - This will remove all joints already implemented.
  27365. */
  27366. PhysicsImpostor.prototype.forceUpdate = function () {
  27367. this._init();
  27368. if (this.parent) {
  27369. this.parent.forceUpdate();
  27370. }
  27371. };
  27372. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27373. /*public get mesh(): AbstractMesh {
  27374. return this._mesh;
  27375. }*/
  27376. /**
  27377. * Gets the body that holds this impostor. Either its own, or its parent.
  27378. */
  27379. get: function () {
  27380. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27381. },
  27382. /**
  27383. * Set the physics body. Used mainly by the physics engine/plugin
  27384. */
  27385. set: function (physicsBody) {
  27386. if (this._physicsBody) {
  27387. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27388. }
  27389. this._physicsBody = physicsBody;
  27390. this.resetUpdateFlags();
  27391. },
  27392. enumerable: true,
  27393. configurable: true
  27394. });
  27395. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27396. get: function () {
  27397. return this._parent;
  27398. },
  27399. enumerable: true,
  27400. configurable: true
  27401. });
  27402. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27403. this._bodyUpdateRequired = false;
  27404. };
  27405. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27406. if (this.object.getBoundingInfo) {
  27407. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27408. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27409. }
  27410. else {
  27411. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27412. }
  27413. };
  27414. PhysicsImpostor.prototype.getObjectCenter = function () {
  27415. if (this.object.getBoundingInfo) {
  27416. return this.object.getBoundingInfo().boundingBox.center;
  27417. }
  27418. else {
  27419. return this.object.position;
  27420. }
  27421. };
  27422. /**
  27423. * Get a specific parametes from the options parameter.
  27424. */
  27425. PhysicsImpostor.prototype.getParam = function (paramName) {
  27426. return this._options[paramName];
  27427. };
  27428. /**
  27429. * Sets a specific parameter in the options given to the physics plugin
  27430. */
  27431. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27432. this._options[paramName] = value;
  27433. this._bodyUpdateRequired = true;
  27434. };
  27435. /**
  27436. * Specifically change the body's mass option. Won't recreate the physics body object
  27437. */
  27438. PhysicsImpostor.prototype.setMass = function (mass) {
  27439. if (this.getParam("mass") !== mass) {
  27440. this.setParam("mass", mass);
  27441. }
  27442. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27443. };
  27444. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27445. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27446. };
  27447. /**
  27448. * Set the body's linear velocity.
  27449. */
  27450. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27451. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27452. };
  27453. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27454. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27455. };
  27456. /**
  27457. * Set the body's linear velocity.
  27458. */
  27459. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27460. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27461. };
  27462. /**
  27463. * Execute a function with the physics plugin native code.
  27464. * Provide a function the will have two variables - the world object and the physics body object.
  27465. */
  27466. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27467. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27468. };
  27469. /**
  27470. * Register a function that will be executed before the physics world is stepping forward.
  27471. */
  27472. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27473. this._onBeforePhysicsStepCallbacks.push(func);
  27474. };
  27475. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27476. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27477. if (index > -1) {
  27478. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27479. }
  27480. else {
  27481. BABYLON.Tools.Warn("Function to remove was not found");
  27482. }
  27483. };
  27484. /**
  27485. * Register a function that will be executed after the physics step
  27486. */
  27487. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27488. this._onAfterPhysicsStepCallbacks.push(func);
  27489. };
  27490. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27491. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27492. if (index > -1) {
  27493. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27494. }
  27495. else {
  27496. BABYLON.Tools.Warn("Function to remove was not found");
  27497. }
  27498. };
  27499. /**
  27500. * register a function that will be executed when this impostor collides against a different body.
  27501. */
  27502. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27503. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27504. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27505. };
  27506. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27507. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27508. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27509. if (index > -1) {
  27510. this._onPhysicsCollideCallbacks.splice(index, 1);
  27511. }
  27512. else {
  27513. BABYLON.Tools.Warn("Function to remove was not found");
  27514. }
  27515. };
  27516. /**
  27517. * Apply a force
  27518. */
  27519. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27520. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27521. };
  27522. /**
  27523. * Apply an impulse
  27524. */
  27525. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27526. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27527. };
  27528. /**
  27529. * A help function to create a joint.
  27530. */
  27531. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27532. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27533. this.addJoint(otherImpostor, joint);
  27534. };
  27535. /**
  27536. * Add a joint to this impostor with a different impostor.
  27537. */
  27538. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27539. this._joints.push({
  27540. otherImpostor: otherImpostor,
  27541. joint: joint
  27542. });
  27543. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27544. };
  27545. /**
  27546. * Will keep this body still, in a sleep mode.
  27547. */
  27548. PhysicsImpostor.prototype.sleep = function () {
  27549. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27550. };
  27551. /**
  27552. * Wake the body up.
  27553. */
  27554. PhysicsImpostor.prototype.wakeUp = function () {
  27555. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27556. };
  27557. PhysicsImpostor.prototype.clone = function (newObject) {
  27558. if (!newObject)
  27559. return null;
  27560. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27561. };
  27562. PhysicsImpostor.prototype.dispose = function () {
  27563. var _this = this;
  27564. //no dispose if no physics engine is available.
  27565. if (!this._physicsEngine) {
  27566. return;
  27567. }
  27568. this._joints.forEach(function (j) {
  27569. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  27570. });
  27571. //dispose the physics body
  27572. this._physicsEngine.removeImpostor(this);
  27573. if (this.parent) {
  27574. this.parent.forceUpdate();
  27575. }
  27576. else {
  27577. }
  27578. };
  27579. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27580. this._deltaPosition.copyFrom(position);
  27581. };
  27582. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27583. if (!this._deltaRotation) {
  27584. this._deltaRotation = new BABYLON.Quaternion();
  27585. }
  27586. this._deltaRotation.copyFrom(rotation);
  27587. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27588. };
  27589. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27590. //Impostor types
  27591. PhysicsImpostor.NoImpostor = 0;
  27592. PhysicsImpostor.SphereImpostor = 1;
  27593. PhysicsImpostor.BoxImpostor = 2;
  27594. PhysicsImpostor.PlaneImpostor = 3;
  27595. PhysicsImpostor.MeshImpostor = 4;
  27596. PhysicsImpostor.CylinderImpostor = 7;
  27597. PhysicsImpostor.ParticleImpostor = 8;
  27598. PhysicsImpostor.HeightmapImpostor = 9;
  27599. return PhysicsImpostor;
  27600. })();
  27601. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27602. })(BABYLON || (BABYLON = {}));
  27603. var BABYLON;
  27604. (function (BABYLON) {
  27605. var PhysicsEngine = (function () {
  27606. function PhysicsEngine(gravity, _physicsPlugin) {
  27607. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27608. this._physicsPlugin = _physicsPlugin;
  27609. //new methods and parameters
  27610. this._impostors = [];
  27611. this._joints = [];
  27612. if (!this._physicsPlugin.isSupported()) {
  27613. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27614. + "Please make sure it is included.");
  27615. }
  27616. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27617. this.setGravity(gravity);
  27618. this.setTimeStep();
  27619. }
  27620. PhysicsEngine.prototype.setGravity = function (gravity) {
  27621. this.gravity = gravity;
  27622. this._physicsPlugin.setGravity(this.gravity);
  27623. };
  27624. /**
  27625. * Set the time step of the physics engine.
  27626. * default is 1/60.
  27627. * To slow it down, enter 1/600 for example.
  27628. * To speed it up, 1/30
  27629. * @param {number} newTimeStep the new timestep to apply to this world.
  27630. */
  27631. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27632. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27633. this._physicsPlugin.setTimeStep(newTimeStep);
  27634. };
  27635. PhysicsEngine.prototype.dispose = function () {
  27636. this._impostors.forEach(function (impostor) {
  27637. impostor.dispose();
  27638. });
  27639. this._physicsPlugin.dispose();
  27640. };
  27641. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27642. return this._physicsPlugin.name;
  27643. };
  27644. /**
  27645. * Adding a new impostor for the impostor tracking.
  27646. * This will be done by the impostor itself.
  27647. * @param {PhysicsImpostor} impostor the impostor to add
  27648. */
  27649. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27650. impostor.uniqueId = this._impostors.push(impostor);
  27651. //if no parent, generate the body
  27652. if (!impostor.parent) {
  27653. this._physicsPlugin.generatePhysicsBody(impostor);
  27654. }
  27655. };
  27656. /**
  27657. * Remove an impostor from the engine.
  27658. * This impostor and its mesh will not longer be updated by the physics engine.
  27659. * @param {PhysicsImpostor} impostor the impostor to remove
  27660. */
  27661. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27662. var index = this._impostors.indexOf(impostor);
  27663. if (index > -1) {
  27664. var removed = this._impostors.splice(index, 1);
  27665. //Is it needed?
  27666. if (removed.length) {
  27667. //this will also remove it from the world.
  27668. removed[0].physicsBody = null;
  27669. }
  27670. }
  27671. };
  27672. /**
  27673. * Add a joint to the physics engine
  27674. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27675. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27676. * @param {PhysicsJoint} the joint that will connect both impostors.
  27677. */
  27678. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27679. var impostorJoint = {
  27680. mainImpostor: mainImpostor,
  27681. connectedImpostor: connectedImpostor,
  27682. joint: joint
  27683. };
  27684. joint.physicsPlugin = this._physicsPlugin;
  27685. this._joints.push(impostorJoint);
  27686. this._physicsPlugin.generateJoint(impostorJoint);
  27687. };
  27688. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27689. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27690. return (impostorJoint.connectedImpostor === connectedImpostor
  27691. && impostorJoint.joint === joint
  27692. && impostorJoint.mainImpostor === mainImpostor);
  27693. });
  27694. if (matchingJoints.length) {
  27695. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27696. }
  27697. };
  27698. /**
  27699. * Called by the scene. no need to call it.
  27700. */
  27701. PhysicsEngine.prototype._step = function (delta) {
  27702. var _this = this;
  27703. //check if any mesh has no body / requires an update
  27704. this._impostors.forEach(function (impostor) {
  27705. if (impostor.isBodyInitRequired()) {
  27706. _this._physicsPlugin.generatePhysicsBody(impostor);
  27707. }
  27708. });
  27709. if (delta > 0.1) {
  27710. delta = 0.1;
  27711. }
  27712. else if (delta <= 0) {
  27713. delta = 1.0 / 60.0;
  27714. }
  27715. this._physicsPlugin.executeStep(delta, this._impostors);
  27716. };
  27717. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27718. return this._physicsPlugin;
  27719. };
  27720. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27721. for (var i = 0; i < this._impostors.length; ++i) {
  27722. if (this._impostors[i].object === object) {
  27723. return this._impostors[i];
  27724. }
  27725. }
  27726. };
  27727. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27728. for (var i = 0; i < this._impostors.length; ++i) {
  27729. if (this._impostors[i].physicsBody === body) {
  27730. return this._impostors[i];
  27731. }
  27732. }
  27733. };
  27734. // Statics, Legacy support.
  27735. /**
  27736. * @Deprecated
  27737. *
  27738. */
  27739. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27740. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27741. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27742. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27743. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27744. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27745. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27746. PhysicsEngine.CapsuleImpostor = -1;
  27747. PhysicsEngine.ConeImpostor = -1;
  27748. PhysicsEngine.ConvexHullImpostor = -1;
  27749. PhysicsEngine.Epsilon = 0.001;
  27750. return PhysicsEngine;
  27751. })();
  27752. BABYLON.PhysicsEngine = PhysicsEngine;
  27753. })(BABYLON || (BABYLON = {}));
  27754. var BABYLON;
  27755. (function (BABYLON) {
  27756. var VertexData = (function () {
  27757. function VertexData() {
  27758. }
  27759. VertexData.prototype.set = function (data, kind) {
  27760. switch (kind) {
  27761. case BABYLON.VertexBuffer.PositionKind:
  27762. this.positions = data;
  27763. break;
  27764. case BABYLON.VertexBuffer.NormalKind:
  27765. this.normals = data;
  27766. break;
  27767. case BABYLON.VertexBuffer.UVKind:
  27768. this.uvs = data;
  27769. break;
  27770. case BABYLON.VertexBuffer.UV2Kind:
  27771. this.uvs2 = data;
  27772. break;
  27773. case BABYLON.VertexBuffer.UV3Kind:
  27774. this.uvs3 = data;
  27775. break;
  27776. case BABYLON.VertexBuffer.UV4Kind:
  27777. this.uvs4 = data;
  27778. break;
  27779. case BABYLON.VertexBuffer.UV5Kind:
  27780. this.uvs5 = data;
  27781. break;
  27782. case BABYLON.VertexBuffer.UV6Kind:
  27783. this.uvs6 = data;
  27784. break;
  27785. case BABYLON.VertexBuffer.ColorKind:
  27786. this.colors = data;
  27787. break;
  27788. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27789. this.matricesIndices = data;
  27790. break;
  27791. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27792. this.matricesWeights = data;
  27793. break;
  27794. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27795. this.matricesIndicesExtra = data;
  27796. break;
  27797. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27798. this.matricesWeightsExtra = data;
  27799. break;
  27800. }
  27801. };
  27802. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27803. this._applyTo(mesh, updatable);
  27804. };
  27805. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27806. this._applyTo(geometry, updatable);
  27807. };
  27808. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27809. this._update(mesh);
  27810. };
  27811. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27812. this._update(geometry);
  27813. };
  27814. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27815. if (this.positions) {
  27816. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27817. }
  27818. if (this.normals) {
  27819. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27820. }
  27821. if (this.uvs) {
  27822. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27823. }
  27824. if (this.uvs2) {
  27825. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27826. }
  27827. if (this.uvs3) {
  27828. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27829. }
  27830. if (this.uvs4) {
  27831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27832. }
  27833. if (this.uvs5) {
  27834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27835. }
  27836. if (this.uvs6) {
  27837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27838. }
  27839. if (this.colors) {
  27840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27841. }
  27842. if (this.matricesIndices) {
  27843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27844. }
  27845. if (this.matricesWeights) {
  27846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27847. }
  27848. if (this.matricesIndicesExtra) {
  27849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27850. }
  27851. if (this.matricesWeightsExtra) {
  27852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27853. }
  27854. if (this.indices) {
  27855. meshOrGeometry.setIndices(this.indices);
  27856. }
  27857. };
  27858. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27859. if (this.positions) {
  27860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27861. }
  27862. if (this.normals) {
  27863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27864. }
  27865. if (this.uvs) {
  27866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27867. }
  27868. if (this.uvs2) {
  27869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27870. }
  27871. if (this.uvs3) {
  27872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27873. }
  27874. if (this.uvs4) {
  27875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27876. }
  27877. if (this.uvs5) {
  27878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27879. }
  27880. if (this.uvs6) {
  27881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27882. }
  27883. if (this.colors) {
  27884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27885. }
  27886. if (this.matricesIndices) {
  27887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27888. }
  27889. if (this.matricesWeights) {
  27890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27891. }
  27892. if (this.matricesIndicesExtra) {
  27893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27894. }
  27895. if (this.matricesWeightsExtra) {
  27896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27897. }
  27898. if (this.indices) {
  27899. meshOrGeometry.setIndices(this.indices);
  27900. }
  27901. };
  27902. VertexData.prototype.transform = function (matrix) {
  27903. var transformed = BABYLON.Vector3.Zero();
  27904. var index;
  27905. if (this.positions) {
  27906. var position = BABYLON.Vector3.Zero();
  27907. for (index = 0; index < this.positions.length; index += 3) {
  27908. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27909. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27910. this.positions[index] = transformed.x;
  27911. this.positions[index + 1] = transformed.y;
  27912. this.positions[index + 2] = transformed.z;
  27913. }
  27914. }
  27915. if (this.normals) {
  27916. var normal = BABYLON.Vector3.Zero();
  27917. for (index = 0; index < this.normals.length; index += 3) {
  27918. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27919. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27920. this.normals[index] = transformed.x;
  27921. this.normals[index + 1] = transformed.y;
  27922. this.normals[index + 2] = transformed.z;
  27923. }
  27924. }
  27925. };
  27926. VertexData.prototype.merge = function (other) {
  27927. if (other.indices) {
  27928. if (!this.indices) {
  27929. this.indices = [];
  27930. }
  27931. var offset = this.positions ? this.positions.length / 3 : 0;
  27932. for (var index = 0; index < other.indices.length; index++) {
  27933. //TODO check type - if Int32Array!
  27934. this.indices.push(other.indices[index] + offset);
  27935. }
  27936. }
  27937. this.positions = this._mergeElement(this.positions, other.positions);
  27938. this.normals = this._mergeElement(this.normals, other.normals);
  27939. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27940. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27941. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27942. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27943. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27944. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27945. this.colors = this._mergeElement(this.colors, other.colors);
  27946. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27947. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27948. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27949. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27950. };
  27951. VertexData.prototype._mergeElement = function (source, other) {
  27952. if (!other)
  27953. return source;
  27954. if (!source)
  27955. return other;
  27956. var len = other.length + source.length;
  27957. var isSrcTypedArray = source instanceof Float32Array;
  27958. var isOthTypedArray = other instanceof Float32Array;
  27959. // use non-loop method when the source is Float32Array
  27960. if (isSrcTypedArray) {
  27961. var ret32 = new Float32Array(len);
  27962. ret32.set(source);
  27963. ret32.set(other, source.length);
  27964. return ret32;
  27965. }
  27966. else if (!isOthTypedArray) {
  27967. return source.concat(other);
  27968. }
  27969. else {
  27970. var ret = source.slice(0); // copy source to a separate array
  27971. for (var i = 0, len = other.length; i < len; i++) {
  27972. ret.push(other[i]);
  27973. }
  27974. return ret;
  27975. }
  27976. };
  27977. VertexData.prototype.serialize = function () {
  27978. var serializationObject = this.serialize();
  27979. if (this.positions) {
  27980. serializationObject.positions = this.positions;
  27981. }
  27982. if (this.normals) {
  27983. serializationObject.normals = this.normals;
  27984. }
  27985. if (this.uvs) {
  27986. serializationObject.uvs = this.uvs;
  27987. }
  27988. if (this.uvs2) {
  27989. serializationObject.uvs2 = this.uvs2;
  27990. }
  27991. if (this.uvs3) {
  27992. serializationObject.uvs3 = this.uvs3;
  27993. }
  27994. if (this.uvs4) {
  27995. serializationObject.uvs4 = this.uvs4;
  27996. }
  27997. if (this.uvs5) {
  27998. serializationObject.uvs5 = this.uvs5;
  27999. }
  28000. if (this.uvs6) {
  28001. serializationObject.uvs6 = this.uvs6;
  28002. }
  28003. if (this.colors) {
  28004. serializationObject.colors = this.colors;
  28005. }
  28006. if (this.matricesIndices) {
  28007. serializationObject.matricesIndices = this.matricesIndices;
  28008. serializationObject.matricesIndices._isExpanded = true;
  28009. }
  28010. if (this.matricesWeights) {
  28011. serializationObject.matricesWeights = this.matricesWeights;
  28012. }
  28013. if (this.matricesIndicesExtra) {
  28014. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28015. serializationObject.matricesIndicesExtra._isExpanded = true;
  28016. }
  28017. if (this.matricesWeightsExtra) {
  28018. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28019. }
  28020. serializationObject.indices = this.indices;
  28021. return serializationObject;
  28022. };
  28023. // Statics
  28024. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  28025. return VertexData._ExtractFrom(mesh, copyWhenShared);
  28026. };
  28027. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  28028. return VertexData._ExtractFrom(geometry, copyWhenShared);
  28029. };
  28030. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  28031. var result = new VertexData();
  28032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28033. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  28034. }
  28035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28036. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  28037. }
  28038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28039. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  28040. }
  28041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28042. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  28043. }
  28044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28045. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  28046. }
  28047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28048. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  28049. }
  28050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28051. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  28052. }
  28053. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28054. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  28055. }
  28056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28057. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  28058. }
  28059. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28060. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  28061. }
  28062. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28063. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  28064. }
  28065. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28066. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  28067. }
  28068. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28069. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  28070. }
  28071. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28072. return result;
  28073. };
  28074. VertexData.CreateRibbon = function (options) {
  28075. var pathArray = options.pathArray;
  28076. var closeArray = options.closeArray || false;
  28077. var closePath = options.closePath || false;
  28078. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28079. var offset = options.offset || defaultOffset;
  28080. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28081. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28082. var positions = [];
  28083. var indices = [];
  28084. var normals = [];
  28085. var uvs = [];
  28086. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28087. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28088. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28089. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28090. var minlg; // minimal length among all paths from pathArray
  28091. var lg = []; // array of path lengths : nb of vertex per path
  28092. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28093. var p; // path iterator
  28094. var i; // point iterator
  28095. var j; // point iterator
  28096. // if single path in pathArray
  28097. if (pathArray.length < 2) {
  28098. var ar1 = [];
  28099. var ar2 = [];
  28100. for (i = 0; i < pathArray[0].length - offset; i++) {
  28101. ar1.push(pathArray[0][i]);
  28102. ar2.push(pathArray[0][i + offset]);
  28103. }
  28104. pathArray = [ar1, ar2];
  28105. }
  28106. // positions and horizontal distances (u)
  28107. var idc = 0;
  28108. var closePathCorr = (closePath) ? 1 : 0;
  28109. var path;
  28110. var l;
  28111. minlg = pathArray[0].length;
  28112. var vectlg;
  28113. var dist;
  28114. for (p = 0; p < pathArray.length; p++) {
  28115. uTotalDistance[p] = 0;
  28116. us[p] = [0];
  28117. path = pathArray[p];
  28118. l = path.length;
  28119. minlg = (minlg < l) ? minlg : l;
  28120. j = 0;
  28121. while (j < l) {
  28122. positions.push(path[j].x, path[j].y, path[j].z);
  28123. if (j > 0) {
  28124. vectlg = path[j].subtract(path[j - 1]).length();
  28125. dist = vectlg + uTotalDistance[p];
  28126. us[p].push(dist);
  28127. uTotalDistance[p] = dist;
  28128. }
  28129. j++;
  28130. }
  28131. if (closePath) {
  28132. j--;
  28133. positions.push(path[0].x, path[0].y, path[0].z);
  28134. vectlg = path[j].subtract(path[0]).length();
  28135. dist = vectlg + uTotalDistance[p];
  28136. us[p].push(dist);
  28137. uTotalDistance[p] = dist;
  28138. }
  28139. lg[p] = l + closePathCorr;
  28140. idx[p] = idc;
  28141. idc += (l + closePathCorr);
  28142. }
  28143. // vertical distances (v)
  28144. var path1;
  28145. var path2;
  28146. var vertex1;
  28147. var vertex2;
  28148. for (i = 0; i < minlg + closePathCorr; i++) {
  28149. vTotalDistance[i] = 0;
  28150. vs[i] = [0];
  28151. for (p = 0; p < pathArray.length - 1; p++) {
  28152. path1 = pathArray[p];
  28153. path2 = pathArray[p + 1];
  28154. if (i === minlg) {
  28155. vertex1 = path1[0];
  28156. vertex2 = path2[0];
  28157. }
  28158. else {
  28159. vertex1 = path1[i];
  28160. vertex2 = path2[i];
  28161. }
  28162. vectlg = vertex2.subtract(vertex1).length();
  28163. dist = vectlg + vTotalDistance[i];
  28164. vs[i].push(dist);
  28165. vTotalDistance[i] = dist;
  28166. }
  28167. if (closeArray) {
  28168. path1 = pathArray[p];
  28169. path2 = pathArray[0];
  28170. if (i === minlg) {
  28171. vertex2 = path2[0];
  28172. }
  28173. vectlg = vertex2.subtract(vertex1).length();
  28174. dist = vectlg + vTotalDistance[i];
  28175. vTotalDistance[i] = dist;
  28176. }
  28177. }
  28178. // uvs
  28179. var u;
  28180. var v;
  28181. for (p = 0; p < pathArray.length; p++) {
  28182. for (i = 0; i < minlg + closePathCorr; i++) {
  28183. u = us[p][i] / uTotalDistance[p];
  28184. v = vs[i][p] / vTotalDistance[i];
  28185. uvs.push(u, v);
  28186. }
  28187. }
  28188. // indices
  28189. p = 0; // path index
  28190. var pi = 0; // positions array index
  28191. var l1 = lg[p] - 1; // path1 length
  28192. var l2 = lg[p + 1] - 1; // path2 length
  28193. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28194. var shft = idx[1] - idx[0]; // shift
  28195. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28196. while (pi <= min && p < path1nb) {
  28197. // 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
  28198. indices.push(pi, pi + shft, pi + 1);
  28199. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28200. pi += 1;
  28201. if (pi === min) {
  28202. p++;
  28203. if (p === lg.length - 1) {
  28204. shft = idx[0] - idx[p];
  28205. l1 = lg[p] - 1;
  28206. l2 = lg[0] - 1;
  28207. }
  28208. else {
  28209. shft = idx[p + 1] - idx[p];
  28210. l1 = lg[p] - 1;
  28211. l2 = lg[p + 1] - 1;
  28212. }
  28213. pi = idx[p];
  28214. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28215. }
  28216. }
  28217. // normals
  28218. VertexData.ComputeNormals(positions, indices, normals);
  28219. if (closePath) {
  28220. var indexFirst = 0;
  28221. var indexLast = 0;
  28222. for (p = 0; p < pathArray.length; p++) {
  28223. indexFirst = idx[p] * 3;
  28224. if (p + 1 < pathArray.length) {
  28225. indexLast = (idx[p + 1] - 1) * 3;
  28226. }
  28227. else {
  28228. indexLast = normals.length - 3;
  28229. }
  28230. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28231. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28232. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28233. normals[indexLast] = normals[indexFirst];
  28234. normals[indexLast + 1] = normals[indexFirst + 1];
  28235. normals[indexLast + 2] = normals[indexFirst + 2];
  28236. }
  28237. }
  28238. // sides
  28239. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28240. // Result
  28241. var vertexData = new VertexData();
  28242. vertexData.indices = indices;
  28243. vertexData.positions = positions;
  28244. vertexData.normals = normals;
  28245. vertexData.uvs = uvs;
  28246. if (closePath) {
  28247. vertexData._idx = idx;
  28248. }
  28249. return vertexData;
  28250. };
  28251. VertexData.CreateBox = function (options) {
  28252. var normalsSource = [
  28253. new BABYLON.Vector3(0, 0, 1),
  28254. new BABYLON.Vector3(0, 0, -1),
  28255. new BABYLON.Vector3(1, 0, 0),
  28256. new BABYLON.Vector3(-1, 0, 0),
  28257. new BABYLON.Vector3(0, 1, 0),
  28258. new BABYLON.Vector3(0, -1, 0)
  28259. ];
  28260. var indices = [];
  28261. var positions = [];
  28262. var normals = [];
  28263. var uvs = [];
  28264. var width = options.width || options.size || 1;
  28265. var height = options.height || options.size || 1;
  28266. var depth = options.depth || options.size || 1;
  28267. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28268. var faceUV = options.faceUV || new Array(6);
  28269. var faceColors = options.faceColors;
  28270. var colors = [];
  28271. // default face colors and UV if undefined
  28272. for (var f = 0; f < 6; f++) {
  28273. if (faceUV[f] === undefined) {
  28274. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28275. }
  28276. if (faceColors && faceColors[f] === undefined) {
  28277. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28278. }
  28279. }
  28280. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28281. // Create each face in turn.
  28282. for (var index = 0; index < normalsSource.length; index++) {
  28283. var normal = normalsSource[index];
  28284. // Get two vectors perpendicular to the face normal and to each other.
  28285. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28286. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28287. // Six indices (two triangles) per face.
  28288. var verticesLength = positions.length / 3;
  28289. indices.push(verticesLength);
  28290. indices.push(verticesLength + 1);
  28291. indices.push(verticesLength + 2);
  28292. indices.push(verticesLength);
  28293. indices.push(verticesLength + 2);
  28294. indices.push(verticesLength + 3);
  28295. // Four vertices per face.
  28296. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28297. positions.push(vertex.x, vertex.y, vertex.z);
  28298. normals.push(normal.x, normal.y, normal.z);
  28299. uvs.push(faceUV[index].z, faceUV[index].w);
  28300. if (faceColors) {
  28301. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28302. }
  28303. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28304. positions.push(vertex.x, vertex.y, vertex.z);
  28305. normals.push(normal.x, normal.y, normal.z);
  28306. uvs.push(faceUV[index].x, faceUV[index].w);
  28307. if (faceColors) {
  28308. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28309. }
  28310. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28311. positions.push(vertex.x, vertex.y, vertex.z);
  28312. normals.push(normal.x, normal.y, normal.z);
  28313. uvs.push(faceUV[index].x, faceUV[index].y);
  28314. if (faceColors) {
  28315. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28316. }
  28317. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28318. positions.push(vertex.x, vertex.y, vertex.z);
  28319. normals.push(normal.x, normal.y, normal.z);
  28320. uvs.push(faceUV[index].z, faceUV[index].y);
  28321. if (faceColors) {
  28322. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28323. }
  28324. }
  28325. // sides
  28326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28327. // Result
  28328. var vertexData = new VertexData();
  28329. vertexData.indices = indices;
  28330. vertexData.positions = positions;
  28331. vertexData.normals = normals;
  28332. vertexData.uvs = uvs;
  28333. if (faceColors) {
  28334. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28335. vertexData.colors = totalColors;
  28336. }
  28337. return vertexData;
  28338. };
  28339. VertexData.CreateSphere = function (options) {
  28340. var segments = options.segments || 32;
  28341. var diameterX = options.diameterX || options.diameter || 1;
  28342. var diameterY = options.diameterY || options.diameter || 1;
  28343. var diameterZ = options.diameterZ || options.diameter || 1;
  28344. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28345. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28346. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28347. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28348. var totalZRotationSteps = 2 + segments;
  28349. var totalYRotationSteps = 2 * totalZRotationSteps;
  28350. var indices = [];
  28351. var positions = [];
  28352. var normals = [];
  28353. var uvs = [];
  28354. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28355. var normalizedZ = zRotationStep / totalZRotationSteps;
  28356. var angleZ = normalizedZ * Math.PI * slice;
  28357. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28358. var normalizedY = yRotationStep / totalYRotationSteps;
  28359. var angleY = normalizedY * Math.PI * 2 * arc;
  28360. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28361. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28362. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28363. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28364. var vertex = complete.multiply(radius);
  28365. var normal = complete.divide(radius).normalize();
  28366. positions.push(vertex.x, vertex.y, vertex.z);
  28367. normals.push(normal.x, normal.y, normal.z);
  28368. uvs.push(normalizedY, normalizedZ);
  28369. }
  28370. if (zRotationStep > 0) {
  28371. var verticesCount = positions.length / 3;
  28372. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28373. indices.push((firstIndex));
  28374. indices.push((firstIndex + 1));
  28375. indices.push(firstIndex + totalYRotationSteps + 1);
  28376. indices.push((firstIndex + totalYRotationSteps + 1));
  28377. indices.push((firstIndex + 1));
  28378. indices.push((firstIndex + totalYRotationSteps + 2));
  28379. }
  28380. }
  28381. }
  28382. // Sides
  28383. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28384. // Result
  28385. var vertexData = new VertexData();
  28386. vertexData.indices = indices;
  28387. vertexData.positions = positions;
  28388. vertexData.normals = normals;
  28389. vertexData.uvs = uvs;
  28390. return vertexData;
  28391. };
  28392. // Cylinder and cone
  28393. VertexData.CreateCylinder = function (options) {
  28394. var height = options.height || 2;
  28395. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28396. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28397. var tessellation = options.tessellation || 24;
  28398. var subdivisions = options.subdivisions || 1;
  28399. var hasRings = options.hasRings;
  28400. var enclose = options.enclose;
  28401. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28402. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28403. var faceUV = options.faceUV || new Array(3);
  28404. var faceColors = options.faceColors;
  28405. // default face colors and UV if undefined
  28406. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28407. var ringNb = (hasRings) ? subdivisions : 1;
  28408. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28409. var f;
  28410. for (f = 0; f < surfaceNb; f++) {
  28411. if (faceColors && faceColors[f] === undefined) {
  28412. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28413. }
  28414. }
  28415. for (f = 0; f < surfaceNb; f++) {
  28416. if (faceUV && faceUV[f] === undefined) {
  28417. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28418. }
  28419. }
  28420. var indices = [];
  28421. var positions = [];
  28422. var normals = [];
  28423. var uvs = [];
  28424. var colors = [];
  28425. var angle_step = Math.PI * 2 * arc / tessellation;
  28426. var angle;
  28427. var h;
  28428. var radius;
  28429. var tan = (diameterBottom - diameterTop) / 2 / height;
  28430. var ringVertex = BABYLON.Vector3.Zero();
  28431. var ringNormal = BABYLON.Vector3.Zero();
  28432. var ringFirstVertex = BABYLON.Vector3.Zero();
  28433. var ringFirstNormal = BABYLON.Vector3.Zero();
  28434. var quadNormal = BABYLON.Vector3.Zero();
  28435. var Y = BABYLON.Axis.Y;
  28436. // positions, normals, uvs
  28437. var i;
  28438. var j;
  28439. var r;
  28440. var ringIdx = 1;
  28441. var s = 1; // surface index
  28442. var cs = 0;
  28443. var v = 0;
  28444. for (i = 0; i <= subdivisions; i++) {
  28445. h = i / subdivisions;
  28446. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28447. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28448. for (r = 0; r < ringIdx; r++) {
  28449. if (hasRings) {
  28450. s += r;
  28451. }
  28452. if (enclose) {
  28453. s += 2 * r;
  28454. }
  28455. for (j = 0; j <= tessellation; j++) {
  28456. angle = j * angle_step;
  28457. // position
  28458. ringVertex.x = Math.cos(-angle) * radius;
  28459. ringVertex.y = -height / 2 + h * height;
  28460. ringVertex.z = Math.sin(-angle) * radius;
  28461. // normal
  28462. if (diameterTop === 0 && i === subdivisions) {
  28463. // if no top cap, reuse former normals
  28464. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28465. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28466. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28467. }
  28468. else {
  28469. ringNormal.x = ringVertex.x;
  28470. ringNormal.z = ringVertex.z;
  28471. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28472. ringNormal.normalize();
  28473. }
  28474. // keep first ring vertex values for enclose
  28475. if (j === 0) {
  28476. ringFirstVertex.copyFrom(ringVertex);
  28477. ringFirstNormal.copyFrom(ringNormal);
  28478. }
  28479. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28480. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28481. if (hasRings) {
  28482. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28483. }
  28484. else {
  28485. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28486. }
  28487. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28488. if (faceColors) {
  28489. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28490. }
  28491. }
  28492. // if enclose, add four vertices and their dedicated normals
  28493. if (arc !== 1 && enclose) {
  28494. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28495. positions.push(0, ringVertex.y, 0);
  28496. positions.push(0, ringVertex.y, 0);
  28497. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28498. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28499. quadNormal.normalize();
  28500. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28501. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28502. quadNormal.normalize();
  28503. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28504. if (hasRings) {
  28505. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28506. }
  28507. else {
  28508. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28509. }
  28510. uvs.push(faceUV[s + 1].x, v);
  28511. uvs.push(faceUV[s + 1].z, v);
  28512. if (hasRings) {
  28513. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28514. }
  28515. else {
  28516. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28517. }
  28518. uvs.push(faceUV[s + 2].x, v);
  28519. uvs.push(faceUV[s + 2].z, v);
  28520. if (faceColors) {
  28521. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28522. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28523. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28524. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28525. }
  28526. }
  28527. if (cs !== s) {
  28528. cs = s;
  28529. }
  28530. }
  28531. }
  28532. // indices
  28533. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28534. var s;
  28535. i = 0;
  28536. for (s = 0; s < subdivisions; s++) {
  28537. for (j = 0; j < tessellation; j++) {
  28538. var i0 = i * (e + 1) + j;
  28539. var i1 = (i + 1) * (e + 1) + j;
  28540. var i2 = i * (e + 1) + (j + 1);
  28541. var i3 = (i + 1) * (e + 1) + (j + 1);
  28542. indices.push(i0, i1, i2);
  28543. indices.push(i3, i2, i1);
  28544. }
  28545. if (arc !== 1 && enclose) {
  28546. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28547. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28548. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28549. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28550. }
  28551. i = (hasRings) ? (i + 2) : (i + 1);
  28552. }
  28553. // Caps
  28554. var createCylinderCap = function (isTop) {
  28555. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28556. if (radius === 0) {
  28557. return;
  28558. }
  28559. // Cap positions, normals & uvs
  28560. var angle;
  28561. var circleVector;
  28562. var i;
  28563. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28564. var c;
  28565. if (faceColors) {
  28566. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28567. }
  28568. // cap center
  28569. var vbase = positions.length / 3;
  28570. var offset = isTop ? height / 2 : -height / 2;
  28571. var center = new BABYLON.Vector3(0, offset, 0);
  28572. positions.push(center.x, center.y, center.z);
  28573. normals.push(0, isTop ? 1 : -1, 0);
  28574. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28575. if (faceColors) {
  28576. colors.push(c.r, c.g, c.b, c.a);
  28577. }
  28578. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28579. for (i = 0; i <= tessellation; i++) {
  28580. angle = Math.PI * 2 * i * arc / tessellation;
  28581. var cos = Math.cos(-angle);
  28582. var sin = Math.sin(-angle);
  28583. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28584. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28585. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28586. normals.push(0, isTop ? 1 : -1, 0);
  28587. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28588. if (faceColors) {
  28589. colors.push(c.r, c.g, c.b, c.a);
  28590. }
  28591. }
  28592. // Cap indices
  28593. for (i = 0; i < tessellation; i++) {
  28594. if (!isTop) {
  28595. indices.push(vbase);
  28596. indices.push(vbase + (i + 1));
  28597. indices.push(vbase + (i + 2));
  28598. }
  28599. else {
  28600. indices.push(vbase);
  28601. indices.push(vbase + (i + 2));
  28602. indices.push(vbase + (i + 1));
  28603. }
  28604. }
  28605. };
  28606. // add caps to geometry
  28607. createCylinderCap(false);
  28608. createCylinderCap(true);
  28609. // Sides
  28610. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28611. var vertexData = new VertexData();
  28612. vertexData.indices = indices;
  28613. vertexData.positions = positions;
  28614. vertexData.normals = normals;
  28615. vertexData.uvs = uvs;
  28616. if (faceColors) {
  28617. vertexData.colors = colors;
  28618. }
  28619. return vertexData;
  28620. };
  28621. VertexData.CreateTorus = function (options) {
  28622. var indices = [];
  28623. var positions = [];
  28624. var normals = [];
  28625. var uvs = [];
  28626. var diameter = options.diameter || 1;
  28627. var thickness = options.thickness || 0.5;
  28628. var tessellation = options.tessellation || 16;
  28629. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28630. var stride = tessellation + 1;
  28631. for (var i = 0; i <= tessellation; i++) {
  28632. var u = i / tessellation;
  28633. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28634. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28635. for (var j = 0; j <= tessellation; j++) {
  28636. var v = 1 - j / tessellation;
  28637. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28638. var dx = Math.cos(innerAngle);
  28639. var dy = Math.sin(innerAngle);
  28640. // Create a vertex.
  28641. var normal = new BABYLON.Vector3(dx, dy, 0);
  28642. var position = normal.scale(thickness / 2);
  28643. var textureCoordinate = new BABYLON.Vector2(u, v);
  28644. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28645. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28646. positions.push(position.x, position.y, position.z);
  28647. normals.push(normal.x, normal.y, normal.z);
  28648. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28649. // And create indices for two triangles.
  28650. var nextI = (i + 1) % stride;
  28651. var nextJ = (j + 1) % stride;
  28652. indices.push(i * stride + j);
  28653. indices.push(i * stride + nextJ);
  28654. indices.push(nextI * stride + j);
  28655. indices.push(i * stride + nextJ);
  28656. indices.push(nextI * stride + nextJ);
  28657. indices.push(nextI * stride + j);
  28658. }
  28659. }
  28660. // Sides
  28661. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28662. // Result
  28663. var vertexData = new VertexData();
  28664. vertexData.indices = indices;
  28665. vertexData.positions = positions;
  28666. vertexData.normals = normals;
  28667. vertexData.uvs = uvs;
  28668. return vertexData;
  28669. };
  28670. VertexData.CreateLineSystem = function (options) {
  28671. var indices = [];
  28672. var positions = [];
  28673. var lines = options.lines;
  28674. var idx = 0;
  28675. for (var l = 0; l < lines.length; l++) {
  28676. var points = lines[l];
  28677. for (var index = 0; index < points.length; index++) {
  28678. positions.push(points[index].x, points[index].y, points[index].z);
  28679. if (index > 0) {
  28680. indices.push(idx - 1);
  28681. indices.push(idx);
  28682. }
  28683. idx++;
  28684. }
  28685. }
  28686. var vertexData = new VertexData();
  28687. vertexData.indices = indices;
  28688. vertexData.positions = positions;
  28689. return vertexData;
  28690. };
  28691. VertexData.CreateDashedLines = function (options) {
  28692. var dashSize = options.dashSize || 3;
  28693. var gapSize = options.gapSize || 1;
  28694. var dashNb = options.dashNb || 200;
  28695. var points = options.points;
  28696. var positions = new Array();
  28697. var indices = new Array();
  28698. var curvect = BABYLON.Vector3.Zero();
  28699. var lg = 0;
  28700. var nb = 0;
  28701. var shft = 0;
  28702. var dashshft = 0;
  28703. var curshft = 0;
  28704. var idx = 0;
  28705. var i = 0;
  28706. for (i = 0; i < points.length - 1; i++) {
  28707. points[i + 1].subtractToRef(points[i], curvect);
  28708. lg += curvect.length();
  28709. }
  28710. shft = lg / dashNb;
  28711. dashshft = dashSize * shft / (dashSize + gapSize);
  28712. for (i = 0; i < points.length - 1; i++) {
  28713. points[i + 1].subtractToRef(points[i], curvect);
  28714. nb = Math.floor(curvect.length() / shft);
  28715. curvect.normalize();
  28716. for (var j = 0; j < nb; j++) {
  28717. curshft = shft * j;
  28718. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28719. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28720. indices.push(idx, idx + 1);
  28721. idx += 2;
  28722. }
  28723. }
  28724. // Result
  28725. var vertexData = new VertexData();
  28726. vertexData.positions = positions;
  28727. vertexData.indices = indices;
  28728. return vertexData;
  28729. };
  28730. VertexData.CreateGround = function (options) {
  28731. var indices = [];
  28732. var positions = [];
  28733. var normals = [];
  28734. var uvs = [];
  28735. var row, col;
  28736. var width = options.width || 1;
  28737. var height = options.height || 1;
  28738. var subdivisions = options.subdivisions || 1;
  28739. for (row = 0; row <= subdivisions; row++) {
  28740. for (col = 0; col <= subdivisions; col++) {
  28741. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28742. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28743. positions.push(position.x, position.y, position.z);
  28744. normals.push(normal.x, normal.y, normal.z);
  28745. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28746. }
  28747. }
  28748. for (row = 0; row < subdivisions; row++) {
  28749. for (col = 0; col < subdivisions; col++) {
  28750. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28751. indices.push(col + 1 + row * (subdivisions + 1));
  28752. indices.push(col + row * (subdivisions + 1));
  28753. indices.push(col + (row + 1) * (subdivisions + 1));
  28754. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28755. indices.push(col + row * (subdivisions + 1));
  28756. }
  28757. }
  28758. // Result
  28759. var vertexData = new VertexData();
  28760. vertexData.indices = indices;
  28761. vertexData.positions = positions;
  28762. vertexData.normals = normals;
  28763. vertexData.uvs = uvs;
  28764. return vertexData;
  28765. };
  28766. VertexData.CreateTiledGround = function (options) {
  28767. var xmin = options.xmin;
  28768. var zmin = options.zmin;
  28769. var xmax = options.xmax;
  28770. var zmax = options.zmax;
  28771. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28772. var precision = options.precision || { w: 1, h: 1 };
  28773. var indices = [];
  28774. var positions = [];
  28775. var normals = [];
  28776. var uvs = [];
  28777. var row, col, tileRow, tileCol;
  28778. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28779. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28780. precision.w = (precision.w < 1) ? 1 : precision.w;
  28781. precision.h = (precision.h < 1) ? 1 : precision.h;
  28782. var tileSize = {
  28783. 'w': (xmax - xmin) / subdivisions.w,
  28784. 'h': (zmax - zmin) / subdivisions.h
  28785. };
  28786. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28787. // Indices
  28788. var base = positions.length / 3;
  28789. var rowLength = precision.w + 1;
  28790. for (row = 0; row < precision.h; row++) {
  28791. for (col = 0; col < precision.w; col++) {
  28792. var square = [
  28793. base + col + row * rowLength,
  28794. base + (col + 1) + row * rowLength,
  28795. base + (col + 1) + (row + 1) * rowLength,
  28796. base + col + (row + 1) * rowLength
  28797. ];
  28798. indices.push(square[1]);
  28799. indices.push(square[2]);
  28800. indices.push(square[3]);
  28801. indices.push(square[0]);
  28802. indices.push(square[1]);
  28803. indices.push(square[3]);
  28804. }
  28805. }
  28806. // Position, normals and uvs
  28807. var position = BABYLON.Vector3.Zero();
  28808. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28809. for (row = 0; row <= precision.h; row++) {
  28810. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28811. for (col = 0; col <= precision.w; col++) {
  28812. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28813. position.y = 0;
  28814. positions.push(position.x, position.y, position.z);
  28815. normals.push(normal.x, normal.y, normal.z);
  28816. uvs.push(col / precision.w, row / precision.h);
  28817. }
  28818. }
  28819. }
  28820. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28821. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28822. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28823. }
  28824. }
  28825. // Result
  28826. var vertexData = new VertexData();
  28827. vertexData.indices = indices;
  28828. vertexData.positions = positions;
  28829. vertexData.normals = normals;
  28830. vertexData.uvs = uvs;
  28831. return vertexData;
  28832. };
  28833. VertexData.CreateGroundFromHeightMap = function (options) {
  28834. var indices = [];
  28835. var positions = [];
  28836. var normals = [];
  28837. var uvs = [];
  28838. var row, col;
  28839. // Vertices
  28840. for (row = 0; row <= options.subdivisions; row++) {
  28841. for (col = 0; col <= options.subdivisions; col++) {
  28842. 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));
  28843. // Compute height
  28844. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28845. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28846. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28847. var r = options.buffer[pos] / 255.0;
  28848. var g = options.buffer[pos + 1] / 255.0;
  28849. var b = options.buffer[pos + 2] / 255.0;
  28850. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28851. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28852. // Add vertex
  28853. positions.push(position.x, position.y, position.z);
  28854. normals.push(0, 0, 0);
  28855. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28856. }
  28857. }
  28858. // Indices
  28859. for (row = 0; row < options.subdivisions; row++) {
  28860. for (col = 0; col < options.subdivisions; col++) {
  28861. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28862. indices.push(col + 1 + row * (options.subdivisions + 1));
  28863. indices.push(col + row * (options.subdivisions + 1));
  28864. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28865. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28866. indices.push(col + row * (options.subdivisions + 1));
  28867. }
  28868. }
  28869. // Normals
  28870. VertexData.ComputeNormals(positions, indices, normals);
  28871. // Result
  28872. var vertexData = new VertexData();
  28873. vertexData.indices = indices;
  28874. vertexData.positions = positions;
  28875. vertexData.normals = normals;
  28876. vertexData.uvs = uvs;
  28877. return vertexData;
  28878. };
  28879. VertexData.CreatePlane = function (options) {
  28880. var indices = [];
  28881. var positions = [];
  28882. var normals = [];
  28883. var uvs = [];
  28884. var width = options.width || options.size || 1;
  28885. var height = options.height || options.size || 1;
  28886. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28887. // Vertices
  28888. var halfWidth = width / 2.0;
  28889. var halfHeight = height / 2.0;
  28890. positions.push(-halfWidth, -halfHeight, 0);
  28891. normals.push(0, 0, -1.0);
  28892. uvs.push(0.0, 0.0);
  28893. positions.push(halfWidth, -halfHeight, 0);
  28894. normals.push(0, 0, -1.0);
  28895. uvs.push(1.0, 0.0);
  28896. positions.push(halfWidth, halfHeight, 0);
  28897. normals.push(0, 0, -1.0);
  28898. uvs.push(1.0, 1.0);
  28899. positions.push(-halfWidth, halfHeight, 0);
  28900. normals.push(0, 0, -1.0);
  28901. uvs.push(0.0, 1.0);
  28902. // Indices
  28903. indices.push(0);
  28904. indices.push(1);
  28905. indices.push(2);
  28906. indices.push(0);
  28907. indices.push(2);
  28908. indices.push(3);
  28909. // Sides
  28910. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28911. // Result
  28912. var vertexData = new VertexData();
  28913. vertexData.indices = indices;
  28914. vertexData.positions = positions;
  28915. vertexData.normals = normals;
  28916. vertexData.uvs = uvs;
  28917. return vertexData;
  28918. };
  28919. VertexData.CreateDisc = function (options) {
  28920. var positions = [];
  28921. var indices = [];
  28922. var normals = [];
  28923. var uvs = [];
  28924. var radius = options.radius || 0.5;
  28925. var tessellation = options.tessellation || 64;
  28926. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28927. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28928. // positions and uvs
  28929. positions.push(0, 0, 0); // disc center first
  28930. uvs.push(0.5, 0.5);
  28931. var theta = Math.PI * 2 * arc;
  28932. var step = theta / tessellation;
  28933. for (var a = 0; a < theta; a += step) {
  28934. var x = Math.cos(a);
  28935. var y = Math.sin(a);
  28936. var u = (x + 1) / 2;
  28937. var v = (1 - y) / 2;
  28938. positions.push(radius * x, radius * y, 0);
  28939. uvs.push(u, v);
  28940. }
  28941. if (arc === 1) {
  28942. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28943. uvs.push(uvs[2], uvs[3]);
  28944. }
  28945. //indices
  28946. var vertexNb = positions.length / 3;
  28947. for (var i = 1; i < vertexNb - 1; i++) {
  28948. indices.push(i + 1, 0, i);
  28949. }
  28950. // result
  28951. VertexData.ComputeNormals(positions, indices, normals);
  28952. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28953. var vertexData = new VertexData();
  28954. vertexData.indices = indices;
  28955. vertexData.positions = positions;
  28956. vertexData.normals = normals;
  28957. vertexData.uvs = uvs;
  28958. return vertexData;
  28959. };
  28960. VertexData.CreateIcoSphere = function (options) {
  28961. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28962. var radius = options.radius || 1;
  28963. var flat = (options.flat === undefined) ? true : options.flat;
  28964. var subdivisions = options.subdivisions || 4;
  28965. var radiusX = options.radiusX || radius;
  28966. var radiusY = options.radiusY || radius;
  28967. var radiusZ = options.radiusZ || radius;
  28968. var t = (1 + Math.sqrt(5)) / 2;
  28969. // 12 vertex x,y,z
  28970. var ico_vertices = [
  28971. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28972. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28973. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28974. ];
  28975. // index of 3 vertex makes a face of icopshere
  28976. var ico_indices = [
  28977. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28978. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28979. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28980. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28981. ];
  28982. // vertex for uv have aliased position, not for UV
  28983. var vertices_unalias_id = [
  28984. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28985. // vertex alias
  28986. 0,
  28987. 2,
  28988. 3,
  28989. 3,
  28990. 3,
  28991. 4,
  28992. 7,
  28993. 8,
  28994. 9,
  28995. 9,
  28996. 10,
  28997. 11 // 23: B + 12
  28998. ];
  28999. // uv as integer step (not pixels !)
  29000. var ico_vertexuv = [
  29001. 5, 1, 3, 1, 6, 4, 0, 0,
  29002. 5, 3, 4, 2, 2, 2, 4, 0,
  29003. 2, 0, 1, 1, 6, 0, 6, 2,
  29004. // vertex alias (for same vertex on different faces)
  29005. 0, 4,
  29006. 3, 3,
  29007. 4, 4,
  29008. 3, 1,
  29009. 4, 2,
  29010. 4, 4,
  29011. 0, 2,
  29012. 1, 1,
  29013. 2, 2,
  29014. 3, 3,
  29015. 1, 3,
  29016. 2, 4 // 23: B + 12
  29017. ];
  29018. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29019. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29020. // First island of uv mapping
  29021. // v = 4h 3+ 2
  29022. // v = 3h 9+ 4
  29023. // v = 2h 9+ 5 B
  29024. // v = 1h 9 1 0
  29025. // v = 0h 3 8 7 A
  29026. // u = 0 1 2 3 4 5 6 *a
  29027. // Second island of uv mapping
  29028. // v = 4h 0+ B+ 4+
  29029. // v = 3h A+ 2+
  29030. // v = 2h 7+ 6 3+
  29031. // v = 1h 8+ 3+
  29032. // v = 0h
  29033. // u = 0 1 2 3 4 5 6 *a
  29034. // Face layout on texture UV mapping
  29035. // ============
  29036. // \ 4 /\ 16 / ======
  29037. // \ / \ / /\ 11 /
  29038. // \/ 7 \/ / \ /
  29039. // ======= / 10 \/
  29040. // /\ 17 /\ =======
  29041. // / \ / \ \ 15 /\
  29042. // / 8 \/ 12 \ \ / \
  29043. // ============ \/ 6 \
  29044. // \ 18 /\ ============
  29045. // \ / \ \ 5 /\ 0 /
  29046. // \/ 13 \ \ / \ /
  29047. // ======= \/ 1 \/
  29048. // =============
  29049. // /\ 19 /\ 2 /\
  29050. // / \ / \ / \
  29051. // / 14 \/ 9 \/ 3 \
  29052. // ===================
  29053. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29054. var ustep = 138 / 1024;
  29055. var vstep = 239 / 1024;
  29056. var uoffset = 60 / 1024;
  29057. var voffset = 26 / 1024;
  29058. // Second island should have margin, not to touch the first island
  29059. // avoid any borderline artefact in pixel rounding
  29060. var island_u_offset = -40 / 1024;
  29061. var island_v_offset = +20 / 1024;
  29062. // face is either island 0 or 1 :
  29063. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29064. var island = [
  29065. 0, 0, 0, 0, 1,
  29066. 0, 0, 1, 1, 0,
  29067. 0, 0, 1, 1, 0,
  29068. 0, 1, 1, 1, 0 // 15 - 19
  29069. ];
  29070. var indices = [];
  29071. var positions = [];
  29072. var normals = [];
  29073. var uvs = [];
  29074. var current_indice = 0;
  29075. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29076. var face_vertex_pos = new Array(3);
  29077. var face_vertex_uv = new Array(3);
  29078. var v012;
  29079. for (v012 = 0; v012 < 3; v012++) {
  29080. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29081. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29082. }
  29083. // create all with normals
  29084. for (var face = 0; face < 20; face++) {
  29085. // 3 vertex per face
  29086. for (v012 = 0; v012 < 3; v012++) {
  29087. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29088. var v_id = ico_indices[3 * face + v012];
  29089. // vertex have 3D position (x,y,z)
  29090. 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]);
  29091. // Normalize to get normal, then scale to radius
  29092. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29093. // uv Coordinates from vertex ID
  29094. 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);
  29095. }
  29096. // Subdivide the face (interpolate pos, norm, uv)
  29097. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29098. // - norm is linear interpolation of vertex corner normal
  29099. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29100. // - uv is linear interpolation
  29101. //
  29102. // Topology is as below for sub-divide by 2
  29103. // vertex shown as v0,v1,v2
  29104. // interp index is i1 to progress in range [v0,v1[
  29105. // interp index is i2 to progress in range [v0,v2[
  29106. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29107. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29108. //
  29109. //
  29110. // i2 v2
  29111. // ^ ^
  29112. // / / \
  29113. // / / \
  29114. // / / \
  29115. // / / (0,1) \
  29116. // / #---------\
  29117. // / / \ (0,0)'/ \
  29118. // / / \ / \
  29119. // / / \ / \
  29120. // / / (0,0) \ / (1,0) \
  29121. // / #---------#---------\
  29122. // v0 v1
  29123. //
  29124. // --------------------> i1
  29125. //
  29126. // interp of (i1,i2):
  29127. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29128. // along i1 : lerp(x0,x1, i1/(S-i2))
  29129. //
  29130. // centroid of triangle is needed to get help normal computation
  29131. // (c1,c2) are used for centroid location
  29132. var interp_vertex = function (i1, i2, c1, c2) {
  29133. // vertex is interpolated from
  29134. // - face_vertex_pos[0..2]
  29135. // - face_vertex_uv[0..2]
  29136. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29137. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29138. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29139. pos_interp.normalize();
  29140. var vertex_normal;
  29141. if (flat) {
  29142. // in flat mode, recalculate normal as face centroid normal
  29143. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29144. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29145. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29146. }
  29147. else {
  29148. // in smooth mode, recalculate normal from each single vertex position
  29149. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29150. }
  29151. // Vertex normal need correction due to X,Y,Z radius scaling
  29152. vertex_normal.x /= radiusX;
  29153. vertex_normal.y /= radiusY;
  29154. vertex_normal.z /= radiusZ;
  29155. vertex_normal.normalize();
  29156. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29157. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29158. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29159. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29160. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29161. uvs.push(uv_interp.x, uv_interp.y);
  29162. // push each vertex has member of a face
  29163. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29164. indices.push(current_indice);
  29165. current_indice++;
  29166. };
  29167. for (var i2 = 0; i2 < subdivisions; i2++) {
  29168. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29169. // face : (i1,i2) for /\ :
  29170. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29171. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29172. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29173. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29174. if (i1 + i2 + 1 < subdivisions) {
  29175. // face : (i1,i2)' for \/ :
  29176. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29177. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29178. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29179. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29180. }
  29181. }
  29182. }
  29183. }
  29184. // Sides
  29185. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29186. // Result
  29187. var vertexData = new VertexData();
  29188. vertexData.indices = indices;
  29189. vertexData.positions = positions;
  29190. vertexData.normals = normals;
  29191. vertexData.uvs = uvs;
  29192. return vertexData;
  29193. };
  29194. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29195. VertexData.CreatePolyhedron = function (options) {
  29196. // provided polyhedron types :
  29197. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29198. // 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)
  29199. var polyhedra = [];
  29200. 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]] };
  29201. 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]] };
  29202. polyhedra[2] = {
  29203. 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]],
  29204. 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]]
  29205. };
  29206. polyhedra[3] = {
  29207. 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]],
  29208. 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]]
  29209. };
  29210. polyhedra[4] = {
  29211. 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]],
  29212. 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]]
  29213. };
  29214. 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]] };
  29215. 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]] };
  29216. 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]] };
  29217. 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]] };
  29218. 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]] };
  29219. 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]] };
  29220. 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]] };
  29221. 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]] };
  29222. 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]] };
  29223. polyhedra[14] = {
  29224. 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]],
  29225. 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]]
  29226. };
  29227. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29228. var size = options.size;
  29229. var sizeX = options.sizeX || size || 1;
  29230. var sizeY = options.sizeY || size || 1;
  29231. var sizeZ = options.sizeZ || size || 1;
  29232. var data = options.custom || polyhedra[type];
  29233. var nbfaces = data.face.length;
  29234. var faceUV = options.faceUV || new Array(nbfaces);
  29235. var faceColors = options.faceColors;
  29236. var flat = (options.flat === undefined) ? true : options.flat;
  29237. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29238. var positions = [];
  29239. var indices = [];
  29240. var normals = [];
  29241. var uvs = [];
  29242. var colors = [];
  29243. var index = 0;
  29244. var faceIdx = 0; // face cursor in the array "indexes"
  29245. var indexes = [];
  29246. var i = 0;
  29247. var f = 0;
  29248. var u, v, ang, x, y, tmp;
  29249. // default face colors and UV if undefined
  29250. if (flat) {
  29251. for (f = 0; f < nbfaces; f++) {
  29252. if (faceColors && faceColors[f] === undefined) {
  29253. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29254. }
  29255. if (faceUV && faceUV[f] === undefined) {
  29256. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29257. }
  29258. }
  29259. }
  29260. if (!flat) {
  29261. for (i = 0; i < data.vertex.length; i++) {
  29262. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29263. uvs.push(0, 0);
  29264. }
  29265. for (f = 0; f < nbfaces; f++) {
  29266. for (i = 0; i < data.face[f].length - 2; i++) {
  29267. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29268. }
  29269. }
  29270. }
  29271. else {
  29272. for (f = 0; f < nbfaces; f++) {
  29273. var fl = data.face[f].length; // number of vertices of the current face
  29274. ang = 2 * Math.PI / fl;
  29275. x = 0.5 * Math.tan(ang / 2);
  29276. y = 0.5;
  29277. // positions, uvs, colors
  29278. for (i = 0; i < fl; i++) {
  29279. // positions
  29280. 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);
  29281. indexes.push(index);
  29282. index++;
  29283. // uvs
  29284. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29285. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29286. uvs.push(u, v);
  29287. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29288. y = x * Math.sin(ang) + y * Math.cos(ang);
  29289. x = tmp;
  29290. // colors
  29291. if (faceColors) {
  29292. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29293. }
  29294. }
  29295. // indices from indexes
  29296. for (i = 0; i < fl - 2; i++) {
  29297. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29298. }
  29299. faceIdx += fl;
  29300. }
  29301. }
  29302. VertexData.ComputeNormals(positions, indices, normals);
  29303. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29304. var vertexData = new VertexData();
  29305. vertexData.positions = positions;
  29306. vertexData.indices = indices;
  29307. vertexData.normals = normals;
  29308. vertexData.uvs = uvs;
  29309. if (faceColors && flat) {
  29310. vertexData.colors = colors;
  29311. }
  29312. return vertexData;
  29313. };
  29314. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29315. VertexData.CreateTorusKnot = function (options) {
  29316. var indices = [];
  29317. var positions = [];
  29318. var normals = [];
  29319. var uvs = [];
  29320. var radius = options.radius || 2;
  29321. var tube = options.tube || 0.5;
  29322. var radialSegments = options.radialSegments || 32;
  29323. var tubularSegments = options.tubularSegments || 32;
  29324. var p = options.p || 2;
  29325. var q = options.q || 3;
  29326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29327. // Helper
  29328. var getPos = function (angle) {
  29329. var cu = Math.cos(angle);
  29330. var su = Math.sin(angle);
  29331. var quOverP = q / p * angle;
  29332. var cs = Math.cos(quOverP);
  29333. var tx = radius * (2 + cs) * 0.5 * cu;
  29334. var ty = radius * (2 + cs) * su * 0.5;
  29335. var tz = radius * Math.sin(quOverP) * 0.5;
  29336. return new BABYLON.Vector3(tx, ty, tz);
  29337. };
  29338. // Vertices
  29339. var i;
  29340. var j;
  29341. for (i = 0; i <= radialSegments; i++) {
  29342. var modI = i % radialSegments;
  29343. var u = modI / radialSegments * 2 * p * Math.PI;
  29344. var p1 = getPos(u);
  29345. var p2 = getPos(u + 0.01);
  29346. var tang = p2.subtract(p1);
  29347. var n = p2.add(p1);
  29348. var bitan = BABYLON.Vector3.Cross(tang, n);
  29349. n = BABYLON.Vector3.Cross(bitan, tang);
  29350. bitan.normalize();
  29351. n.normalize();
  29352. for (j = 0; j < tubularSegments; j++) {
  29353. var modJ = j % tubularSegments;
  29354. var v = modJ / tubularSegments * 2 * Math.PI;
  29355. var cx = -tube * Math.cos(v);
  29356. var cy = tube * Math.sin(v);
  29357. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29358. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29359. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29360. uvs.push(i / radialSegments);
  29361. uvs.push(j / tubularSegments);
  29362. }
  29363. }
  29364. for (i = 0; i < radialSegments; i++) {
  29365. for (j = 0; j < tubularSegments; j++) {
  29366. var jNext = (j + 1) % tubularSegments;
  29367. var a = i * tubularSegments + j;
  29368. var b = (i + 1) * tubularSegments + j;
  29369. var c = (i + 1) * tubularSegments + jNext;
  29370. var d = i * tubularSegments + jNext;
  29371. indices.push(d);
  29372. indices.push(b);
  29373. indices.push(a);
  29374. indices.push(d);
  29375. indices.push(c);
  29376. indices.push(b);
  29377. }
  29378. }
  29379. // Normals
  29380. VertexData.ComputeNormals(positions, indices, normals);
  29381. // Sides
  29382. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29383. // Result
  29384. var vertexData = new VertexData();
  29385. vertexData.indices = indices;
  29386. vertexData.positions = positions;
  29387. vertexData.normals = normals;
  29388. vertexData.uvs = uvs;
  29389. return vertexData;
  29390. };
  29391. // Tools
  29392. /**
  29393. * @param {any} - positions (number[] or Float32Array)
  29394. * @param {any} - indices (number[] or Uint16Array)
  29395. * @param {any} - normals (number[] or Float32Array)
  29396. */
  29397. VertexData.ComputeNormals = function (positions, indices, normals) {
  29398. var index = 0;
  29399. var p1p2x = 0.0;
  29400. var p1p2y = 0.0;
  29401. var p1p2z = 0.0;
  29402. var p3p2x = 0.0;
  29403. var p3p2y = 0.0;
  29404. var p3p2z = 0.0;
  29405. var faceNormalx = 0.0;
  29406. var faceNormaly = 0.0;
  29407. var faceNormalz = 0.0;
  29408. var length = 0.0;
  29409. var i1 = 0;
  29410. var i2 = 0;
  29411. var i3 = 0;
  29412. for (index = 0; index < positions.length; index++) {
  29413. normals[index] = 0.0;
  29414. }
  29415. // indice triplet = 1 face
  29416. var nbFaces = indices.length / 3;
  29417. for (index = 0; index < nbFaces; index++) {
  29418. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29419. i2 = indices[index * 3 + 1];
  29420. i3 = indices[index * 3 + 2];
  29421. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29422. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29423. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29424. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29425. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29426. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29427. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29428. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29429. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29430. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29431. length = (length === 0) ? 1.0 : length;
  29432. faceNormalx /= length; // normalize this normal
  29433. faceNormaly /= length;
  29434. faceNormalz /= length;
  29435. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29436. normals[i1 * 3 + 1] += faceNormaly;
  29437. normals[i1 * 3 + 2] += faceNormalz;
  29438. normals[i2 * 3] += faceNormalx;
  29439. normals[i2 * 3 + 1] += faceNormaly;
  29440. normals[i2 * 3 + 2] += faceNormalz;
  29441. normals[i3 * 3] += faceNormalx;
  29442. normals[i3 * 3 + 1] += faceNormaly;
  29443. normals[i3 * 3 + 2] += faceNormalz;
  29444. }
  29445. // last normalization of each normal
  29446. for (index = 0; index < normals.length / 3; index++) {
  29447. faceNormalx = normals[index * 3];
  29448. faceNormaly = normals[index * 3 + 1];
  29449. faceNormalz = normals[index * 3 + 2];
  29450. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29451. length = (length === 0) ? 1.0 : length;
  29452. faceNormalx /= length;
  29453. faceNormaly /= length;
  29454. faceNormalz /= length;
  29455. normals[index * 3] = faceNormalx;
  29456. normals[index * 3 + 1] = faceNormaly;
  29457. normals[index * 3 + 2] = faceNormalz;
  29458. }
  29459. };
  29460. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29461. var li = indices.length;
  29462. var ln = normals.length;
  29463. var i;
  29464. var n;
  29465. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29466. switch (sideOrientation) {
  29467. case BABYLON.Mesh.FRONTSIDE:
  29468. // nothing changed
  29469. break;
  29470. case BABYLON.Mesh.BACKSIDE:
  29471. var tmp;
  29472. // indices
  29473. for (i = 0; i < li; i += 3) {
  29474. tmp = indices[i];
  29475. indices[i] = indices[i + 2];
  29476. indices[i + 2] = tmp;
  29477. }
  29478. // normals
  29479. for (n = 0; n < ln; n++) {
  29480. normals[n] = -normals[n];
  29481. }
  29482. break;
  29483. case BABYLON.Mesh.DOUBLESIDE:
  29484. // positions
  29485. var lp = positions.length;
  29486. var l = lp / 3;
  29487. for (var p = 0; p < lp; p++) {
  29488. positions[lp + p] = positions[p];
  29489. }
  29490. // indices
  29491. for (i = 0; i < li; i += 3) {
  29492. indices[i + li] = indices[i + 2] + l;
  29493. indices[i + 1 + li] = indices[i + 1] + l;
  29494. indices[i + 2 + li] = indices[i] + l;
  29495. }
  29496. // normals
  29497. for (n = 0; n < ln; n++) {
  29498. normals[ln + n] = -normals[n];
  29499. }
  29500. // uvs
  29501. var lu = uvs.length;
  29502. for (var u = 0; u < lu; u++) {
  29503. uvs[u + lu] = uvs[u];
  29504. }
  29505. break;
  29506. }
  29507. };
  29508. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29509. var vertexData = new VertexData();
  29510. // positions
  29511. var positions = parsedVertexData.positions;
  29512. if (positions) {
  29513. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29514. }
  29515. // normals
  29516. var normals = parsedVertexData.normals;
  29517. if (normals) {
  29518. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29519. }
  29520. // uvs
  29521. var uvs = parsedVertexData.uvs;
  29522. if (uvs) {
  29523. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29524. }
  29525. // uv2s
  29526. var uv2s = parsedVertexData.uv2s;
  29527. if (uv2s) {
  29528. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29529. }
  29530. // uv3s
  29531. var uv3s = parsedVertexData.uv3s;
  29532. if (uv3s) {
  29533. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29534. }
  29535. // uv4s
  29536. var uv4s = parsedVertexData.uv4s;
  29537. if (uv4s) {
  29538. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29539. }
  29540. // uv5s
  29541. var uv5s = parsedVertexData.uv5s;
  29542. if (uv5s) {
  29543. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29544. }
  29545. // uv6s
  29546. var uv6s = parsedVertexData.uv6s;
  29547. if (uv6s) {
  29548. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29549. }
  29550. // colors
  29551. var colors = parsedVertexData.colors;
  29552. if (colors) {
  29553. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29554. }
  29555. // matricesIndices
  29556. var matricesIndices = parsedVertexData.matricesIndices;
  29557. if (matricesIndices) {
  29558. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29559. }
  29560. // matricesWeights
  29561. var matricesWeights = parsedVertexData.matricesWeights;
  29562. if (matricesWeights) {
  29563. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29564. }
  29565. // indices
  29566. var indices = parsedVertexData.indices;
  29567. if (indices) {
  29568. vertexData.indices = indices;
  29569. }
  29570. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29571. };
  29572. return VertexData;
  29573. })();
  29574. BABYLON.VertexData = VertexData;
  29575. })(BABYLON || (BABYLON = {}));
  29576. var BABYLON;
  29577. (function (BABYLON) {
  29578. var Tags = (function () {
  29579. function Tags() {
  29580. }
  29581. Tags.EnableFor = function (obj) {
  29582. obj._tags = obj._tags || {};
  29583. obj.hasTags = function () {
  29584. return Tags.HasTags(obj);
  29585. };
  29586. obj.addTags = function (tagsString) {
  29587. return Tags.AddTagsTo(obj, tagsString);
  29588. };
  29589. obj.removeTags = function (tagsString) {
  29590. return Tags.RemoveTagsFrom(obj, tagsString);
  29591. };
  29592. obj.matchesTagsQuery = function (tagsQuery) {
  29593. return Tags.MatchesQuery(obj, tagsQuery);
  29594. };
  29595. };
  29596. Tags.DisableFor = function (obj) {
  29597. delete obj._tags;
  29598. delete obj.hasTags;
  29599. delete obj.addTags;
  29600. delete obj.removeTags;
  29601. delete obj.matchesTagsQuery;
  29602. };
  29603. Tags.HasTags = function (obj) {
  29604. if (!obj._tags) {
  29605. return false;
  29606. }
  29607. return !BABYLON.Tools.IsEmpty(obj._tags);
  29608. };
  29609. Tags.GetTags = function (obj, asString) {
  29610. if (asString === void 0) { asString = true; }
  29611. if (!obj._tags) {
  29612. return null;
  29613. }
  29614. if (asString) {
  29615. var tagsArray = [];
  29616. for (var tag in obj._tags) {
  29617. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29618. tagsArray.push(tag);
  29619. }
  29620. }
  29621. return tagsArray.join(" ");
  29622. }
  29623. else {
  29624. return obj._tags;
  29625. }
  29626. };
  29627. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29628. // a tag cannot start with '||', '&&', and '!'
  29629. // it cannot contain whitespaces
  29630. Tags.AddTagsTo = function (obj, tagsString) {
  29631. if (!tagsString) {
  29632. return;
  29633. }
  29634. if (typeof tagsString !== "string") {
  29635. return;
  29636. }
  29637. var tags = tagsString.split(" ");
  29638. for (var t in tags) {
  29639. Tags._AddTagTo(obj, tags[t]);
  29640. }
  29641. };
  29642. Tags._AddTagTo = function (obj, tag) {
  29643. tag = tag.trim();
  29644. if (tag === "" || tag === "true" || tag === "false") {
  29645. return;
  29646. }
  29647. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29648. return;
  29649. }
  29650. Tags.EnableFor(obj);
  29651. obj._tags[tag] = true;
  29652. };
  29653. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29654. if (!Tags.HasTags(obj)) {
  29655. return;
  29656. }
  29657. var tags = tagsString.split(" ");
  29658. for (var t in tags) {
  29659. Tags._RemoveTagFrom(obj, tags[t]);
  29660. }
  29661. };
  29662. Tags._RemoveTagFrom = function (obj, tag) {
  29663. delete obj._tags[tag];
  29664. };
  29665. Tags.MatchesQuery = function (obj, tagsQuery) {
  29666. if (tagsQuery === undefined) {
  29667. return true;
  29668. }
  29669. if (tagsQuery === "") {
  29670. return Tags.HasTags(obj);
  29671. }
  29672. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29673. };
  29674. return Tags;
  29675. })();
  29676. BABYLON.Tags = Tags;
  29677. })(BABYLON || (BABYLON = {}));
  29678. var BABYLON;
  29679. (function (BABYLON) {
  29680. var Internals;
  29681. (function (Internals) {
  29682. var AndOrNotEvaluator = (function () {
  29683. function AndOrNotEvaluator() {
  29684. }
  29685. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29686. if (!query.match(/\([^\(\)]*\)/g)) {
  29687. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29688. }
  29689. else {
  29690. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29691. // remove parenthesis
  29692. r = r.slice(1, r.length - 1);
  29693. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29694. });
  29695. }
  29696. if (query === "true") {
  29697. return true;
  29698. }
  29699. if (query === "false") {
  29700. return false;
  29701. }
  29702. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29703. };
  29704. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29705. evaluateCallback = evaluateCallback || (function (r) {
  29706. return r === "true" ? true : false;
  29707. });
  29708. var result;
  29709. var or = parenthesisContent.split("||");
  29710. for (var i in or) {
  29711. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29712. var and = ori.split("&&");
  29713. if (and.length > 1) {
  29714. for (var j = 0; j < and.length; ++j) {
  29715. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29716. if (andj !== "true" && andj !== "false") {
  29717. if (andj[0] === "!") {
  29718. result = !evaluateCallback(andj.substring(1));
  29719. }
  29720. else {
  29721. result = evaluateCallback(andj);
  29722. }
  29723. }
  29724. else {
  29725. result = andj === "true" ? true : false;
  29726. }
  29727. if (!result) {
  29728. ori = "false";
  29729. break;
  29730. }
  29731. }
  29732. }
  29733. if (result || ori === "true") {
  29734. result = true;
  29735. break;
  29736. }
  29737. // result equals false (or undefined)
  29738. if (ori !== "true" && ori !== "false") {
  29739. if (ori[0] === "!") {
  29740. result = !evaluateCallback(ori.substring(1));
  29741. }
  29742. else {
  29743. result = evaluateCallback(ori);
  29744. }
  29745. }
  29746. else {
  29747. result = ori === "true" ? true : false;
  29748. }
  29749. }
  29750. // the whole parenthesis scope is replaced by 'true' or 'false'
  29751. return result ? "true" : "false";
  29752. };
  29753. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29754. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29755. // remove whitespaces
  29756. r = r.replace(/[\s]/g, function () { return ""; });
  29757. return r.length % 2 ? "!" : "";
  29758. });
  29759. booleanString = booleanString.trim();
  29760. if (booleanString === "!true") {
  29761. booleanString = "false";
  29762. }
  29763. else if (booleanString === "!false") {
  29764. booleanString = "true";
  29765. }
  29766. return booleanString;
  29767. };
  29768. return AndOrNotEvaluator;
  29769. })();
  29770. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29771. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29772. })(BABYLON || (BABYLON = {}));
  29773. var BABYLON;
  29774. (function (BABYLON) {
  29775. var PostProcessRenderPass = (function () {
  29776. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29777. this._enabled = true;
  29778. this._refCount = 0;
  29779. this._name = name;
  29780. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29781. this.setRenderList(renderList);
  29782. this._renderTexture.onBeforeRender = beforeRender;
  29783. this._renderTexture.onAfterRender = afterRender;
  29784. this._scene = scene;
  29785. this._renderList = renderList;
  29786. }
  29787. // private
  29788. PostProcessRenderPass.prototype._incRefCount = function () {
  29789. if (this._refCount === 0) {
  29790. this._scene.customRenderTargets.push(this._renderTexture);
  29791. }
  29792. return ++this._refCount;
  29793. };
  29794. PostProcessRenderPass.prototype._decRefCount = function () {
  29795. this._refCount--;
  29796. if (this._refCount <= 0) {
  29797. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29798. }
  29799. return this._refCount;
  29800. };
  29801. PostProcessRenderPass.prototype._update = function () {
  29802. this.setRenderList(this._renderList);
  29803. };
  29804. // public
  29805. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29806. this._renderTexture.renderList = renderList;
  29807. };
  29808. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29809. return this._renderTexture;
  29810. };
  29811. return PostProcessRenderPass;
  29812. })();
  29813. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29814. })(BABYLON || (BABYLON = {}));
  29815. var BABYLON;
  29816. (function (BABYLON) {
  29817. var PostProcessRenderEffect = (function () {
  29818. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29819. this._engine = engine;
  29820. this._name = name;
  29821. this._singleInstance = singleInstance || true;
  29822. this._getPostProcess = getPostProcess;
  29823. this._cameras = [];
  29824. this._indicesForCamera = [];
  29825. this._postProcesses = {};
  29826. this._renderPasses = {};
  29827. this._renderEffectAsPasses = {};
  29828. }
  29829. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29830. get: function () {
  29831. for (var index in this._postProcesses) {
  29832. if (!this._postProcesses[index].isSupported) {
  29833. return false;
  29834. }
  29835. }
  29836. return true;
  29837. },
  29838. enumerable: true,
  29839. configurable: true
  29840. });
  29841. PostProcessRenderEffect.prototype._update = function () {
  29842. for (var renderPassName in this._renderPasses) {
  29843. this._renderPasses[renderPassName]._update();
  29844. }
  29845. };
  29846. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29847. this._renderPasses[renderPass._name] = renderPass;
  29848. this._linkParameters();
  29849. };
  29850. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29851. delete this._renderPasses[renderPass._name];
  29852. this._linkParameters();
  29853. };
  29854. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29855. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29856. this._linkParameters();
  29857. };
  29858. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29859. for (var renderPassName in this._renderPasses) {
  29860. if (renderPassName === passName) {
  29861. return this._renderPasses[passName];
  29862. }
  29863. }
  29864. };
  29865. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29866. this._renderPasses = {};
  29867. this._linkParameters();
  29868. };
  29869. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29870. var cameraKey;
  29871. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29872. for (var i = 0; i < _cam.length; i++) {
  29873. var camera = _cam[i];
  29874. var cameraName = camera.name;
  29875. if (this._singleInstance) {
  29876. cameraKey = 0;
  29877. }
  29878. else {
  29879. cameraKey = cameraName;
  29880. }
  29881. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29882. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29883. if (!this._indicesForCamera[cameraName]) {
  29884. this._indicesForCamera[cameraName] = [];
  29885. }
  29886. this._indicesForCamera[cameraName].push(index);
  29887. if (this._cameras.indexOf(camera) === -1) {
  29888. this._cameras[cameraName] = camera;
  29889. }
  29890. for (var passName in this._renderPasses) {
  29891. this._renderPasses[passName]._incRefCount();
  29892. }
  29893. }
  29894. this._linkParameters();
  29895. };
  29896. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29897. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29898. for (var i = 0; i < _cam.length; i++) {
  29899. var camera = _cam[i];
  29900. var cameraName = camera.name;
  29901. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29902. var index = this._cameras.indexOf(cameraName);
  29903. this._indicesForCamera.splice(index, 1);
  29904. this._cameras.splice(index, 1);
  29905. for (var passName in this._renderPasses) {
  29906. this._renderPasses[passName]._decRefCount();
  29907. }
  29908. }
  29909. };
  29910. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29911. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29912. for (var i = 0; i < _cam.length; i++) {
  29913. var camera = _cam[i];
  29914. var cameraName = camera.name;
  29915. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29916. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29917. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29918. }
  29919. }
  29920. for (var passName in this._renderPasses) {
  29921. this._renderPasses[passName]._incRefCount();
  29922. }
  29923. }
  29924. };
  29925. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29926. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29927. for (var i = 0; i < _cam.length; i++) {
  29928. var camera = _cam[i];
  29929. var cameraName = camera.Name;
  29930. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29931. for (var passName in this._renderPasses) {
  29932. this._renderPasses[passName]._decRefCount();
  29933. }
  29934. }
  29935. };
  29936. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29937. if (this._singleInstance) {
  29938. return this._postProcesses[0];
  29939. }
  29940. else {
  29941. return this._postProcesses[camera.name];
  29942. }
  29943. };
  29944. PostProcessRenderEffect.prototype._linkParameters = function () {
  29945. var _this = this;
  29946. for (var index in this._postProcesses) {
  29947. if (this.applyParameters) {
  29948. this.applyParameters(this._postProcesses[index]);
  29949. }
  29950. this._postProcesses[index].onBeforeRender = function (effect) {
  29951. _this._linkTextures(effect);
  29952. };
  29953. }
  29954. };
  29955. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29956. for (var renderPassName in this._renderPasses) {
  29957. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29958. }
  29959. for (var renderEffectName in this._renderEffectAsPasses) {
  29960. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29961. }
  29962. };
  29963. return PostProcessRenderEffect;
  29964. })();
  29965. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29966. })(BABYLON || (BABYLON = {}));
  29967. var BABYLON;
  29968. (function (BABYLON) {
  29969. var PostProcessRenderPipeline = (function () {
  29970. function PostProcessRenderPipeline(engine, name) {
  29971. this._engine = engine;
  29972. this._name = name;
  29973. this._renderEffects = {};
  29974. this._renderEffectsForIsolatedPass = {};
  29975. this._cameras = [];
  29976. }
  29977. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29978. get: function () {
  29979. for (var renderEffectName in this._renderEffects) {
  29980. if (!this._renderEffects[renderEffectName].isSupported) {
  29981. return false;
  29982. }
  29983. }
  29984. return true;
  29985. },
  29986. enumerable: true,
  29987. configurable: true
  29988. });
  29989. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29990. this._renderEffects[renderEffect._name] = renderEffect;
  29991. };
  29992. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29993. var renderEffects = this._renderEffects[renderEffectName];
  29994. if (!renderEffects) {
  29995. return;
  29996. }
  29997. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29998. };
  29999. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  30000. var renderEffects = this._renderEffects[renderEffectName];
  30001. if (!renderEffects) {
  30002. return;
  30003. }
  30004. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  30005. };
  30006. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  30007. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30008. var indicesToDelete = [];
  30009. var i;
  30010. for (i = 0; i < _cam.length; i++) {
  30011. var camera = _cam[i];
  30012. var cameraName = camera.name;
  30013. if (this._cameras.indexOf(camera) === -1) {
  30014. this._cameras[cameraName] = camera;
  30015. }
  30016. else if (unique) {
  30017. indicesToDelete.push(i);
  30018. }
  30019. }
  30020. for (i = 0; i < indicesToDelete.length; i++) {
  30021. cameras.splice(indicesToDelete[i], 1);
  30022. }
  30023. for (var renderEffectName in this._renderEffects) {
  30024. this._renderEffects[renderEffectName]._attachCameras(_cam);
  30025. }
  30026. };
  30027. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  30028. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30029. for (var renderEffectName in this._renderEffects) {
  30030. this._renderEffects[renderEffectName]._detachCameras(_cam);
  30031. }
  30032. for (var i = 0; i < _cam.length; i++) {
  30033. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  30034. }
  30035. };
  30036. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  30037. var _this = this;
  30038. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30039. var pass = null;
  30040. var renderEffectName;
  30041. for (renderEffectName in this._renderEffects) {
  30042. pass = this._renderEffects[renderEffectName].getPass(passName);
  30043. if (pass != null) {
  30044. break;
  30045. }
  30046. }
  30047. if (pass === null) {
  30048. return;
  30049. }
  30050. for (renderEffectName in this._renderEffects) {
  30051. this._renderEffects[renderEffectName]._disable(_cam);
  30052. }
  30053. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  30054. for (var i = 0; i < _cam.length; i++) {
  30055. var camera = _cam[i];
  30056. var cameraName = camera.name;
  30057. 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); });
  30058. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  30059. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  30060. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  30061. }
  30062. };
  30063. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  30064. var _this = this;
  30065. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30066. for (var i = 0; i < _cam.length; i++) {
  30067. var camera = _cam[i];
  30068. var cameraName = camera.name;
  30069. 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); });
  30070. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  30071. }
  30072. for (var renderEffectName in this._renderEffects) {
  30073. this._renderEffects[renderEffectName]._enable(_cam);
  30074. }
  30075. };
  30076. PostProcessRenderPipeline.prototype._update = function () {
  30077. for (var renderEffectName in this._renderEffects) {
  30078. this._renderEffects[renderEffectName]._update();
  30079. }
  30080. for (var i = 0; i < this._cameras.length; i++) {
  30081. var cameraName = this._cameras[i].name;
  30082. if (this._renderEffectsForIsolatedPass[cameraName]) {
  30083. this._renderEffectsForIsolatedPass[cameraName]._update();
  30084. }
  30085. }
  30086. };
  30087. PostProcessRenderPipeline.prototype.dispose = function () {
  30088. // Must be implemented by children
  30089. };
  30090. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  30091. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  30092. return PostProcessRenderPipeline;
  30093. })();
  30094. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  30095. })(BABYLON || (BABYLON = {}));
  30096. var BABYLON;
  30097. (function (BABYLON) {
  30098. var PostProcessRenderPipelineManager = (function () {
  30099. function PostProcessRenderPipelineManager() {
  30100. this._renderPipelines = {};
  30101. }
  30102. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  30103. this._renderPipelines[renderPipeline._name] = renderPipeline;
  30104. };
  30105. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  30106. var renderPipeline = this._renderPipelines[renderPipelineName];
  30107. if (!renderPipeline) {
  30108. return;
  30109. }
  30110. renderPipeline._attachCameras(cameras, unique);
  30111. };
  30112. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  30113. var renderPipeline = this._renderPipelines[renderPipelineName];
  30114. if (!renderPipeline) {
  30115. return;
  30116. }
  30117. renderPipeline._detachCameras(cameras);
  30118. };
  30119. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30120. var renderPipeline = this._renderPipelines[renderPipelineName];
  30121. if (!renderPipeline) {
  30122. return;
  30123. }
  30124. renderPipeline._enableEffect(renderEffectName, cameras);
  30125. };
  30126. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30127. var renderPipeline = this._renderPipelines[renderPipelineName];
  30128. if (!renderPipeline) {
  30129. return;
  30130. }
  30131. renderPipeline._disableEffect(renderEffectName, cameras);
  30132. };
  30133. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  30134. var renderPipeline = this._renderPipelines[renderPipelineName];
  30135. if (!renderPipeline) {
  30136. return;
  30137. }
  30138. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  30139. };
  30140. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  30141. var renderPipeline = this._renderPipelines[renderPipelineName];
  30142. if (!renderPipeline) {
  30143. return;
  30144. }
  30145. renderPipeline._disableDisplayOnlyPass(cameras);
  30146. };
  30147. PostProcessRenderPipelineManager.prototype.update = function () {
  30148. for (var renderPipelineName in this._renderPipelines) {
  30149. var pipeline = this._renderPipelines[renderPipelineName];
  30150. if (!pipeline.isSupported) {
  30151. pipeline.dispose();
  30152. delete this._renderPipelines[renderPipelineName];
  30153. }
  30154. else {
  30155. pipeline._update();
  30156. }
  30157. }
  30158. };
  30159. return PostProcessRenderPipelineManager;
  30160. })();
  30161. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  30162. })(BABYLON || (BABYLON = {}));
  30163. var BABYLON;
  30164. (function (BABYLON) {
  30165. var BoundingBoxRenderer = (function () {
  30166. function BoundingBoxRenderer(scene) {
  30167. this.frontColor = new BABYLON.Color3(1, 1, 1);
  30168. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  30169. this.showBackLines = true;
  30170. this.renderList = new BABYLON.SmartArray(32);
  30171. this._scene = scene;
  30172. }
  30173. BoundingBoxRenderer.prototype._prepareRessources = function () {
  30174. if (this._colorShader) {
  30175. return;
  30176. }
  30177. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  30178. attributes: ["position"],
  30179. uniforms: ["worldViewProjection", "color"]
  30180. });
  30181. var engine = this._scene.getEngine();
  30182. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  30183. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  30184. 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]);
  30185. };
  30186. BoundingBoxRenderer.prototype.reset = function () {
  30187. this.renderList.reset();
  30188. };
  30189. BoundingBoxRenderer.prototype.render = function () {
  30190. if (this.renderList.length === 0) {
  30191. return;
  30192. }
  30193. this._prepareRessources();
  30194. if (!this._colorShader.isReady()) {
  30195. return;
  30196. }
  30197. var engine = this._scene.getEngine();
  30198. engine.setDepthWrite(false);
  30199. this._colorShader._preBind();
  30200. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  30201. var boundingBox = this.renderList.data[boundingBoxIndex];
  30202. var min = boundingBox.minimum;
  30203. var max = boundingBox.maximum;
  30204. var diff = max.subtract(min);
  30205. var median = min.add(diff.scale(0.5));
  30206. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  30207. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  30208. .multiply(boundingBox.getWorldMatrix());
  30209. // VBOs
  30210. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  30211. if (this.showBackLines) {
  30212. // Back
  30213. engine.setDepthFunctionToGreaterOrEqual();
  30214. this._scene.resetCachedMaterial();
  30215. this._colorShader.setColor4("color", this.backColor.toColor4());
  30216. this._colorShader.bind(worldMatrix);
  30217. // Draw order
  30218. engine.draw(false, 0, 24);
  30219. }
  30220. // Front
  30221. engine.setDepthFunctionToLess();
  30222. this._scene.resetCachedMaterial();
  30223. this._colorShader.setColor4("color", this.frontColor.toColor4());
  30224. this._colorShader.bind(worldMatrix);
  30225. // Draw order
  30226. engine.draw(false, 0, 24);
  30227. }
  30228. this._colorShader.unbind();
  30229. engine.setDepthFunctionToLessOrEqual();
  30230. engine.setDepthWrite(true);
  30231. };
  30232. BoundingBoxRenderer.prototype.dispose = function () {
  30233. if (!this._colorShader) {
  30234. return;
  30235. }
  30236. this._colorShader.dispose();
  30237. this._vb.dispose();
  30238. this._scene.getEngine()._releaseBuffer(this._ib);
  30239. };
  30240. return BoundingBoxRenderer;
  30241. })();
  30242. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  30243. })(BABYLON || (BABYLON = {}));
  30244. var BABYLON;
  30245. (function (BABYLON) {
  30246. var Condition = (function () {
  30247. function Condition(actionManager) {
  30248. this._actionManager = actionManager;
  30249. }
  30250. Condition.prototype.isValid = function () {
  30251. return true;
  30252. };
  30253. Condition.prototype._getProperty = function (propertyPath) {
  30254. return this._actionManager._getProperty(propertyPath);
  30255. };
  30256. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  30257. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30258. };
  30259. Condition.prototype.serialize = function () {
  30260. };
  30261. Condition.prototype._serialize = function (serializedCondition) {
  30262. return {
  30263. type: 2,
  30264. children: [],
  30265. name: serializedCondition.name,
  30266. properties: serializedCondition.properties
  30267. };
  30268. };
  30269. return Condition;
  30270. })();
  30271. BABYLON.Condition = Condition;
  30272. var ValueCondition = (function (_super) {
  30273. __extends(ValueCondition, _super);
  30274. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  30275. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  30276. _super.call(this, actionManager);
  30277. this.propertyPath = propertyPath;
  30278. this.value = value;
  30279. this.operator = operator;
  30280. this._target = target;
  30281. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  30282. this._property = this._getProperty(this.propertyPath);
  30283. }
  30284. Object.defineProperty(ValueCondition, "IsEqual", {
  30285. get: function () {
  30286. return ValueCondition._IsEqual;
  30287. },
  30288. enumerable: true,
  30289. configurable: true
  30290. });
  30291. Object.defineProperty(ValueCondition, "IsDifferent", {
  30292. get: function () {
  30293. return ValueCondition._IsDifferent;
  30294. },
  30295. enumerable: true,
  30296. configurable: true
  30297. });
  30298. Object.defineProperty(ValueCondition, "IsGreater", {
  30299. get: function () {
  30300. return ValueCondition._IsGreater;
  30301. },
  30302. enumerable: true,
  30303. configurable: true
  30304. });
  30305. Object.defineProperty(ValueCondition, "IsLesser", {
  30306. get: function () {
  30307. return ValueCondition._IsLesser;
  30308. },
  30309. enumerable: true,
  30310. configurable: true
  30311. });
  30312. // Methods
  30313. ValueCondition.prototype.isValid = function () {
  30314. switch (this.operator) {
  30315. case ValueCondition.IsGreater:
  30316. return this._effectiveTarget[this._property] > this.value;
  30317. case ValueCondition.IsLesser:
  30318. return this._effectiveTarget[this._property] < this.value;
  30319. case ValueCondition.IsEqual:
  30320. case ValueCondition.IsDifferent:
  30321. var check;
  30322. if (this.value.equals) {
  30323. check = this.value.equals(this._effectiveTarget[this._property]);
  30324. }
  30325. else {
  30326. check = this.value === this._effectiveTarget[this._property];
  30327. }
  30328. return this.operator === ValueCondition.IsEqual ? check : !check;
  30329. }
  30330. return false;
  30331. };
  30332. ValueCondition.prototype.serialize = function () {
  30333. return this._serialize({
  30334. name: "ValueCondition",
  30335. properties: [
  30336. BABYLON.Action._GetTargetProperty(this._target),
  30337. { name: "propertyPath", value: this.propertyPath },
  30338. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  30339. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  30340. ]
  30341. });
  30342. };
  30343. ValueCondition.GetOperatorName = function (operator) {
  30344. switch (operator) {
  30345. case ValueCondition._IsEqual: return "IsEqual";
  30346. case ValueCondition._IsDifferent: return "IsDifferent";
  30347. case ValueCondition._IsGreater: return "IsGreater";
  30348. case ValueCondition._IsLesser: return "IsLesser";
  30349. default: return "";
  30350. }
  30351. };
  30352. // Statics
  30353. ValueCondition._IsEqual = 0;
  30354. ValueCondition._IsDifferent = 1;
  30355. ValueCondition._IsGreater = 2;
  30356. ValueCondition._IsLesser = 3;
  30357. return ValueCondition;
  30358. })(Condition);
  30359. BABYLON.ValueCondition = ValueCondition;
  30360. var PredicateCondition = (function (_super) {
  30361. __extends(PredicateCondition, _super);
  30362. function PredicateCondition(actionManager, predicate) {
  30363. _super.call(this, actionManager);
  30364. this.predicate = predicate;
  30365. }
  30366. PredicateCondition.prototype.isValid = function () {
  30367. return this.predicate();
  30368. };
  30369. return PredicateCondition;
  30370. })(Condition);
  30371. BABYLON.PredicateCondition = PredicateCondition;
  30372. var StateCondition = (function (_super) {
  30373. __extends(StateCondition, _super);
  30374. function StateCondition(actionManager, target, value) {
  30375. _super.call(this, actionManager);
  30376. this.value = value;
  30377. this._target = target;
  30378. }
  30379. // Methods
  30380. StateCondition.prototype.isValid = function () {
  30381. return this._target.state === this.value;
  30382. };
  30383. StateCondition.prototype.serialize = function () {
  30384. return this._serialize({
  30385. name: "StateCondition",
  30386. properties: [
  30387. BABYLON.Action._GetTargetProperty(this._target),
  30388. { name: "value", value: this.value }
  30389. ]
  30390. });
  30391. };
  30392. return StateCondition;
  30393. })(Condition);
  30394. BABYLON.StateCondition = StateCondition;
  30395. })(BABYLON || (BABYLON = {}));
  30396. var BABYLON;
  30397. (function (BABYLON) {
  30398. var Action = (function () {
  30399. function Action(triggerOptions, condition) {
  30400. this.triggerOptions = triggerOptions;
  30401. if (triggerOptions.parameter) {
  30402. this.trigger = triggerOptions.trigger;
  30403. this._triggerParameter = triggerOptions.parameter;
  30404. }
  30405. else {
  30406. this.trigger = triggerOptions;
  30407. }
  30408. this._nextActiveAction = this;
  30409. this._condition = condition;
  30410. }
  30411. // Methods
  30412. Action.prototype._prepare = function () {
  30413. };
  30414. Action.prototype.getTriggerParameter = function () {
  30415. return this._triggerParameter;
  30416. };
  30417. Action.prototype._executeCurrent = function (evt) {
  30418. if (this._nextActiveAction._condition) {
  30419. var condition = this._nextActiveAction._condition;
  30420. var currentRenderId = this._actionManager.getScene().getRenderId();
  30421. // We cache the current evaluation for the current frame
  30422. if (condition._evaluationId === currentRenderId) {
  30423. if (!condition._currentResult) {
  30424. return;
  30425. }
  30426. }
  30427. else {
  30428. condition._evaluationId = currentRenderId;
  30429. if (!condition.isValid()) {
  30430. condition._currentResult = false;
  30431. return;
  30432. }
  30433. condition._currentResult = true;
  30434. }
  30435. }
  30436. this._nextActiveAction.execute(evt);
  30437. this.skipToNextActiveAction();
  30438. };
  30439. Action.prototype.execute = function (evt) {
  30440. };
  30441. Action.prototype.skipToNextActiveAction = function () {
  30442. if (this._nextActiveAction._child) {
  30443. if (!this._nextActiveAction._child._actionManager) {
  30444. this._nextActiveAction._child._actionManager = this._actionManager;
  30445. }
  30446. this._nextActiveAction = this._nextActiveAction._child;
  30447. }
  30448. else {
  30449. this._nextActiveAction = this;
  30450. }
  30451. };
  30452. Action.prototype.then = function (action) {
  30453. this._child = action;
  30454. action._actionManager = this._actionManager;
  30455. action._prepare();
  30456. return action;
  30457. };
  30458. Action.prototype._getProperty = function (propertyPath) {
  30459. return this._actionManager._getProperty(propertyPath);
  30460. };
  30461. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30462. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30463. };
  30464. Action.prototype.serialize = function (parent) {
  30465. };
  30466. // Called by BABYLON.Action objects in serialize(...). Internal use
  30467. Action.prototype._serialize = function (serializedAction, parent) {
  30468. var serializationObject = {
  30469. type: 1,
  30470. children: [],
  30471. name: serializedAction.name,
  30472. properties: serializedAction.properties || []
  30473. };
  30474. // Serialize child
  30475. if (this._child) {
  30476. this._child.serialize(serializationObject);
  30477. }
  30478. // Check if "this" has a condition
  30479. if (this._condition) {
  30480. var serializedCondition = this._condition.serialize();
  30481. serializedCondition.children.push(serializationObject);
  30482. if (parent) {
  30483. parent.children.push(serializedCondition);
  30484. }
  30485. return serializedCondition;
  30486. }
  30487. if (parent) {
  30488. parent.children.push(serializationObject);
  30489. }
  30490. return serializationObject;
  30491. };
  30492. Action._SerializeValueAsString = function (value) {
  30493. if (typeof value === "number") {
  30494. return value.toString();
  30495. }
  30496. if (typeof value === "boolean") {
  30497. return value ? "true" : "false";
  30498. }
  30499. if (value instanceof BABYLON.Vector2) {
  30500. return value.x + ", " + value.y;
  30501. }
  30502. if (value instanceof BABYLON.Vector3) {
  30503. return value.x + ", " + value.y + ", " + value.z;
  30504. }
  30505. if (value instanceof BABYLON.Color3) {
  30506. return value.r + ", " + value.g + ", " + value.b;
  30507. }
  30508. if (value instanceof BABYLON.Color4) {
  30509. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  30510. }
  30511. return value; // string
  30512. };
  30513. Action._GetTargetProperty = function (target) {
  30514. return {
  30515. name: "target",
  30516. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  30517. : target instanceof BABYLON.Light ? "LightProperties"
  30518. : target instanceof BABYLON.Camera ? "CameraProperties"
  30519. : "SceneProperties",
  30520. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  30521. };
  30522. };
  30523. return Action;
  30524. })();
  30525. BABYLON.Action = Action;
  30526. })(BABYLON || (BABYLON = {}));
  30527. var BABYLON;
  30528. (function (BABYLON) {
  30529. /**
  30530. * ActionEvent is the event beint sent when an action is triggered.
  30531. */
  30532. var ActionEvent = (function () {
  30533. /**
  30534. * @constructor
  30535. * @param source The mesh or sprite that triggered the action.
  30536. * @param pointerX The X mouse cursor position at the time of the event
  30537. * @param pointerY The Y mouse cursor position at the time of the event
  30538. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30539. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30540. */
  30541. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30542. this.source = source;
  30543. this.pointerX = pointerX;
  30544. this.pointerY = pointerY;
  30545. this.meshUnderPointer = meshUnderPointer;
  30546. this.sourceEvent = sourceEvent;
  30547. this.additionalData = additionalData;
  30548. }
  30549. /**
  30550. * Helper function to auto-create an ActionEvent from a source mesh.
  30551. * @param source The source mesh that triggered the event
  30552. * @param evt {Event} The original (browser) event
  30553. */
  30554. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30555. var scene = source.getScene();
  30556. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30557. };
  30558. /**
  30559. * Helper function to auto-create an ActionEvent from a source mesh.
  30560. * @param source The source sprite that triggered the event
  30561. * @param scene Scene associated with the sprite
  30562. * @param evt {Event} The original (browser) event
  30563. */
  30564. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30565. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30566. };
  30567. /**
  30568. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30569. * @param scene the scene where the event occurred
  30570. * @param evt {Event} The original (browser) event
  30571. */
  30572. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30573. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30574. };
  30575. return ActionEvent;
  30576. })();
  30577. BABYLON.ActionEvent = ActionEvent;
  30578. /**
  30579. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30580. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30581. */
  30582. var ActionManager = (function () {
  30583. function ActionManager(scene) {
  30584. // Members
  30585. this.actions = new Array();
  30586. this._scene = scene;
  30587. scene._actionManagers.push(this);
  30588. }
  30589. Object.defineProperty(ActionManager, "NothingTrigger", {
  30590. get: function () {
  30591. return ActionManager._NothingTrigger;
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30597. get: function () {
  30598. return ActionManager._OnPickTrigger;
  30599. },
  30600. enumerable: true,
  30601. configurable: true
  30602. });
  30603. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30604. get: function () {
  30605. return ActionManager._OnLeftPickTrigger;
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30611. get: function () {
  30612. return ActionManager._OnRightPickTrigger;
  30613. },
  30614. enumerable: true,
  30615. configurable: true
  30616. });
  30617. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30618. get: function () {
  30619. return ActionManager._OnCenterPickTrigger;
  30620. },
  30621. enumerable: true,
  30622. configurable: true
  30623. });
  30624. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30625. get: function () {
  30626. return ActionManager._OnPickDownTrigger;
  30627. },
  30628. enumerable: true,
  30629. configurable: true
  30630. });
  30631. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30632. get: function () {
  30633. return ActionManager._OnPickUpTrigger;
  30634. },
  30635. enumerable: true,
  30636. configurable: true
  30637. });
  30638. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30639. /// This trigger will only be raised if you also declared a OnPickDown
  30640. get: function () {
  30641. return ActionManager._OnPickOutTrigger;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30647. get: function () {
  30648. return ActionManager._OnLongPressTrigger;
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30654. get: function () {
  30655. return ActionManager._OnPointerOverTrigger;
  30656. },
  30657. enumerable: true,
  30658. configurable: true
  30659. });
  30660. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30661. get: function () {
  30662. return ActionManager._OnPointerOutTrigger;
  30663. },
  30664. enumerable: true,
  30665. configurable: true
  30666. });
  30667. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30668. get: function () {
  30669. return ActionManager._OnEveryFrameTrigger;
  30670. },
  30671. enumerable: true,
  30672. configurable: true
  30673. });
  30674. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30675. get: function () {
  30676. return ActionManager._OnIntersectionEnterTrigger;
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30682. get: function () {
  30683. return ActionManager._OnIntersectionExitTrigger;
  30684. },
  30685. enumerable: true,
  30686. configurable: true
  30687. });
  30688. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30689. get: function () {
  30690. return ActionManager._OnKeyDownTrigger;
  30691. },
  30692. enumerable: true,
  30693. configurable: true
  30694. });
  30695. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30696. get: function () {
  30697. return ActionManager._OnKeyUpTrigger;
  30698. },
  30699. enumerable: true,
  30700. configurable: true
  30701. });
  30702. // Methods
  30703. ActionManager.prototype.dispose = function () {
  30704. var index = this._scene._actionManagers.indexOf(this);
  30705. if (index > -1) {
  30706. this._scene._actionManagers.splice(index, 1);
  30707. }
  30708. };
  30709. ActionManager.prototype.getScene = function () {
  30710. return this._scene;
  30711. };
  30712. /**
  30713. * Does this action manager handles actions of any of the given triggers
  30714. * @param {number[]} triggers - the triggers to be tested
  30715. * @return {boolean} whether one (or more) of the triggers is handeled
  30716. */
  30717. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30718. for (var index = 0; index < this.actions.length; index++) {
  30719. var action = this.actions[index];
  30720. if (triggers.indexOf(action.trigger) > -1) {
  30721. return true;
  30722. }
  30723. }
  30724. return false;
  30725. };
  30726. /**
  30727. * Does this action manager handles actions of a given trigger
  30728. * @param {number} trigger - the trigger to be tested
  30729. * @return {boolean} whether the trigger is handeled
  30730. */
  30731. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30732. for (var index = 0; index < this.actions.length; index++) {
  30733. var action = this.actions[index];
  30734. if (action.trigger === trigger) {
  30735. return true;
  30736. }
  30737. }
  30738. return false;
  30739. };
  30740. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30741. /**
  30742. * Does this action manager has pointer triggers
  30743. * @return {boolean} whether or not it has pointer triggers
  30744. */
  30745. get: function () {
  30746. for (var index = 0; index < this.actions.length; index++) {
  30747. var action = this.actions[index];
  30748. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30749. return true;
  30750. }
  30751. }
  30752. return false;
  30753. },
  30754. enumerable: true,
  30755. configurable: true
  30756. });
  30757. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30758. /**
  30759. * Does this action manager has pick triggers
  30760. * @return {boolean} whether or not it has pick triggers
  30761. */
  30762. get: function () {
  30763. for (var index = 0; index < this.actions.length; index++) {
  30764. var action = this.actions[index];
  30765. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30766. return true;
  30767. }
  30768. }
  30769. return false;
  30770. },
  30771. enumerable: true,
  30772. configurable: true
  30773. });
  30774. /**
  30775. * Registers an action to this action manager
  30776. * @param {BABYLON.Action} action - the action to be registered
  30777. * @return {BABYLON.Action} the action amended (prepared) after registration
  30778. */
  30779. ActionManager.prototype.registerAction = function (action) {
  30780. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30781. if (this.getScene().actionManager !== this) {
  30782. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30783. return null;
  30784. }
  30785. }
  30786. this.actions.push(action);
  30787. action._actionManager = this;
  30788. action._prepare();
  30789. return action;
  30790. };
  30791. /**
  30792. * Process a specific trigger
  30793. * @param {number} trigger - the trigger to process
  30794. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30795. */
  30796. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30797. for (var index = 0; index < this.actions.length; index++) {
  30798. var action = this.actions[index];
  30799. if (action.trigger === trigger) {
  30800. if (trigger === ActionManager.OnKeyUpTrigger
  30801. || trigger === ActionManager.OnKeyDownTrigger) {
  30802. var parameter = action.getTriggerParameter();
  30803. if (parameter) {
  30804. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30805. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30806. if (actualkey !== parameter.toLowerCase()) {
  30807. continue;
  30808. }
  30809. }
  30810. }
  30811. action._executeCurrent(evt);
  30812. }
  30813. }
  30814. };
  30815. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30816. var properties = propertyPath.split(".");
  30817. for (var index = 0; index < properties.length - 1; index++) {
  30818. target = target[properties[index]];
  30819. }
  30820. return target;
  30821. };
  30822. ActionManager.prototype._getProperty = function (propertyPath) {
  30823. var properties = propertyPath.split(".");
  30824. return properties[properties.length - 1];
  30825. };
  30826. ActionManager.prototype.serialize = function (name) {
  30827. var root = {
  30828. children: [],
  30829. name: name,
  30830. type: 3,
  30831. properties: [] // Empty for root but required
  30832. };
  30833. for (var i = 0; i < this.actions.length; i++) {
  30834. var triggerObject = {
  30835. type: 0,
  30836. children: [],
  30837. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  30838. properties: []
  30839. };
  30840. var triggerOptions = this.actions[i].triggerOptions;
  30841. if (triggerOptions && typeof triggerOptions !== "number") {
  30842. if (triggerOptions.parameter instanceof BABYLON.Node) {
  30843. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  30844. }
  30845. else {
  30846. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  30847. }
  30848. }
  30849. // Serialize child action, recursively
  30850. this.actions[i].serialize(triggerObject);
  30851. // Add serialized trigger
  30852. root.children.push(triggerObject);
  30853. }
  30854. return root;
  30855. };
  30856. ActionManager.Parse = function (parsedActions, object, scene) {
  30857. var actionManager = new BABYLON.ActionManager(scene);
  30858. if (object === null)
  30859. scene.actionManager = actionManager;
  30860. else
  30861. object.actionManager = actionManager;
  30862. // instanciate a new object
  30863. var instanciate = function (name, params) {
  30864. var newInstance = Object.create(BABYLON[name].prototype);
  30865. newInstance.constructor.apply(newInstance, params);
  30866. return newInstance;
  30867. };
  30868. var parseParameter = function (name, value, target, propertyPath) {
  30869. if (propertyPath === null) {
  30870. // String, boolean or float
  30871. var floatValue = parseFloat(value);
  30872. if (value === "true" || value === "false")
  30873. return value === "true";
  30874. else
  30875. return isNaN(floatValue) ? value : floatValue;
  30876. }
  30877. var effectiveTarget = propertyPath.split(".");
  30878. var values = value.split(",");
  30879. // Get effective Target
  30880. for (var i = 0; i < effectiveTarget.length; i++) {
  30881. target = target[effectiveTarget[i]];
  30882. }
  30883. // Return appropriate value with its type
  30884. if (typeof (target) === "boolean")
  30885. return values[0] === "true";
  30886. if (typeof (target) === "string")
  30887. return values[0];
  30888. // Parameters with multiple values such as Vector3 etc.
  30889. var split = new Array();
  30890. for (var i = 0; i < values.length; i++)
  30891. split.push(parseFloat(values[i]));
  30892. if (target instanceof BABYLON.Vector3)
  30893. return BABYLON.Vector3.FromArray(split);
  30894. if (target instanceof BABYLON.Vector4)
  30895. return BABYLON.Vector4.FromArray(split);
  30896. if (target instanceof BABYLON.Color3)
  30897. return BABYLON.Color3.FromArray(split);
  30898. if (target instanceof BABYLON.Color4)
  30899. return BABYLON.Color4.FromArray(split);
  30900. return parseFloat(values[0]);
  30901. };
  30902. // traverse graph per trigger
  30903. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30904. if (combineArray === void 0) { combineArray = null; }
  30905. if (parsedAction.detached)
  30906. return;
  30907. var parameters = new Array();
  30908. var target = null;
  30909. var propertyPath = null;
  30910. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30911. // Parameters
  30912. if (parsedAction.type === 2)
  30913. parameters.push(actionManager);
  30914. else
  30915. parameters.push(trigger);
  30916. if (combine) {
  30917. var actions = new Array();
  30918. for (var j = 0; j < parsedAction.combine.length; j++) {
  30919. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30920. }
  30921. parameters.push(actions);
  30922. }
  30923. else {
  30924. for (var i = 0; i < parsedAction.properties.length; i++) {
  30925. var value = parsedAction.properties[i].value;
  30926. var name = parsedAction.properties[i].name;
  30927. var targetType = parsedAction.properties[i].targetType;
  30928. if (name === "target")
  30929. if (targetType !== null && targetType === "SceneProperties")
  30930. value = target = scene;
  30931. else
  30932. value = target = scene.getNodeByName(value);
  30933. else if (name === "parent")
  30934. value = scene.getNodeByName(value);
  30935. else if (name === "sound")
  30936. value = scene.getSoundByName(value);
  30937. else if (name !== "propertyPath") {
  30938. if (parsedAction.type === 2 && name === "operator")
  30939. value = BABYLON.ValueCondition[value];
  30940. else
  30941. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30942. }
  30943. else {
  30944. propertyPath = value;
  30945. }
  30946. parameters.push(value);
  30947. }
  30948. }
  30949. if (combineArray === null) {
  30950. parameters.push(condition);
  30951. }
  30952. else {
  30953. parameters.push(null);
  30954. }
  30955. // If interpolate value action
  30956. if (parsedAction.name === "InterpolateValueAction") {
  30957. var param = parameters[parameters.length - 2];
  30958. parameters[parameters.length - 1] = param;
  30959. parameters[parameters.length - 2] = condition;
  30960. }
  30961. // Action or condition(s) and not CombineAction
  30962. var newAction = instanciate(parsedAction.name, parameters);
  30963. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30964. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30965. if (action)
  30966. action.then(nothing);
  30967. else
  30968. actionManager.registerAction(nothing);
  30969. action = nothing;
  30970. }
  30971. if (combineArray === null) {
  30972. if (newAction instanceof BABYLON.Condition) {
  30973. condition = newAction;
  30974. newAction = action;
  30975. }
  30976. else {
  30977. condition = null;
  30978. if (action)
  30979. action.then(newAction);
  30980. else
  30981. actionManager.registerAction(newAction);
  30982. }
  30983. }
  30984. else {
  30985. combineArray.push(newAction);
  30986. }
  30987. for (var i = 0; i < parsedAction.children.length; i++)
  30988. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30989. };
  30990. // triggers
  30991. for (var i = 0; i < parsedActions.children.length; i++) {
  30992. var triggerParams;
  30993. var trigger = parsedActions.children[i];
  30994. if (trigger.properties.length > 0) {
  30995. var param = trigger.properties[0].value;
  30996. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30997. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30998. }
  30999. else
  31000. triggerParams = BABYLON.ActionManager[trigger.name];
  31001. for (var j = 0; j < trigger.children.length; j++) {
  31002. if (!trigger.detached)
  31003. traverse(trigger.children[j], triggerParams, null, null);
  31004. }
  31005. }
  31006. };
  31007. ActionManager.GetTriggerName = function (trigger) {
  31008. switch (trigger) {
  31009. case 0: return "NothingTrigger";
  31010. case 1: return "OnPickTrigger";
  31011. case 2: return "OnLeftPickTrigger";
  31012. case 3: return "OnRightPickTrigger";
  31013. case 4: return "OnCenterPickTrigger";
  31014. case 5: return "OnPickDownTrigger";
  31015. case 6: return "OnPickUpTrigger";
  31016. case 7: return "OnLongPressTrigger";
  31017. case 8: return "OnPointerOverTrigger";
  31018. case 9: return "OnPointerOutTrigger";
  31019. case 10: return "OnEveryFrameTrigger";
  31020. case 11: return "OnIntersectionEnterTrigger";
  31021. case 12: return "OnIntersectionExitTrigger";
  31022. case 13: return "OnKeyDownTrigger";
  31023. case 14: return "OnKeyUpTrigger";
  31024. case 15: return "OnPickOutTrigger";
  31025. default: return "";
  31026. }
  31027. };
  31028. // Statics
  31029. ActionManager._NothingTrigger = 0;
  31030. ActionManager._OnPickTrigger = 1;
  31031. ActionManager._OnLeftPickTrigger = 2;
  31032. ActionManager._OnRightPickTrigger = 3;
  31033. ActionManager._OnCenterPickTrigger = 4;
  31034. ActionManager._OnPickDownTrigger = 5;
  31035. ActionManager._OnPickUpTrigger = 6;
  31036. ActionManager._OnLongPressTrigger = 7;
  31037. ActionManager._OnPointerOverTrigger = 8;
  31038. ActionManager._OnPointerOutTrigger = 9;
  31039. ActionManager._OnEveryFrameTrigger = 10;
  31040. ActionManager._OnIntersectionEnterTrigger = 11;
  31041. ActionManager._OnIntersectionExitTrigger = 12;
  31042. ActionManager._OnKeyDownTrigger = 13;
  31043. ActionManager._OnKeyUpTrigger = 14;
  31044. ActionManager._OnPickOutTrigger = 15;
  31045. ActionManager.DragMovementThreshold = 10; // in pixels
  31046. ActionManager.LongPressDelay = 500; // in milliseconds
  31047. return ActionManager;
  31048. })();
  31049. BABYLON.ActionManager = ActionManager;
  31050. })(BABYLON || (BABYLON = {}));
  31051. var BABYLON;
  31052. (function (BABYLON) {
  31053. var InterpolateValueAction = (function (_super) {
  31054. __extends(InterpolateValueAction, _super);
  31055. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  31056. if (duration === void 0) { duration = 1000; }
  31057. _super.call(this, triggerOptions, condition);
  31058. this.propertyPath = propertyPath;
  31059. this.value = value;
  31060. this.duration = duration;
  31061. this.stopOtherAnimations = stopOtherAnimations;
  31062. this.onInterpolationDone = onInterpolationDone;
  31063. this._target = this._effectiveTarget = target;
  31064. }
  31065. InterpolateValueAction.prototype._prepare = function () {
  31066. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31067. this._property = this._getProperty(this.propertyPath);
  31068. };
  31069. InterpolateValueAction.prototype.execute = function () {
  31070. var scene = this._actionManager.getScene();
  31071. var keys = [
  31072. {
  31073. frame: 0,
  31074. value: this._effectiveTarget[this._property]
  31075. }, {
  31076. frame: 100,
  31077. value: this.value
  31078. }
  31079. ];
  31080. var dataType;
  31081. if (typeof this.value === "number") {
  31082. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  31083. }
  31084. else if (this.value instanceof BABYLON.Color3) {
  31085. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  31086. }
  31087. else if (this.value instanceof BABYLON.Vector3) {
  31088. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  31089. }
  31090. else if (this.value instanceof BABYLON.Matrix) {
  31091. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  31092. }
  31093. else if (this.value instanceof BABYLON.Quaternion) {
  31094. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  31095. }
  31096. else {
  31097. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  31098. return;
  31099. }
  31100. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  31101. animation.setKeys(keys);
  31102. if (this.stopOtherAnimations) {
  31103. scene.stopAnimation(this._effectiveTarget);
  31104. }
  31105. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  31106. };
  31107. InterpolateValueAction.prototype.serialize = function (parent) {
  31108. return _super.prototype._serialize.call(this, {
  31109. name: "InterpolateValueAction",
  31110. properties: [
  31111. BABYLON.Action._GetTargetProperty(this._target),
  31112. { name: "propertyPath", value: this.propertyPath },
  31113. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31114. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  31115. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  31116. ]
  31117. }, parent);
  31118. };
  31119. return InterpolateValueAction;
  31120. })(BABYLON.Action);
  31121. BABYLON.InterpolateValueAction = InterpolateValueAction;
  31122. })(BABYLON || (BABYLON = {}));
  31123. var BABYLON;
  31124. (function (BABYLON) {
  31125. var SwitchBooleanAction = (function (_super) {
  31126. __extends(SwitchBooleanAction, _super);
  31127. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  31128. _super.call(this, triggerOptions, condition);
  31129. this.propertyPath = propertyPath;
  31130. this._target = this._effectiveTarget = target;
  31131. }
  31132. SwitchBooleanAction.prototype._prepare = function () {
  31133. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31134. this._property = this._getProperty(this.propertyPath);
  31135. };
  31136. SwitchBooleanAction.prototype.execute = function () {
  31137. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  31138. };
  31139. SwitchBooleanAction.prototype.serialize = function (parent) {
  31140. return _super.prototype._serialize.call(this, {
  31141. name: "SwitchBooleanAction",
  31142. properties: [
  31143. BABYLON.Action._GetTargetProperty(this._target),
  31144. { name: "propertyPath", value: this.propertyPath }
  31145. ]
  31146. }, parent);
  31147. };
  31148. return SwitchBooleanAction;
  31149. })(BABYLON.Action);
  31150. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  31151. var SetStateAction = (function (_super) {
  31152. __extends(SetStateAction, _super);
  31153. function SetStateAction(triggerOptions, target, value, condition) {
  31154. _super.call(this, triggerOptions, condition);
  31155. this.value = value;
  31156. this._target = target;
  31157. }
  31158. SetStateAction.prototype.execute = function () {
  31159. this._target.state = this.value;
  31160. };
  31161. SetStateAction.prototype.serialize = function (parent) {
  31162. return _super.prototype._serialize.call(this, {
  31163. name: "SetStateAction",
  31164. properties: [
  31165. BABYLON.Action._GetTargetProperty(this._target),
  31166. { name: "value", value: this.value }
  31167. ]
  31168. }, parent);
  31169. };
  31170. return SetStateAction;
  31171. })(BABYLON.Action);
  31172. BABYLON.SetStateAction = SetStateAction;
  31173. var SetValueAction = (function (_super) {
  31174. __extends(SetValueAction, _super);
  31175. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  31176. _super.call(this, triggerOptions, condition);
  31177. this.propertyPath = propertyPath;
  31178. this.value = value;
  31179. this._target = this._effectiveTarget = target;
  31180. }
  31181. SetValueAction.prototype._prepare = function () {
  31182. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31183. this._property = this._getProperty(this.propertyPath);
  31184. };
  31185. SetValueAction.prototype.execute = function () {
  31186. this._effectiveTarget[this._property] = this.value;
  31187. };
  31188. SetValueAction.prototype.serialize = function (parent) {
  31189. return _super.prototype._serialize.call(this, {
  31190. name: "SetValueAction",
  31191. properties: [
  31192. BABYLON.Action._GetTargetProperty(this._target),
  31193. { name: "propertyPath", value: this.propertyPath },
  31194. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31195. ]
  31196. }, parent);
  31197. };
  31198. return SetValueAction;
  31199. })(BABYLON.Action);
  31200. BABYLON.SetValueAction = SetValueAction;
  31201. var IncrementValueAction = (function (_super) {
  31202. __extends(IncrementValueAction, _super);
  31203. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  31204. _super.call(this, triggerOptions, condition);
  31205. this.propertyPath = propertyPath;
  31206. this.value = value;
  31207. this._target = this._effectiveTarget = target;
  31208. }
  31209. IncrementValueAction.prototype._prepare = function () {
  31210. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31211. this._property = this._getProperty(this.propertyPath);
  31212. if (typeof this._effectiveTarget[this._property] !== "number") {
  31213. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  31214. }
  31215. };
  31216. IncrementValueAction.prototype.execute = function () {
  31217. this._effectiveTarget[this._property] += this.value;
  31218. };
  31219. IncrementValueAction.prototype.serialize = function (parent) {
  31220. return _super.prototype._serialize.call(this, {
  31221. name: "IncrementValueAction",
  31222. properties: [
  31223. BABYLON.Action._GetTargetProperty(this._target),
  31224. { name: "propertyPath", value: this.propertyPath },
  31225. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31226. ]
  31227. }, parent);
  31228. };
  31229. return IncrementValueAction;
  31230. })(BABYLON.Action);
  31231. BABYLON.IncrementValueAction = IncrementValueAction;
  31232. var PlayAnimationAction = (function (_super) {
  31233. __extends(PlayAnimationAction, _super);
  31234. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  31235. _super.call(this, triggerOptions, condition);
  31236. this.from = from;
  31237. this.to = to;
  31238. this.loop = loop;
  31239. this._target = target;
  31240. }
  31241. PlayAnimationAction.prototype._prepare = function () {
  31242. };
  31243. PlayAnimationAction.prototype.execute = function () {
  31244. var scene = this._actionManager.getScene();
  31245. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  31246. };
  31247. PlayAnimationAction.prototype.serialize = function (parent) {
  31248. return _super.prototype._serialize.call(this, {
  31249. name: "PlayAnimationAction",
  31250. properties: [
  31251. BABYLON.Action._GetTargetProperty(this._target),
  31252. { name: "from", value: String(this.from) },
  31253. { name: "to", value: String(this.to) },
  31254. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  31255. ]
  31256. }, parent);
  31257. };
  31258. return PlayAnimationAction;
  31259. })(BABYLON.Action);
  31260. BABYLON.PlayAnimationAction = PlayAnimationAction;
  31261. var StopAnimationAction = (function (_super) {
  31262. __extends(StopAnimationAction, _super);
  31263. function StopAnimationAction(triggerOptions, target, condition) {
  31264. _super.call(this, triggerOptions, condition);
  31265. this._target = target;
  31266. }
  31267. StopAnimationAction.prototype._prepare = function () {
  31268. };
  31269. StopAnimationAction.prototype.execute = function () {
  31270. var scene = this._actionManager.getScene();
  31271. scene.stopAnimation(this._target);
  31272. };
  31273. StopAnimationAction.prototype.serialize = function (parent) {
  31274. return _super.prototype._serialize.call(this, {
  31275. name: "StopAnimationAction",
  31276. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  31277. }, parent);
  31278. };
  31279. return StopAnimationAction;
  31280. })(BABYLON.Action);
  31281. BABYLON.StopAnimationAction = StopAnimationAction;
  31282. var DoNothingAction = (function (_super) {
  31283. __extends(DoNothingAction, _super);
  31284. function DoNothingAction(triggerOptions, condition) {
  31285. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  31286. _super.call(this, triggerOptions, condition);
  31287. }
  31288. DoNothingAction.prototype.execute = function () {
  31289. };
  31290. DoNothingAction.prototype.serialize = function (parent) {
  31291. return _super.prototype._serialize.call(this, {
  31292. name: "DoNothingAction",
  31293. properties: []
  31294. }, parent);
  31295. };
  31296. return DoNothingAction;
  31297. })(BABYLON.Action);
  31298. BABYLON.DoNothingAction = DoNothingAction;
  31299. var CombineAction = (function (_super) {
  31300. __extends(CombineAction, _super);
  31301. function CombineAction(triggerOptions, children, condition) {
  31302. _super.call(this, triggerOptions, condition);
  31303. this.children = children;
  31304. }
  31305. CombineAction.prototype._prepare = function () {
  31306. for (var index = 0; index < this.children.length; index++) {
  31307. this.children[index]._actionManager = this._actionManager;
  31308. this.children[index]._prepare();
  31309. }
  31310. };
  31311. CombineAction.prototype.execute = function (evt) {
  31312. for (var index = 0; index < this.children.length; index++) {
  31313. this.children[index].execute(evt);
  31314. }
  31315. };
  31316. CombineAction.prototype.serialize = function (parent) {
  31317. var serializationObject = _super.prototype._serialize.call(this, {
  31318. name: "CombineAction",
  31319. properties: [],
  31320. combine: []
  31321. }, parent);
  31322. for (var i = 0; i < this.children.length; i++) {
  31323. serializationObject.combine.push(this.children[i].serialize(null));
  31324. }
  31325. return serializationObject;
  31326. };
  31327. return CombineAction;
  31328. })(BABYLON.Action);
  31329. BABYLON.CombineAction = CombineAction;
  31330. var ExecuteCodeAction = (function (_super) {
  31331. __extends(ExecuteCodeAction, _super);
  31332. function ExecuteCodeAction(triggerOptions, func, condition) {
  31333. _super.call(this, triggerOptions, condition);
  31334. this.func = func;
  31335. }
  31336. ExecuteCodeAction.prototype.execute = function (evt) {
  31337. this.func(evt);
  31338. };
  31339. return ExecuteCodeAction;
  31340. })(BABYLON.Action);
  31341. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  31342. var SetParentAction = (function (_super) {
  31343. __extends(SetParentAction, _super);
  31344. function SetParentAction(triggerOptions, target, parent, condition) {
  31345. _super.call(this, triggerOptions, condition);
  31346. this._target = target;
  31347. this._parent = parent;
  31348. }
  31349. SetParentAction.prototype._prepare = function () {
  31350. };
  31351. SetParentAction.prototype.execute = function () {
  31352. if (this._target.parent === this._parent) {
  31353. return;
  31354. }
  31355. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  31356. invertParentWorldMatrix.invert();
  31357. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  31358. this._target.parent = this._parent;
  31359. };
  31360. SetParentAction.prototype.serialize = function (parent) {
  31361. return _super.prototype._serialize.call(this, {
  31362. name: "SetParentAction",
  31363. properties: [
  31364. BABYLON.Action._GetTargetProperty(this._target),
  31365. BABYLON.Action._GetTargetProperty(this._parent),
  31366. ]
  31367. }, parent);
  31368. };
  31369. return SetParentAction;
  31370. })(BABYLON.Action);
  31371. BABYLON.SetParentAction = SetParentAction;
  31372. var PlaySoundAction = (function (_super) {
  31373. __extends(PlaySoundAction, _super);
  31374. function PlaySoundAction(triggerOptions, sound, condition) {
  31375. _super.call(this, triggerOptions, condition);
  31376. this._sound = sound;
  31377. }
  31378. PlaySoundAction.prototype._prepare = function () {
  31379. };
  31380. PlaySoundAction.prototype.execute = function () {
  31381. if (this._sound !== undefined)
  31382. this._sound.play();
  31383. };
  31384. PlaySoundAction.prototype.serialize = function (parent) {
  31385. return _super.prototype._serialize.call(this, {
  31386. name: "PlaySoundAction",
  31387. properties: [{ name: "sound", value: this._sound.name }]
  31388. }, parent);
  31389. };
  31390. return PlaySoundAction;
  31391. })(BABYLON.Action);
  31392. BABYLON.PlaySoundAction = PlaySoundAction;
  31393. var StopSoundAction = (function (_super) {
  31394. __extends(StopSoundAction, _super);
  31395. function StopSoundAction(triggerOptions, sound, condition) {
  31396. _super.call(this, triggerOptions, condition);
  31397. this._sound = sound;
  31398. }
  31399. StopSoundAction.prototype._prepare = function () {
  31400. };
  31401. StopSoundAction.prototype.execute = function () {
  31402. if (this._sound !== undefined)
  31403. this._sound.stop();
  31404. };
  31405. StopSoundAction.prototype.serialize = function (parent) {
  31406. return _super.prototype._serialize.call(this, {
  31407. name: "StopSoundAction",
  31408. properties: [{ name: "sound", value: this._sound.name }]
  31409. }, parent);
  31410. };
  31411. return StopSoundAction;
  31412. })(BABYLON.Action);
  31413. BABYLON.StopSoundAction = StopSoundAction;
  31414. })(BABYLON || (BABYLON = {}));
  31415. var BABYLON;
  31416. (function (BABYLON) {
  31417. var Geometry = (function () {
  31418. function Geometry(id, scene, vertexData, updatable, mesh) {
  31419. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31420. this._totalVertices = 0;
  31421. this._isDisposed = false;
  31422. this.id = id;
  31423. this._engine = scene.getEngine();
  31424. this._meshes = [];
  31425. this._scene = scene;
  31426. //Init vertex buffer cache
  31427. this._vertexBuffers = {};
  31428. this._indices = [];
  31429. // vertexData
  31430. if (vertexData) {
  31431. this.setAllVerticesData(vertexData, updatable);
  31432. }
  31433. else {
  31434. this._totalVertices = 0;
  31435. this._indices = [];
  31436. }
  31437. // applyToMesh
  31438. if (mesh) {
  31439. if (mesh instanceof BABYLON.LinesMesh) {
  31440. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31441. this.updateExtend();
  31442. }
  31443. this.applyToMesh(mesh);
  31444. mesh.computeWorldMatrix(true);
  31445. }
  31446. }
  31447. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31448. /**
  31449. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  31450. * @returns The Bias Vector
  31451. */
  31452. get: function () {
  31453. return this._boundingBias;
  31454. },
  31455. set: function (value) {
  31456. if (this._boundingBias && this._boundingBias.equals(value)) {
  31457. return;
  31458. }
  31459. this._boundingBias = value.clone();
  31460. this.updateBoundingInfo(true, null);
  31461. },
  31462. enumerable: true,
  31463. configurable: true
  31464. });
  31465. Object.defineProperty(Geometry.prototype, "extend", {
  31466. get: function () {
  31467. return this._extend;
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. Geometry.prototype.getScene = function () {
  31473. return this._scene;
  31474. };
  31475. Geometry.prototype.getEngine = function () {
  31476. return this._engine;
  31477. };
  31478. Geometry.prototype.isReady = function () {
  31479. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31480. };
  31481. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31482. vertexData.applyToGeometry(this, updatable);
  31483. this.notifyUpdate();
  31484. };
  31485. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31486. if (this._vertexBuffers[kind]) {
  31487. this._vertexBuffers[kind].dispose();
  31488. }
  31489. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31490. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31491. stride = this._vertexBuffers[kind].getStrideSize();
  31492. this._totalVertices = data.length / stride;
  31493. this.updateExtend(data);
  31494. var meshes = this._meshes;
  31495. var numOfMeshes = meshes.length;
  31496. for (var index = 0; index < numOfMeshes; index++) {
  31497. var mesh = meshes[index];
  31498. mesh._resetPointsArrayCache();
  31499. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31500. mesh._createGlobalSubMesh();
  31501. mesh.computeWorldMatrix(true);
  31502. }
  31503. }
  31504. this.notifyUpdate(kind);
  31505. };
  31506. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31507. var vertexBuffer = this.getVertexBuffer(kind);
  31508. if (!vertexBuffer) {
  31509. return;
  31510. }
  31511. vertexBuffer.updateDirectly(data, offset);
  31512. this.notifyUpdate(kind);
  31513. };
  31514. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31515. var vertexBuffer = this.getVertexBuffer(kind);
  31516. if (!vertexBuffer) {
  31517. return;
  31518. }
  31519. vertexBuffer.update(data);
  31520. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31521. var stride = vertexBuffer.getStrideSize();
  31522. this._totalVertices = data.length / stride;
  31523. this.updateBoundingInfo(updateExtends, data);
  31524. }
  31525. this.notifyUpdate(kind);
  31526. };
  31527. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31528. if (updateExtends) {
  31529. this.updateExtend(data);
  31530. }
  31531. var meshes = this._meshes;
  31532. var numOfMeshes = meshes.length;
  31533. for (var index = 0; index < numOfMeshes; index++) {
  31534. var mesh = meshes[index];
  31535. mesh._resetPointsArrayCache();
  31536. if (updateExtends) {
  31537. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31538. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31539. var subMesh = mesh.subMeshes[subIndex];
  31540. subMesh.refreshBoundingInfo();
  31541. }
  31542. }
  31543. }
  31544. };
  31545. Geometry.prototype.getTotalVertices = function () {
  31546. if (!this.isReady()) {
  31547. return 0;
  31548. }
  31549. return this._totalVertices;
  31550. };
  31551. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  31552. var vertexBuffer = this.getVertexBuffer(kind);
  31553. if (!vertexBuffer) {
  31554. return null;
  31555. }
  31556. var orig = vertexBuffer.getData();
  31557. if (!copyWhenShared || this._meshes.length === 1) {
  31558. return orig;
  31559. }
  31560. else {
  31561. var len = orig.length;
  31562. var copy = [];
  31563. for (var i = 0; i < len; i++) {
  31564. copy.push(orig[i]);
  31565. }
  31566. return copy;
  31567. }
  31568. };
  31569. Geometry.prototype.getVertexBuffer = function (kind) {
  31570. if (!this.isReady()) {
  31571. return null;
  31572. }
  31573. return this._vertexBuffers[kind];
  31574. };
  31575. Geometry.prototype.getVertexBuffers = function () {
  31576. if (!this.isReady()) {
  31577. return null;
  31578. }
  31579. return this._vertexBuffers;
  31580. };
  31581. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31582. if (!this._vertexBuffers) {
  31583. if (this._delayInfo) {
  31584. return this._delayInfo.indexOf(kind) !== -1;
  31585. }
  31586. return false;
  31587. }
  31588. return this._vertexBuffers[kind] !== undefined;
  31589. };
  31590. Geometry.prototype.getVerticesDataKinds = function () {
  31591. var result = [];
  31592. var kind;
  31593. if (!this._vertexBuffers && this._delayInfo) {
  31594. for (kind in this._delayInfo) {
  31595. result.push(kind);
  31596. }
  31597. }
  31598. else {
  31599. for (kind in this._vertexBuffers) {
  31600. result.push(kind);
  31601. }
  31602. }
  31603. return result;
  31604. };
  31605. Geometry.prototype.setIndices = function (indices, totalVertices) {
  31606. if (this._indexBuffer) {
  31607. this._engine._releaseBuffer(this._indexBuffer);
  31608. }
  31609. this._indices = indices;
  31610. if (this._meshes.length !== 0 && this._indices) {
  31611. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31612. }
  31613. if (totalVertices !== undefined) {
  31614. this._totalVertices = totalVertices;
  31615. }
  31616. var meshes = this._meshes;
  31617. var numOfMeshes = meshes.length;
  31618. for (var index = 0; index < numOfMeshes; index++) {
  31619. meshes[index]._createGlobalSubMesh();
  31620. }
  31621. this.notifyUpdate();
  31622. };
  31623. Geometry.prototype.getTotalIndices = function () {
  31624. if (!this.isReady()) {
  31625. return 0;
  31626. }
  31627. return this._indices.length;
  31628. };
  31629. Geometry.prototype.getIndices = function (copyWhenShared) {
  31630. if (!this.isReady()) {
  31631. return null;
  31632. }
  31633. var orig = this._indices;
  31634. if (!copyWhenShared || this._meshes.length === 1) {
  31635. return orig;
  31636. }
  31637. else {
  31638. var len = orig.length;
  31639. var copy = [];
  31640. for (var i = 0; i < len; i++) {
  31641. copy.push(orig[i]);
  31642. }
  31643. return copy;
  31644. }
  31645. };
  31646. Geometry.prototype.getIndexBuffer = function () {
  31647. if (!this.isReady()) {
  31648. return null;
  31649. }
  31650. return this._indexBuffer;
  31651. };
  31652. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31653. var meshes = this._meshes;
  31654. var index = meshes.indexOf(mesh);
  31655. if (index === -1) {
  31656. return;
  31657. }
  31658. for (var kind in this._vertexBuffers) {
  31659. this._vertexBuffers[kind].dispose();
  31660. }
  31661. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  31662. this._indexBuffer = null;
  31663. }
  31664. meshes.splice(index, 1);
  31665. mesh._geometry = null;
  31666. if (meshes.length === 0 && shouldDispose) {
  31667. this.dispose();
  31668. }
  31669. };
  31670. Geometry.prototype.applyToMesh = function (mesh) {
  31671. if (mesh._geometry === this) {
  31672. return;
  31673. }
  31674. var previousGeometry = mesh._geometry;
  31675. if (previousGeometry) {
  31676. previousGeometry.releaseForMesh(mesh);
  31677. }
  31678. var meshes = this._meshes;
  31679. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31680. mesh._geometry = this;
  31681. this._scene.pushGeometry(this);
  31682. meshes.push(mesh);
  31683. if (this.isReady()) {
  31684. this._applyToMesh(mesh);
  31685. }
  31686. else {
  31687. mesh._boundingInfo = this._boundingInfo;
  31688. }
  31689. };
  31690. Geometry.prototype.updateExtend = function (data) {
  31691. if (data === void 0) { data = null; }
  31692. if (!data) {
  31693. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31694. }
  31695. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31696. };
  31697. Geometry.prototype._applyToMesh = function (mesh) {
  31698. var numOfMeshes = this._meshes.length;
  31699. // vertexBuffers
  31700. for (var kind in this._vertexBuffers) {
  31701. if (numOfMeshes === 1) {
  31702. this._vertexBuffers[kind].create();
  31703. }
  31704. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31705. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31706. mesh._resetPointsArrayCache();
  31707. if (!this._extend) {
  31708. this.updateExtend(this._vertexBuffers[kind].getData());
  31709. }
  31710. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31711. mesh._createGlobalSubMesh();
  31712. //bounding info was just created again, world matrix should be applied again.
  31713. mesh._updateBoundingInfo();
  31714. }
  31715. }
  31716. // indexBuffer
  31717. if (numOfMeshes === 1 && this._indices) {
  31718. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31719. }
  31720. if (this._indexBuffer) {
  31721. this._indexBuffer.references = numOfMeshes;
  31722. }
  31723. };
  31724. Geometry.prototype.notifyUpdate = function (kind) {
  31725. if (this.onGeometryUpdated) {
  31726. this.onGeometryUpdated(this, kind);
  31727. }
  31728. };
  31729. Geometry.prototype.load = function (scene, onLoaded) {
  31730. var _this = this;
  31731. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31732. return;
  31733. }
  31734. if (this.isReady()) {
  31735. if (onLoaded) {
  31736. onLoaded();
  31737. }
  31738. return;
  31739. }
  31740. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31741. scene._addPendingData(this);
  31742. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31743. _this._delayLoadingFunction(JSON.parse(data), _this);
  31744. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31745. _this._delayInfo = [];
  31746. scene._removePendingData(_this);
  31747. var meshes = _this._meshes;
  31748. var numOfMeshes = meshes.length;
  31749. for (var index = 0; index < numOfMeshes; index++) {
  31750. _this._applyToMesh(meshes[index]);
  31751. }
  31752. if (onLoaded) {
  31753. onLoaded();
  31754. }
  31755. }, function () { }, scene.database);
  31756. };
  31757. Geometry.prototype.isDisposed = function () {
  31758. return this._isDisposed;
  31759. };
  31760. Geometry.prototype.dispose = function () {
  31761. var meshes = this._meshes;
  31762. var numOfMeshes = meshes.length;
  31763. var index;
  31764. for (index = 0; index < numOfMeshes; index++) {
  31765. this.releaseForMesh(meshes[index]);
  31766. }
  31767. this._meshes = [];
  31768. for (var kind in this._vertexBuffers) {
  31769. this._vertexBuffers[kind].dispose();
  31770. }
  31771. this._vertexBuffers = [];
  31772. this._totalVertices = 0;
  31773. if (this._indexBuffer) {
  31774. this._engine._releaseBuffer(this._indexBuffer);
  31775. }
  31776. this._indexBuffer = null;
  31777. this._indices = [];
  31778. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31779. this.delayLoadingFile = null;
  31780. this._delayLoadingFunction = null;
  31781. this._delayInfo = [];
  31782. this._boundingInfo = null;
  31783. this._scene.removeGeometry(this);
  31784. this._isDisposed = true;
  31785. };
  31786. Geometry.prototype.copy = function (id) {
  31787. var vertexData = new BABYLON.VertexData();
  31788. vertexData.indices = [];
  31789. var indices = this.getIndices();
  31790. for (var index = 0; index < indices.length; index++) {
  31791. vertexData.indices.push(indices[index]);
  31792. }
  31793. var updatable = false;
  31794. var stopChecking = false;
  31795. var kind;
  31796. for (kind in this._vertexBuffers) {
  31797. // using slice() to make a copy of the array and not just reference it
  31798. var data = this.getVerticesData(kind);
  31799. if (data instanceof Float32Array) {
  31800. vertexData.set(new Float32Array(data), kind);
  31801. }
  31802. else {
  31803. vertexData.set(data.slice(0), kind);
  31804. }
  31805. if (!stopChecking) {
  31806. updatable = this.getVertexBuffer(kind).isUpdatable();
  31807. stopChecking = !updatable;
  31808. }
  31809. }
  31810. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31811. geometry.delayLoadState = this.delayLoadState;
  31812. geometry.delayLoadingFile = this.delayLoadingFile;
  31813. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31814. for (kind in this._delayInfo) {
  31815. geometry._delayInfo = geometry._delayInfo || [];
  31816. geometry._delayInfo.push(kind);
  31817. }
  31818. // Bounding info
  31819. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31820. return geometry;
  31821. };
  31822. Geometry.prototype.serialize = function () {
  31823. var serializationObject = {};
  31824. serializationObject.id = this.id;
  31825. if (BABYLON.Tags.HasTags(this)) {
  31826. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31827. }
  31828. return serializationObject;
  31829. };
  31830. Geometry.prototype.serializeVerticeData = function () {
  31831. var serializationObject = this.serialize();
  31832. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31833. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31834. }
  31835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31836. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31837. }
  31838. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31839. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31840. }
  31841. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31842. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31843. }
  31844. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31845. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31846. }
  31847. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31848. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31849. }
  31850. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31851. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31852. }
  31853. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31854. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31855. }
  31856. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31857. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31858. }
  31859. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31860. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31861. serializationObject.matricesIndices._isExpanded = true;
  31862. }
  31863. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31864. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31865. }
  31866. serializationObject.indices = this.getIndices();
  31867. return serializationObject;
  31868. };
  31869. // Statics
  31870. Geometry.ExtractFromMesh = function (mesh, id) {
  31871. var geometry = mesh._geometry;
  31872. if (!geometry) {
  31873. return null;
  31874. }
  31875. return geometry.copy(id);
  31876. };
  31877. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31878. // be aware Math.random() could cause collisions
  31879. Geometry.RandomId = function () {
  31880. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31881. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31882. return v.toString(16);
  31883. });
  31884. };
  31885. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31886. var scene = mesh.getScene();
  31887. // Geometry
  31888. var geometryId = parsedGeometry.geometryId;
  31889. if (geometryId) {
  31890. var geometry = scene.getGeometryByID(geometryId);
  31891. if (geometry) {
  31892. geometry.applyToMesh(mesh);
  31893. }
  31894. }
  31895. else if (parsedGeometry instanceof ArrayBuffer) {
  31896. var binaryInfo = mesh._binaryInfo;
  31897. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31898. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31899. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31900. }
  31901. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31902. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31903. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31904. }
  31905. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31906. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31907. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31908. }
  31909. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31910. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31911. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31912. }
  31913. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31914. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31915. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31916. }
  31917. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31918. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31919. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31920. }
  31921. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31922. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31923. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31924. }
  31925. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31926. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31927. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31928. }
  31929. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31930. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31931. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31932. }
  31933. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31934. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31935. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31936. }
  31937. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31938. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31939. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31940. }
  31941. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31942. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31943. mesh.setIndices(indicesData);
  31944. }
  31945. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31946. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31947. mesh.subMeshes = [];
  31948. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31949. var materialIndex = subMeshesData[(i * 5) + 0];
  31950. var verticesStart = subMeshesData[(i * 5) + 1];
  31951. var verticesCount = subMeshesData[(i * 5) + 2];
  31952. var indexStart = subMeshesData[(i * 5) + 3];
  31953. var indexCount = subMeshesData[(i * 5) + 4];
  31954. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31955. }
  31956. }
  31957. }
  31958. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31959. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31960. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31961. if (parsedGeometry.uvs) {
  31962. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31963. }
  31964. if (parsedGeometry.uvs2) {
  31965. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31966. }
  31967. if (parsedGeometry.uvs3) {
  31968. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31969. }
  31970. if (parsedGeometry.uvs4) {
  31971. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31972. }
  31973. if (parsedGeometry.uvs5) {
  31974. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31975. }
  31976. if (parsedGeometry.uvs6) {
  31977. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31978. }
  31979. if (parsedGeometry.colors) {
  31980. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31981. }
  31982. if (parsedGeometry.matricesIndices) {
  31983. if (!parsedGeometry.matricesIndices._isExpanded) {
  31984. var floatIndices = [];
  31985. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31986. var matricesIndex = parsedGeometry.matricesIndices[i];
  31987. floatIndices.push(matricesIndex & 0x000000FF);
  31988. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31989. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31990. floatIndices.push(matricesIndex >> 24);
  31991. }
  31992. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31993. }
  31994. else {
  31995. delete parsedGeometry.matricesIndices._isExpanded;
  31996. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31997. }
  31998. }
  31999. if (parsedGeometry.matricesIndicesExtra) {
  32000. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32001. var floatIndices = [];
  32002. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32003. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32004. floatIndices.push(matricesIndex & 0x000000FF);
  32005. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32006. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32007. floatIndices.push(matricesIndex >> 24);
  32008. }
  32009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  32010. }
  32011. else {
  32012. delete parsedGeometry.matricesIndices._isExpanded;
  32013. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  32014. }
  32015. }
  32016. if (parsedGeometry.matricesWeights) {
  32017. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  32018. }
  32019. if (parsedGeometry.matricesWeightsExtra) {
  32020. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  32021. }
  32022. mesh.setIndices(parsedGeometry.indices);
  32023. }
  32024. // SubMeshes
  32025. if (parsedGeometry.subMeshes) {
  32026. mesh.subMeshes = [];
  32027. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32028. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32029. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32030. }
  32031. }
  32032. // Flat shading
  32033. if (mesh._shouldGenerateFlatShading) {
  32034. mesh.convertToFlatShadedMesh();
  32035. delete mesh._shouldGenerateFlatShading;
  32036. }
  32037. // Update
  32038. mesh.computeWorldMatrix(true);
  32039. // Octree
  32040. if (scene['_selectionOctree']) {
  32041. scene['_selectionOctree'].addMesh(mesh);
  32042. }
  32043. };
  32044. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32045. if (scene.getGeometryByID(parsedVertexData.id)) {
  32046. return null; // null since geometry could be something else than a box...
  32047. }
  32048. var geometry = new Geometry(parsedVertexData.id, scene);
  32049. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32050. if (parsedVertexData.delayLoadingFile) {
  32051. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32052. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32053. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32054. geometry._delayInfo = [];
  32055. if (parsedVertexData.hasUVs) {
  32056. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32057. }
  32058. if (parsedVertexData.hasUVs2) {
  32059. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32060. }
  32061. if (parsedVertexData.hasUVs3) {
  32062. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32063. }
  32064. if (parsedVertexData.hasUVs4) {
  32065. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32066. }
  32067. if (parsedVertexData.hasUVs5) {
  32068. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32069. }
  32070. if (parsedVertexData.hasUVs6) {
  32071. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32072. }
  32073. if (parsedVertexData.hasColors) {
  32074. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32075. }
  32076. if (parsedVertexData.hasMatricesIndices) {
  32077. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32078. }
  32079. if (parsedVertexData.hasMatricesWeights) {
  32080. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32081. }
  32082. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32083. }
  32084. else {
  32085. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32086. }
  32087. scene.pushGeometry(geometry, true);
  32088. return geometry;
  32089. };
  32090. return Geometry;
  32091. })();
  32092. BABYLON.Geometry = Geometry;
  32093. /////// Primitives //////////////////////////////////////////////
  32094. var Geometry;
  32095. (function (Geometry) {
  32096. var Primitives;
  32097. (function (Primitives) {
  32098. /// Abstract class
  32099. var _Primitive = (function (_super) {
  32100. __extends(_Primitive, _super);
  32101. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32102. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  32103. this._canBeRegenerated = _canBeRegenerated;
  32104. this._beingRegenerated = true;
  32105. this.regenerate();
  32106. this._beingRegenerated = false;
  32107. }
  32108. _Primitive.prototype.canBeRegenerated = function () {
  32109. return this._canBeRegenerated;
  32110. };
  32111. _Primitive.prototype.regenerate = function () {
  32112. if (!this._canBeRegenerated) {
  32113. return;
  32114. }
  32115. this._beingRegenerated = true;
  32116. this.setAllVerticesData(this._regenerateVertexData(), false);
  32117. this._beingRegenerated = false;
  32118. };
  32119. _Primitive.prototype.asNewGeometry = function (id) {
  32120. return _super.prototype.copy.call(this, id);
  32121. };
  32122. // overrides
  32123. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32124. if (!this._beingRegenerated) {
  32125. return;
  32126. }
  32127. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32128. };
  32129. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32130. if (!this._beingRegenerated) {
  32131. return;
  32132. }
  32133. _super.prototype.setVerticesData.call(this, kind, data, false);
  32134. };
  32135. // to override
  32136. // protected
  32137. _Primitive.prototype._regenerateVertexData = function () {
  32138. throw new Error("Abstract method");
  32139. };
  32140. _Primitive.prototype.copy = function (id) {
  32141. throw new Error("Must be overriden in sub-classes.");
  32142. };
  32143. _Primitive.prototype.serialize = function () {
  32144. var serializationObject = _super.prototype.serialize.call(this);
  32145. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32146. return serializationObject;
  32147. };
  32148. return _Primitive;
  32149. })(Geometry);
  32150. Primitives._Primitive = _Primitive;
  32151. var Ribbon = (function (_super) {
  32152. __extends(Ribbon, _super);
  32153. // Members
  32154. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32155. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32156. _super.call(this, id, scene, canBeRegenerated, mesh);
  32157. this.pathArray = pathArray;
  32158. this.closeArray = closeArray;
  32159. this.closePath = closePath;
  32160. this.offset = offset;
  32161. this.side = side;
  32162. }
  32163. Ribbon.prototype._regenerateVertexData = function () {
  32164. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32165. };
  32166. Ribbon.prototype.copy = function (id) {
  32167. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  32168. };
  32169. return Ribbon;
  32170. })(_Primitive);
  32171. Primitives.Ribbon = Ribbon;
  32172. var Box = (function (_super) {
  32173. __extends(Box, _super);
  32174. // Members
  32175. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32176. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32177. _super.call(this, id, scene, canBeRegenerated, mesh);
  32178. this.size = size;
  32179. this.side = side;
  32180. }
  32181. Box.prototype._regenerateVertexData = function () {
  32182. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32183. };
  32184. Box.prototype.copy = function (id) {
  32185. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32186. };
  32187. Box.prototype.serialize = function () {
  32188. var serializationObject = _super.prototype.serialize.call(this);
  32189. serializationObject.size = this.size;
  32190. return serializationObject;
  32191. };
  32192. Box.Parse = function (parsedBox, scene) {
  32193. if (scene.getGeometryByID(parsedBox.id)) {
  32194. return null; // null since geometry could be something else than a box...
  32195. }
  32196. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32197. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32198. scene.pushGeometry(box, true);
  32199. return box;
  32200. };
  32201. return Box;
  32202. })(_Primitive);
  32203. Primitives.Box = Box;
  32204. var Sphere = (function (_super) {
  32205. __extends(Sphere, _super);
  32206. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32207. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32208. _super.call(this, id, scene, canBeRegenerated, mesh);
  32209. this.segments = segments;
  32210. this.diameter = diameter;
  32211. this.side = side;
  32212. }
  32213. Sphere.prototype._regenerateVertexData = function () {
  32214. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32215. };
  32216. Sphere.prototype.copy = function (id) {
  32217. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32218. };
  32219. Sphere.prototype.serialize = function () {
  32220. var serializationObject = _super.prototype.serialize.call(this);
  32221. serializationObject.segments = this.segments;
  32222. serializationObject.diameter = this.diameter;
  32223. return serializationObject;
  32224. };
  32225. Sphere.Parse = function (parsedSphere, scene) {
  32226. if (scene.getGeometryByID(parsedSphere.id)) {
  32227. return null; // null since geometry could be something else than a sphere...
  32228. }
  32229. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32230. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32231. scene.pushGeometry(sphere, true);
  32232. return sphere;
  32233. };
  32234. return Sphere;
  32235. })(_Primitive);
  32236. Primitives.Sphere = Sphere;
  32237. var Disc = (function (_super) {
  32238. __extends(Disc, _super);
  32239. // Members
  32240. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32241. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32242. _super.call(this, id, scene, canBeRegenerated, mesh);
  32243. this.radius = radius;
  32244. this.tessellation = tessellation;
  32245. this.side = side;
  32246. }
  32247. Disc.prototype._regenerateVertexData = function () {
  32248. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32249. };
  32250. Disc.prototype.copy = function (id) {
  32251. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32252. };
  32253. return Disc;
  32254. })(_Primitive);
  32255. Primitives.Disc = Disc;
  32256. var Cylinder = (function (_super) {
  32257. __extends(Cylinder, _super);
  32258. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32259. if (subdivisions === void 0) { subdivisions = 1; }
  32260. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32261. _super.call(this, id, scene, canBeRegenerated, mesh);
  32262. this.height = height;
  32263. this.diameterTop = diameterTop;
  32264. this.diameterBottom = diameterBottom;
  32265. this.tessellation = tessellation;
  32266. this.subdivisions = subdivisions;
  32267. this.side = side;
  32268. }
  32269. Cylinder.prototype._regenerateVertexData = function () {
  32270. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32271. };
  32272. Cylinder.prototype.copy = function (id) {
  32273. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32274. };
  32275. Cylinder.prototype.serialize = function () {
  32276. var serializationObject = _super.prototype.serialize.call(this);
  32277. serializationObject.height = this.height;
  32278. serializationObject.diameterTop = this.diameterTop;
  32279. serializationObject.diameterBottom = this.diameterBottom;
  32280. serializationObject.tessellation = this.tessellation;
  32281. return serializationObject;
  32282. };
  32283. Cylinder.Parse = function (parsedCylinder, scene) {
  32284. if (scene.getGeometryByID(parsedCylinder.id)) {
  32285. return null; // null since geometry could be something else than a cylinder...
  32286. }
  32287. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32288. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32289. scene.pushGeometry(cylinder, true);
  32290. return cylinder;
  32291. };
  32292. return Cylinder;
  32293. })(_Primitive);
  32294. Primitives.Cylinder = Cylinder;
  32295. var Torus = (function (_super) {
  32296. __extends(Torus, _super);
  32297. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32298. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32299. _super.call(this, id, scene, canBeRegenerated, mesh);
  32300. this.diameter = diameter;
  32301. this.thickness = thickness;
  32302. this.tessellation = tessellation;
  32303. this.side = side;
  32304. }
  32305. Torus.prototype._regenerateVertexData = function () {
  32306. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32307. };
  32308. Torus.prototype.copy = function (id) {
  32309. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32310. };
  32311. Torus.prototype.serialize = function () {
  32312. var serializationObject = _super.prototype.serialize.call(this);
  32313. serializationObject.diameter = this.diameter;
  32314. serializationObject.thickness = this.thickness;
  32315. serializationObject.tessellation = this.tessellation;
  32316. return serializationObject;
  32317. };
  32318. Torus.Parse = function (parsedTorus, scene) {
  32319. if (scene.getGeometryByID(parsedTorus.id)) {
  32320. return null; // null since geometry could be something else than a torus...
  32321. }
  32322. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32323. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32324. scene.pushGeometry(torus, true);
  32325. return torus;
  32326. };
  32327. return Torus;
  32328. })(_Primitive);
  32329. Primitives.Torus = Torus;
  32330. var Ground = (function (_super) {
  32331. __extends(Ground, _super);
  32332. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32333. _super.call(this, id, scene, canBeRegenerated, mesh);
  32334. this.width = width;
  32335. this.height = height;
  32336. this.subdivisions = subdivisions;
  32337. }
  32338. Ground.prototype._regenerateVertexData = function () {
  32339. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32340. };
  32341. Ground.prototype.copy = function (id) {
  32342. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32343. };
  32344. Ground.prototype.serialize = function () {
  32345. var serializationObject = _super.prototype.serialize.call(this);
  32346. serializationObject.width = this.width;
  32347. serializationObject.height = this.height;
  32348. serializationObject.subdivisions = this.subdivisions;
  32349. return serializationObject;
  32350. };
  32351. Ground.Parse = function (parsedGround, scene) {
  32352. if (scene.getGeometryByID(parsedGround.id)) {
  32353. return null; // null since geometry could be something else than a ground...
  32354. }
  32355. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32356. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32357. scene.pushGeometry(ground, true);
  32358. return ground;
  32359. };
  32360. return Ground;
  32361. })(_Primitive);
  32362. Primitives.Ground = Ground;
  32363. var TiledGround = (function (_super) {
  32364. __extends(TiledGround, _super);
  32365. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32366. _super.call(this, id, scene, canBeRegenerated, mesh);
  32367. this.xmin = xmin;
  32368. this.zmin = zmin;
  32369. this.xmax = xmax;
  32370. this.zmax = zmax;
  32371. this.subdivisions = subdivisions;
  32372. this.precision = precision;
  32373. }
  32374. TiledGround.prototype._regenerateVertexData = function () {
  32375. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32376. };
  32377. TiledGround.prototype.copy = function (id) {
  32378. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32379. };
  32380. return TiledGround;
  32381. })(_Primitive);
  32382. Primitives.TiledGround = TiledGround;
  32383. var Plane = (function (_super) {
  32384. __extends(Plane, _super);
  32385. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32386. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32387. _super.call(this, id, scene, canBeRegenerated, mesh);
  32388. this.size = size;
  32389. this.side = side;
  32390. }
  32391. Plane.prototype._regenerateVertexData = function () {
  32392. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32393. };
  32394. Plane.prototype.copy = function (id) {
  32395. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32396. };
  32397. Plane.prototype.serialize = function () {
  32398. var serializationObject = _super.prototype.serialize.call(this);
  32399. serializationObject.size = this.size;
  32400. return serializationObject;
  32401. };
  32402. Plane.Parse = function (parsedPlane, scene) {
  32403. if (scene.getGeometryByID(parsedPlane.id)) {
  32404. return null; // null since geometry could be something else than a ground...
  32405. }
  32406. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32407. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32408. scene.pushGeometry(plane, true);
  32409. return plane;
  32410. };
  32411. return Plane;
  32412. })(_Primitive);
  32413. Primitives.Plane = Plane;
  32414. var TorusKnot = (function (_super) {
  32415. __extends(TorusKnot, _super);
  32416. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32417. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32418. _super.call(this, id, scene, canBeRegenerated, mesh);
  32419. this.radius = radius;
  32420. this.tube = tube;
  32421. this.radialSegments = radialSegments;
  32422. this.tubularSegments = tubularSegments;
  32423. this.p = p;
  32424. this.q = q;
  32425. this.side = side;
  32426. }
  32427. TorusKnot.prototype._regenerateVertexData = function () {
  32428. 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 });
  32429. };
  32430. TorusKnot.prototype.copy = function (id) {
  32431. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32432. };
  32433. TorusKnot.prototype.serialize = function () {
  32434. var serializationObject = _super.prototype.serialize.call(this);
  32435. serializationObject.radius = this.radius;
  32436. serializationObject.tube = this.tube;
  32437. serializationObject.radialSegments = this.radialSegments;
  32438. serializationObject.tubularSegments = this.tubularSegments;
  32439. serializationObject.p = this.p;
  32440. serializationObject.q = this.q;
  32441. return serializationObject;
  32442. };
  32443. ;
  32444. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32445. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32446. return null; // null since geometry could be something else than a ground...
  32447. }
  32448. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32449. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32450. scene.pushGeometry(torusKnot, true);
  32451. return torusKnot;
  32452. };
  32453. return TorusKnot;
  32454. })(_Primitive);
  32455. Primitives.TorusKnot = TorusKnot;
  32456. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32457. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32458. })(BABYLON || (BABYLON = {}));
  32459. var BABYLON;
  32460. (function (BABYLON) {
  32461. var GroundMesh = (function (_super) {
  32462. __extends(GroundMesh, _super);
  32463. function GroundMesh(name, scene) {
  32464. _super.call(this, name, scene);
  32465. this.generateOctree = false;
  32466. this._worldInverse = new BABYLON.Matrix();
  32467. }
  32468. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  32469. get: function () {
  32470. return this._subdivisions;
  32471. },
  32472. enumerable: true,
  32473. configurable: true
  32474. });
  32475. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  32476. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  32477. this._subdivisions = chunksCount;
  32478. this.subdivide(this._subdivisions);
  32479. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  32480. };
  32481. /**
  32482. * Returns a height (y) value in the Worl system :
  32483. * the ground altitude at the coordinates (x, z) expressed in the World system.
  32484. * Returns the ground y position if (x, z) are outside the ground surface.
  32485. * Not pertinent if the ground is rotated.
  32486. */
  32487. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  32488. // express x and y in the ground local system
  32489. x -= this.position.x;
  32490. z -= this.position.z;
  32491. x /= this.scaling.x;
  32492. z /= this.scaling.z;
  32493. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32494. return this.position.y;
  32495. }
  32496. if (!this._heightQuads || this._heightQuads.length == 0) {
  32497. this._initHeightQuads();
  32498. this._computeHeightQuads();
  32499. }
  32500. var facet = this._getFacetAt(x, z);
  32501. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  32502. // return y in the World system
  32503. return y * this.scaling.y + this.position.y;
  32504. };
  32505. /**
  32506. * Returns a normalized vector (Vector3) orthogonal to the ground
  32507. * at the ground coordinates (x, z) expressed in the World system.
  32508. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  32509. * Not pertinent if the ground is rotated.
  32510. */
  32511. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  32512. var normal = new BABYLON.Vector3(0, 1, 0);
  32513. this.getNormalAtCoordinatesToRef(x, z, normal);
  32514. return normal;
  32515. };
  32516. /**
  32517. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  32518. * at the ground coordinates (x, z) expressed in the World system.
  32519. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  32520. * Not pertinent if the ground is rotated.
  32521. */
  32522. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  32523. // express x and y in the ground local system
  32524. x -= this.position.x;
  32525. z -= this.position.z;
  32526. x /= this.scaling.x;
  32527. z /= this.scaling.z;
  32528. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32529. return;
  32530. }
  32531. if (!this._heightQuads || this._heightQuads.length == 0) {
  32532. this._initHeightQuads();
  32533. this._computeHeightQuads();
  32534. }
  32535. var facet = this._getFacetAt(x, z);
  32536. ref.x = facet.x;
  32537. ref.y = facet.y;
  32538. ref.z = facet.z;
  32539. };
  32540. /**
  32541. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  32542. * if the ground has been updated.
  32543. * This can be used in the render loop
  32544. */
  32545. GroundMesh.prototype.updateCoordinateHeights = function () {
  32546. if (!this._heightQuads || this._heightQuads.length == 0) {
  32547. this._initHeightQuads();
  32548. }
  32549. this._computeHeightQuads();
  32550. };
  32551. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  32552. GroundMesh.prototype._getFacetAt = function (x, z) {
  32553. // retrieve col and row from x, z coordinates in the ground local system
  32554. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  32555. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  32556. var quad = this._heightQuads[row * this._subdivisions + col];
  32557. var facet;
  32558. if (z < quad.slope.x * x + quad.slope.y) {
  32559. facet = quad.facet1;
  32560. }
  32561. else {
  32562. facet = quad.facet2;
  32563. }
  32564. return facet;
  32565. };
  32566. // Creates and populates the heightMap array with "facet" elements :
  32567. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  32568. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32569. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32570. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32571. GroundMesh.prototype._initHeightQuads = function () {
  32572. this._heightQuads = new Array();
  32573. for (var row = 0; row < this._subdivisions; row++) {
  32574. for (var col = 0; col < this._subdivisions; col++) {
  32575. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  32576. this._heightQuads[row * this._subdivisions + col] = quad;
  32577. }
  32578. }
  32579. };
  32580. // Compute each quad element values and update the the heightMap array :
  32581. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32582. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32583. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32584. GroundMesh.prototype._computeHeightQuads = function () {
  32585. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32586. var v1 = BABYLON.Tmp.Vector3[0];
  32587. var v2 = BABYLON.Tmp.Vector3[1];
  32588. var v3 = BABYLON.Tmp.Vector3[2];
  32589. var v4 = BABYLON.Tmp.Vector3[3];
  32590. var v1v2 = BABYLON.Tmp.Vector3[4];
  32591. var v1v3 = BABYLON.Tmp.Vector3[5];
  32592. var v1v4 = BABYLON.Tmp.Vector3[6];
  32593. var norm1 = BABYLON.Tmp.Vector3[7];
  32594. var norm2 = BABYLON.Tmp.Vector3[8];
  32595. var i = 0;
  32596. var j = 0;
  32597. var k = 0;
  32598. var cd = 0; // 2D slope coefficient : z = cd * x + h
  32599. var h = 0;
  32600. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  32601. var d2 = 0;
  32602. for (var row = 0; row < this._subdivisions; row++) {
  32603. for (var col = 0; col < this._subdivisions; col++) {
  32604. i = col * 3;
  32605. j = row * (this._subdivisions + 1) * 3;
  32606. k = (row + 1) * (this._subdivisions + 1) * 3;
  32607. v1.x = positions[j + i];
  32608. v1.y = positions[j + i + 1];
  32609. v1.z = positions[j + i + 2];
  32610. v2.x = positions[j + i + 3];
  32611. v2.y = positions[j + i + 4];
  32612. v2.z = positions[j + i + 5];
  32613. v3.x = positions[k + i];
  32614. v3.y = positions[k + i + 1];
  32615. v3.z = positions[k + i + 2];
  32616. v4.x = positions[k + i + 3];
  32617. v4.y = positions[k + i + 4];
  32618. v4.z = positions[k + i + 5];
  32619. // 2D slope V1V4
  32620. cd = (v4.z - v1.z) / (v4.x - v1.x);
  32621. h = v1.z - cd * v1.x; // v1 belongs to the slope
  32622. // facet equations :
  32623. // we compute each facet normal vector
  32624. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  32625. // we compute the value d by applying the equation to v1 which belongs to the plane
  32626. // then we store the facet equation in a Vector4
  32627. v2.subtractToRef(v1, v1v2);
  32628. v3.subtractToRef(v1, v1v3);
  32629. v4.subtractToRef(v1, v1v4);
  32630. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  32631. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  32632. norm1.normalize();
  32633. norm2.normalize();
  32634. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  32635. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  32636. var quad = this._heightQuads[row * this._subdivisions + col];
  32637. quad.slope.copyFromFloats(cd, h);
  32638. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  32639. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  32640. }
  32641. }
  32642. };
  32643. return GroundMesh;
  32644. })(BABYLON.Mesh);
  32645. BABYLON.GroundMesh = GroundMesh;
  32646. })(BABYLON || (BABYLON = {}));
  32647. var BABYLON;
  32648. (function (BABYLON) {
  32649. var LinesMesh = (function (_super) {
  32650. __extends(LinesMesh, _super);
  32651. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  32652. if (parent === void 0) { parent = null; }
  32653. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  32654. this.color = new BABYLON.Color3(1, 1, 1);
  32655. this.alpha = 1;
  32656. if (source) {
  32657. this.color = source.color.clone();
  32658. this.alpha = source.alpha;
  32659. }
  32660. this._intersectionThreshold = 0.1;
  32661. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  32662. attributes: ["position"],
  32663. uniforms: ["worldViewProjection", "color"],
  32664. needAlphaBlending: true
  32665. });
  32666. }
  32667. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  32668. /**
  32669. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32670. * This margin is expressed in world space coordinates, so its value may vary.
  32671. * Default value is 0.1
  32672. * @returns the intersection Threshold value.
  32673. */
  32674. get: function () {
  32675. return this._intersectionThreshold;
  32676. },
  32677. /**
  32678. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32679. * This margin is expressed in world space coordinates, so its value may vary.
  32680. * @param value the new threshold to apply
  32681. */
  32682. set: function (value) {
  32683. if (this._intersectionThreshold === value) {
  32684. return;
  32685. }
  32686. this._intersectionThreshold = value;
  32687. if (this.geometry) {
  32688. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32689. }
  32690. },
  32691. enumerable: true,
  32692. configurable: true
  32693. });
  32694. Object.defineProperty(LinesMesh.prototype, "material", {
  32695. get: function () {
  32696. return this._colorShader;
  32697. },
  32698. enumerable: true,
  32699. configurable: true
  32700. });
  32701. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32702. get: function () {
  32703. return false;
  32704. },
  32705. enumerable: true,
  32706. configurable: true
  32707. });
  32708. LinesMesh.prototype.createInstance = function (name) {
  32709. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  32710. return null;
  32711. };
  32712. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32713. var engine = this.getScene().getEngine();
  32714. var indexToBind = this._geometry.getIndexBuffer();
  32715. // VBOs
  32716. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32717. // Color
  32718. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32719. };
  32720. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32721. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32722. return;
  32723. }
  32724. var engine = this.getScene().getEngine();
  32725. // Draw order
  32726. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32727. };
  32728. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32729. this._colorShader.dispose();
  32730. _super.prototype.dispose.call(this, doNotRecurse);
  32731. };
  32732. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32733. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32734. };
  32735. return LinesMesh;
  32736. })(BABYLON.Mesh);
  32737. BABYLON.LinesMesh = LinesMesh;
  32738. })(BABYLON || (BABYLON = {}));
  32739. var BABYLON;
  32740. (function (BABYLON) {
  32741. var DebugLayer = (function () {
  32742. function DebugLayer(scene) {
  32743. var _this = this;
  32744. this._transformationMatrix = BABYLON.Matrix.Identity();
  32745. this._enabled = false;
  32746. this._labelsEnabled = false;
  32747. this._displayStatistics = true;
  32748. this._displayTree = false;
  32749. this._displayLogs = false;
  32750. this._skeletonViewers = new Array();
  32751. this._identityMatrix = BABYLON.Matrix.Identity();
  32752. this.axisRatio = 0.02;
  32753. this.accentColor = "orange";
  32754. this._scene = scene;
  32755. this._syncPositions = function () {
  32756. var engine = _this._scene.getEngine();
  32757. var canvasRect = engine.getRenderingCanvasClientRect();
  32758. if (_this._showUI) {
  32759. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32760. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32761. _this._statsDiv.style.width = "400px";
  32762. _this._statsDiv.style.height = "auto";
  32763. _this._statsSubsetDiv.style.maxHeight = "240px";
  32764. _this._optionsDiv.style.left = "0px";
  32765. _this._optionsDiv.style.top = "10px";
  32766. _this._optionsDiv.style.width = "200px";
  32767. _this._optionsDiv.style.height = "auto";
  32768. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32769. _this._logDiv.style.left = "0px";
  32770. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32771. _this._logDiv.style.width = "600px";
  32772. _this._logDiv.style.height = "160px";
  32773. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32774. _this._treeDiv.style.top = "10px";
  32775. _this._treeDiv.style.width = "300px";
  32776. _this._treeDiv.style.height = "auto";
  32777. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32778. }
  32779. _this._globalDiv.style.left = canvasRect.left + "px";
  32780. _this._globalDiv.style.top = canvasRect.top + "px";
  32781. _this._drawingCanvas.style.left = "0px";
  32782. _this._drawingCanvas.style.top = "0px";
  32783. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32784. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32785. var devicePixelRatio = window.devicePixelRatio || 1;
  32786. var context = _this._drawingContext;
  32787. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32788. context.mozBackingStorePixelRatio ||
  32789. context.msBackingStorePixelRatio ||
  32790. context.oBackingStorePixelRatio ||
  32791. context.backingStorePixelRatio || 1;
  32792. _this._ratio = devicePixelRatio / backingStoreRatio;
  32793. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32794. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32795. };
  32796. this._onCanvasClick = function (evt) {
  32797. _this._clickPosition = {
  32798. x: evt.clientX * _this._ratio,
  32799. y: evt.clientY * _this._ratio
  32800. };
  32801. };
  32802. this._syncUI = function () {
  32803. if (_this._showUI) {
  32804. if (_this._displayStatistics) {
  32805. _this._displayStats();
  32806. _this._statsDiv.style.display = "";
  32807. }
  32808. else {
  32809. _this._statsDiv.style.display = "none";
  32810. }
  32811. if (_this._displayLogs) {
  32812. _this._logDiv.style.display = "";
  32813. }
  32814. else {
  32815. _this._logDiv.style.display = "none";
  32816. }
  32817. if (_this._displayTree) {
  32818. _this._treeDiv.style.display = "";
  32819. if (_this._needToRefreshMeshesTree) {
  32820. _this._needToRefreshMeshesTree = false;
  32821. _this._refreshMeshesTreeContent();
  32822. }
  32823. }
  32824. else {
  32825. _this._treeDiv.style.display = "none";
  32826. }
  32827. }
  32828. };
  32829. this._syncData = function () {
  32830. if (_this._labelsEnabled || !_this._showUI) {
  32831. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32832. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32833. var engine = _this._scene.getEngine();
  32834. var viewport = _this._camera.viewport;
  32835. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32836. // Meshes
  32837. var meshes = _this._camera.getActiveMeshes();
  32838. var index;
  32839. var projectedPosition;
  32840. for (index = 0; index < meshes.length; index++) {
  32841. var mesh = meshes.data[index];
  32842. var position = mesh.getBoundingInfo().boundingSphere.center;
  32843. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32844. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32845. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32846. }
  32847. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32848. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32849. }
  32850. }
  32851. // Cameras
  32852. var cameras = _this._scene.cameras;
  32853. for (index = 0; index < cameras.length; index++) {
  32854. var camera = cameras[index];
  32855. if (camera === _this._camera) {
  32856. continue;
  32857. }
  32858. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32859. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32860. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32861. _this._camera.detachControl(engine.getRenderingCanvas());
  32862. _this._camera = camera;
  32863. _this._camera.attachControl(engine.getRenderingCanvas());
  32864. }, function () { return "purple"; });
  32865. }
  32866. }
  32867. // Lights
  32868. var lights = _this._scene.lights;
  32869. for (index = 0; index < lights.length; index++) {
  32870. var light = lights[index];
  32871. if (light.position) {
  32872. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32873. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32874. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32875. light.setEnabled(!light.isEnabled());
  32876. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32877. }
  32878. }
  32879. }
  32880. }
  32881. _this._clickPosition = undefined;
  32882. };
  32883. }
  32884. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32885. while (this._treeSubsetDiv.hasChildNodes()) {
  32886. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32887. }
  32888. // Add meshes
  32889. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32890. sortedArray.sort(function (a, b) {
  32891. if (a.name === b.name) {
  32892. return 0;
  32893. }
  32894. return (a.name > b.name) ? 1 : -1;
  32895. });
  32896. for (var index = 0; index < sortedArray.length; index++) {
  32897. var mesh = sortedArray[index];
  32898. if (!mesh.isEnabled()) {
  32899. continue;
  32900. }
  32901. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32902. m.isVisible = element.checked;
  32903. }, mesh);
  32904. }
  32905. };
  32906. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32907. this._drawingContext.beginPath();
  32908. this._drawingContext.moveTo(zero.x, zero.y);
  32909. this._drawingContext.lineTo(unit.x, unit.y);
  32910. this._drawingContext.strokeStyle = color;
  32911. this._drawingContext.lineWidth = 4;
  32912. this._drawingContext.stroke();
  32913. this._drawingContext.font = "normal 14px Segoe UI";
  32914. this._drawingContext.fillStyle = color;
  32915. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32916. };
  32917. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32918. var position = mesh.getBoundingInfo().boundingSphere.center;
  32919. var worldMatrix = mesh.getWorldMatrix();
  32920. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32921. var unit = (unprojectedVector.subtract(position)).length();
  32922. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32923. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32924. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32925. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32926. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32927. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32928. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32929. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32930. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32931. };
  32932. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32933. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32934. this._drawingContext.font = "normal 12px Segoe UI";
  32935. var textMetrics = this._drawingContext.measureText(text);
  32936. var centerX = projectedPosition.x - textMetrics.width / 2;
  32937. var centerY = projectedPosition.y;
  32938. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32939. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32940. onClick();
  32941. }
  32942. this._drawingContext.beginPath();
  32943. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32944. this._drawingContext.fillStyle = getFillStyle();
  32945. this._drawingContext.globalAlpha = 0.5;
  32946. this._drawingContext.fill();
  32947. this._drawingContext.globalAlpha = 1.0;
  32948. this._drawingContext.strokeStyle = '#FFFFFF';
  32949. this._drawingContext.lineWidth = 1;
  32950. this._drawingContext.stroke();
  32951. this._drawingContext.fillStyle = "#FFFFFF";
  32952. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32953. this._drawingContext.beginPath();
  32954. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32955. this._drawingContext.fill();
  32956. }
  32957. };
  32958. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32959. if (!this._clickPosition) {
  32960. return false;
  32961. }
  32962. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32963. return false;
  32964. }
  32965. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32966. return false;
  32967. }
  32968. return true;
  32969. };
  32970. DebugLayer.prototype.isVisible = function () {
  32971. return this._enabled;
  32972. };
  32973. DebugLayer.prototype.hide = function () {
  32974. if (!this._enabled) {
  32975. return;
  32976. }
  32977. this._enabled = false;
  32978. var engine = this._scene.getEngine();
  32979. this._scene.unregisterBeforeRender(this._syncData);
  32980. this._scene.unregisterAfterRender(this._syncUI);
  32981. this._rootElement.removeChild(this._globalDiv);
  32982. this._scene.forceShowBoundingBoxes = false;
  32983. this._scene.forceWireframe = false;
  32984. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32985. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32986. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32987. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32988. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32989. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32990. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32991. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32992. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32993. this._scene.shadowsEnabled = true;
  32994. this._scene.particlesEnabled = true;
  32995. this._scene.postProcessesEnabled = true;
  32996. this._scene.collisionsEnabled = true;
  32997. this._scene.lightsEnabled = true;
  32998. this._scene.texturesEnabled = true;
  32999. this._scene.lensFlaresEnabled = true;
  33000. this._scene.proceduralTexturesEnabled = true;
  33001. this._scene.renderTargetsEnabled = true;
  33002. this._scene.probesEnabled = true;
  33003. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  33004. this._clearSkeletonViewers();
  33005. };
  33006. DebugLayer.prototype._clearSkeletonViewers = function () {
  33007. for (var index = 0; index < this._skeletonViewers.length; index++) {
  33008. this._skeletonViewers[index].dispose();
  33009. }
  33010. this._skeletonViewers = [];
  33011. };
  33012. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  33013. if (showUI === void 0) { showUI = true; }
  33014. if (camera === void 0) { camera = null; }
  33015. if (rootElement === void 0) { rootElement = null; }
  33016. if (this._enabled) {
  33017. return;
  33018. }
  33019. this._enabled = true;
  33020. if (camera) {
  33021. this._camera = camera;
  33022. }
  33023. else {
  33024. this._camera = this._scene.activeCamera;
  33025. }
  33026. this._showUI = showUI;
  33027. var engine = this._scene.getEngine();
  33028. this._globalDiv = document.createElement("div");
  33029. this._rootElement = rootElement || document.body;
  33030. this._rootElement.appendChild(this._globalDiv);
  33031. this._generateDOMelements();
  33032. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  33033. this._syncPositions();
  33034. this._scene.registerBeforeRender(this._syncData);
  33035. this._scene.registerAfterRender(this._syncUI);
  33036. };
  33037. DebugLayer.prototype._clearLabels = function () {
  33038. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  33039. for (var index = 0; index < this._scene.meshes.length; index++) {
  33040. var mesh = this._scene.meshes[index];
  33041. mesh.renderOverlay = false;
  33042. }
  33043. };
  33044. DebugLayer.prototype._generateheader = function (root, text) {
  33045. var header = document.createElement("div");
  33046. header.innerHTML = text + "&nbsp;";
  33047. header.style.textAlign = "right";
  33048. header.style.width = "100%";
  33049. header.style.color = "white";
  33050. header.style.backgroundColor = "Black";
  33051. header.style.padding = "5px 5px 4px 0px";
  33052. header.style.marginLeft = "-5px";
  33053. header.style.fontWeight = "bold";
  33054. root.appendChild(header);
  33055. };
  33056. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  33057. var label = document.createElement("label");
  33058. label.style.display = "inline";
  33059. label.innerHTML = title;
  33060. label.style.color = color;
  33061. root.appendChild(label);
  33062. root.appendChild(document.createElement("br"));
  33063. };
  33064. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  33065. if (tag === void 0) { tag = null; }
  33066. var label = document.createElement("label");
  33067. label.style.display = "inline";
  33068. var boundingBoxesCheckbox = document.createElement("input");
  33069. boundingBoxesCheckbox.type = "checkbox";
  33070. boundingBoxesCheckbox.checked = initialState;
  33071. boundingBoxesCheckbox.style.display = "inline";
  33072. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  33073. boundingBoxesCheckbox.style.verticalAlign = "sub";
  33074. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  33075. task(evt.target, tag);
  33076. });
  33077. label.appendChild(boundingBoxesCheckbox);
  33078. var container = document.createElement("span");
  33079. var leftPart = document.createElement("span");
  33080. var rightPart = document.createElement("span");
  33081. rightPart.style.cssFloat = "right";
  33082. leftPart.innerHTML = leftTitle;
  33083. rightPart.innerHTML = rightTitle;
  33084. rightPart.style.fontSize = "12px";
  33085. rightPart.style.maxWidth = "200px";
  33086. container.appendChild(leftPart);
  33087. container.appendChild(rightPart);
  33088. label.appendChild(container);
  33089. root.appendChild(label);
  33090. root.appendChild(document.createElement("br"));
  33091. };
  33092. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  33093. if (tag === void 0) { tag = null; }
  33094. var label = document.createElement("label");
  33095. label.style.display = "inline";
  33096. var checkBox = document.createElement("input");
  33097. checkBox.type = "checkbox";
  33098. checkBox.checked = initialState;
  33099. checkBox.style.display = "inline";
  33100. checkBox.style.margin = "0px 5px 0px 0px";
  33101. checkBox.style.verticalAlign = "sub";
  33102. checkBox.addEventListener("change", function (evt) {
  33103. task(evt.target, tag);
  33104. });
  33105. label.appendChild(checkBox);
  33106. label.appendChild(document.createTextNode(title));
  33107. root.appendChild(label);
  33108. root.appendChild(document.createElement("br"));
  33109. };
  33110. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  33111. if (tag === void 0) { tag = null; }
  33112. var button = document.createElement("button");
  33113. button.innerHTML = title;
  33114. button.style.height = "24px";
  33115. button.style.width = "150px";
  33116. button.style.marginBottom = "5px";
  33117. button.style.color = "#444444";
  33118. button.style.border = "1px solid white";
  33119. button.className = "debugLayerButton";
  33120. button.addEventListener("click", function (evt) {
  33121. task(evt.target, tag);
  33122. });
  33123. root.appendChild(button);
  33124. root.appendChild(document.createElement("br"));
  33125. };
  33126. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  33127. if (tag === void 0) { tag = null; }
  33128. var label = document.createElement("label");
  33129. label.style.display = "inline";
  33130. var boundingBoxesRadio = document.createElement("input");
  33131. boundingBoxesRadio.type = "radio";
  33132. boundingBoxesRadio.name = name;
  33133. boundingBoxesRadio.checked = initialState;
  33134. boundingBoxesRadio.style.display = "inline";
  33135. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  33136. boundingBoxesRadio.style.verticalAlign = "sub";
  33137. boundingBoxesRadio.addEventListener("change", function (evt) {
  33138. task(evt.target, tag);
  33139. });
  33140. label.appendChild(boundingBoxesRadio);
  33141. label.appendChild(document.createTextNode(title));
  33142. root.appendChild(label);
  33143. root.appendChild(document.createElement("br"));
  33144. };
  33145. DebugLayer.prototype._generateDOMelements = function () {
  33146. var _this = this;
  33147. this._globalDiv.id = "DebugLayer";
  33148. this._globalDiv.style.position = "absolute";
  33149. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  33150. this._globalDiv.style.fontSize = "14px";
  33151. this._globalDiv.style.color = "white";
  33152. // Drawing canvas
  33153. this._drawingCanvas = document.createElement("canvas");
  33154. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  33155. this._drawingCanvas.style.position = "absolute";
  33156. this._drawingCanvas.style.pointerEvents = "none";
  33157. this._drawingCanvas.style.backgroundColor = "transparent";
  33158. this._drawingContext = this._drawingCanvas.getContext("2d");
  33159. this._globalDiv.appendChild(this._drawingCanvas);
  33160. if (this._showUI) {
  33161. var background = "rgba(128, 128, 128, 0.4)";
  33162. var border = "rgb(180, 180, 180) solid 1px";
  33163. // Stats
  33164. this._statsDiv = document.createElement("div");
  33165. this._statsDiv.id = "DebugLayerStats";
  33166. this._statsDiv.style.border = border;
  33167. this._statsDiv.style.position = "absolute";
  33168. this._statsDiv.style.background = background;
  33169. this._statsDiv.style.padding = "0px 0px 0px 5px";
  33170. this._generateheader(this._statsDiv, "STATISTICS");
  33171. this._statsSubsetDiv = document.createElement("div");
  33172. this._statsSubsetDiv.style.paddingTop = "5px";
  33173. this._statsSubsetDiv.style.paddingBottom = "5px";
  33174. this._statsSubsetDiv.style.overflowY = "auto";
  33175. this._statsDiv.appendChild(this._statsSubsetDiv);
  33176. // Tree
  33177. this._treeDiv = document.createElement("div");
  33178. this._treeDiv.id = "DebugLayerTree";
  33179. this._treeDiv.style.border = border;
  33180. this._treeDiv.style.position = "absolute";
  33181. this._treeDiv.style.background = background;
  33182. this._treeDiv.style.padding = "0px 0px 0px 5px";
  33183. this._treeDiv.style.display = "none";
  33184. this._generateheader(this._treeDiv, "MESHES TREE");
  33185. this._treeSubsetDiv = document.createElement("div");
  33186. this._treeSubsetDiv.style.paddingTop = "5px";
  33187. this._treeSubsetDiv.style.paddingRight = "5px";
  33188. this._treeSubsetDiv.style.overflowY = "auto";
  33189. this._treeSubsetDiv.style.maxHeight = "300px";
  33190. this._treeDiv.appendChild(this._treeSubsetDiv);
  33191. this._needToRefreshMeshesTree = true;
  33192. // Logs
  33193. this._logDiv = document.createElement("div");
  33194. this._logDiv.style.border = border;
  33195. this._logDiv.id = "DebugLayerLogs";
  33196. this._logDiv.style.position = "absolute";
  33197. this._logDiv.style.background = background;
  33198. this._logDiv.style.padding = "0px 0px 0px 5px";
  33199. this._logDiv.style.display = "none";
  33200. this._generateheader(this._logDiv, "LOGS");
  33201. this._logSubsetDiv = document.createElement("div");
  33202. this._logSubsetDiv.style.height = "127px";
  33203. this._logSubsetDiv.style.paddingTop = "5px";
  33204. this._logSubsetDiv.style.overflowY = "auto";
  33205. this._logSubsetDiv.style.fontSize = "12px";
  33206. this._logSubsetDiv.style.fontFamily = "consolas";
  33207. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  33208. this._logDiv.appendChild(this._logSubsetDiv);
  33209. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  33210. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  33211. };
  33212. // Options
  33213. this._optionsDiv = document.createElement("div");
  33214. this._optionsDiv.id = "DebugLayerOptions";
  33215. this._optionsDiv.style.border = border;
  33216. this._optionsDiv.style.position = "absolute";
  33217. this._optionsDiv.style.background = background;
  33218. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  33219. this._optionsDiv.style.overflowY = "auto";
  33220. this._generateheader(this._optionsDiv, "OPTIONS");
  33221. this._optionsSubsetDiv = document.createElement("div");
  33222. this._optionsSubsetDiv.style.paddingTop = "5px";
  33223. this._optionsSubsetDiv.style.paddingBottom = "5px";
  33224. this._optionsSubsetDiv.style.overflowY = "auto";
  33225. this._optionsSubsetDiv.style.maxHeight = "200px";
  33226. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  33227. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  33228. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  33229. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  33230. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  33231. _this._displayTree = element.checked;
  33232. _this._needToRefreshMeshesTree = true;
  33233. });
  33234. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33235. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  33236. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  33237. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  33238. _this._labelsEnabled = element.checked;
  33239. if (!_this._labelsEnabled) {
  33240. _this._clearLabels();
  33241. }
  33242. });
  33243. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  33244. if (element.checked) {
  33245. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  33246. }
  33247. else {
  33248. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  33249. }
  33250. });
  33251. ;
  33252. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33253. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  33254. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  33255. if (element.checked) {
  33256. _this._scene.forceWireframe = false;
  33257. _this._scene.forcePointsCloud = false;
  33258. }
  33259. });
  33260. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  33261. if (element.checked) {
  33262. _this._scene.forceWireframe = true;
  33263. _this._scene.forcePointsCloud = false;
  33264. }
  33265. });
  33266. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  33267. if (element.checked) {
  33268. _this._scene.forceWireframe = false;
  33269. _this._scene.forcePointsCloud = true;
  33270. }
  33271. });
  33272. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33273. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  33274. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  33275. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  33276. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  33277. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  33278. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  33279. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  33280. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  33281. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  33282. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  33283. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  33284. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33285. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  33286. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  33287. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  33288. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  33289. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  33290. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  33291. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  33292. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  33293. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  33294. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  33295. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  33296. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  33297. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  33298. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  33299. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  33300. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  33301. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33302. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  33303. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  33304. if (element.checked) {
  33305. _this._scene.headphone = true;
  33306. }
  33307. });
  33308. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  33309. if (element.checked) {
  33310. _this._scene.headphone = false;
  33311. }
  33312. });
  33313. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  33314. _this._scene.audioEnabled = !element.checked;
  33315. });
  33316. }
  33317. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33318. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  33319. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  33320. if (!element.checked) {
  33321. _this._clearSkeletonViewers();
  33322. return;
  33323. }
  33324. for (var index = 0; index < _this._scene.meshes.length; index++) {
  33325. var mesh = _this._scene.meshes[index];
  33326. if (mesh.skeleton) {
  33327. var found = false;
  33328. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  33329. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  33330. found = true;
  33331. break;
  33332. }
  33333. }
  33334. if (found) {
  33335. continue;
  33336. }
  33337. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  33338. viewer.isEnabled = true;
  33339. _this._skeletonViewers.push(viewer);
  33340. }
  33341. }
  33342. });
  33343. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33344. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  33345. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  33346. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  33347. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  33348. if (_this._camera) {
  33349. console.log(_this._camera);
  33350. }
  33351. else {
  33352. console.warn("No camera defined, or debug layer created before camera creation!");
  33353. }
  33354. });
  33355. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33356. this._globalDiv.appendChild(this._statsDiv);
  33357. this._globalDiv.appendChild(this._logDiv);
  33358. this._globalDiv.appendChild(this._optionsDiv);
  33359. this._globalDiv.appendChild(this._treeDiv);
  33360. }
  33361. };
  33362. DebugLayer.prototype._displayStats = function () {
  33363. var scene = this._scene;
  33364. var engine = scene.getEngine();
  33365. var glInfo = engine.getGlInfo();
  33366. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  33367. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33368. + "<b>Count</b><br>"
  33369. + "Total meshes: " + scene.meshes.length + "<br>"
  33370. + "Total lights: " + scene.lights.length + "<br>"
  33371. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  33372. + "Total materials: " + scene.materials.length + "<br>"
  33373. + "Total textures: " + scene.textures.length + "<br>"
  33374. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  33375. + "Active indices: " + scene.getActiveIndices() + "<br>"
  33376. + "Active bones: " + scene.getActiveBones() + "<br>"
  33377. + "Active particles: " + scene.getActiveParticles() + "<br>"
  33378. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  33379. + "<b>Duration</b><br>"
  33380. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  33381. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  33382. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  33383. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  33384. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  33385. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  33386. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  33387. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  33388. + "</div>"
  33389. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33390. + "<b>Extensions</b><br>"
  33391. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  33392. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  33393. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  33394. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  33395. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  33396. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  33397. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  33398. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  33399. + "</div><br>"
  33400. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33401. + "<b>Caps.</b><br>"
  33402. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  33403. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  33404. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  33405. + "<b>Info</b><br>"
  33406. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  33407. + glInfo.version + "<br>"
  33408. + "</div><br>"
  33409. + glInfo.renderer + "<br>";
  33410. if (this.customStatsFunction) {
  33411. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  33412. }
  33413. };
  33414. return DebugLayer;
  33415. })();
  33416. BABYLON.DebugLayer = DebugLayer;
  33417. })(BABYLON || (BABYLON = {}));
  33418. var BABYLON;
  33419. (function (BABYLON) {
  33420. var DefaultLoadingScreen = (function () {
  33421. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33422. var _this = this;
  33423. if (_loadingText === void 0) { _loadingText = ""; }
  33424. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33425. this._renderingCanvas = _renderingCanvas;
  33426. this._loadingText = _loadingText;
  33427. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33428. // Resize
  33429. this._resizeLoadingUI = function () {
  33430. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33431. _this._loadingDiv.style.position = "absolute";
  33432. _this._loadingDiv.style.left = canvasRect.left + "px";
  33433. _this._loadingDiv.style.top = canvasRect.top + "px";
  33434. _this._loadingDiv.style.width = canvasRect.width + "px";
  33435. _this._loadingDiv.style.height = canvasRect.height + "px";
  33436. };
  33437. }
  33438. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33439. var _this = this;
  33440. if (this._loadingDiv) {
  33441. // Do not add a loading screen if there is already one
  33442. return;
  33443. }
  33444. this._loadingDiv = document.createElement("div");
  33445. this._loadingDiv.id = "babylonjsLoadingDiv";
  33446. this._loadingDiv.style.opacity = "0";
  33447. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33448. // Loading text
  33449. this._loadingTextDiv = document.createElement("div");
  33450. this._loadingTextDiv.style.position = "absolute";
  33451. this._loadingTextDiv.style.left = "0";
  33452. this._loadingTextDiv.style.top = "50%";
  33453. this._loadingTextDiv.style.marginTop = "80px";
  33454. this._loadingTextDiv.style.width = "100%";
  33455. this._loadingTextDiv.style.height = "20px";
  33456. this._loadingTextDiv.style.fontFamily = "Arial";
  33457. this._loadingTextDiv.style.fontSize = "14px";
  33458. this._loadingTextDiv.style.color = "white";
  33459. this._loadingTextDiv.style.textAlign = "center";
  33460. this._loadingTextDiv.innerHTML = "Loading";
  33461. this._loadingDiv.appendChild(this._loadingTextDiv);
  33462. //set the predefined text
  33463. this._loadingTextDiv.innerHTML = this._loadingText;
  33464. // Loading img
  33465. var imgBack = new Image();
  33466. 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==";
  33467. imgBack.style.position = "absolute";
  33468. imgBack.style.left = "50%";
  33469. imgBack.style.top = "50%";
  33470. imgBack.style.marginLeft = "-50px";
  33471. imgBack.style.marginTop = "-50px";
  33472. imgBack.style.transition = "transform 1.0s ease";
  33473. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33474. var deg = 360;
  33475. var onTransitionEnd = function () {
  33476. deg += 360;
  33477. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33478. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33479. };
  33480. imgBack.addEventListener("transitionend", onTransitionEnd);
  33481. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33482. this._loadingDiv.appendChild(imgBack);
  33483. // front image
  33484. var imgFront = new Image();
  33485. 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=";
  33486. imgFront.style.position = "absolute";
  33487. imgFront.style.left = "50%";
  33488. imgFront.style.top = "50%";
  33489. imgFront.style.marginLeft = "-50px";
  33490. imgFront.style.marginTop = "-50px";
  33491. this._loadingDiv.appendChild(imgFront);
  33492. this._resizeLoadingUI();
  33493. window.addEventListener("resize", this._resizeLoadingUI);
  33494. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33495. document.body.appendChild(this._loadingDiv);
  33496. setTimeout(function () {
  33497. _this._loadingDiv.style.opacity = "1";
  33498. imgBack.style.transform = "rotateZ(360deg)";
  33499. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33500. }, 0);
  33501. };
  33502. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33503. var _this = this;
  33504. if (!this._loadingDiv) {
  33505. return;
  33506. }
  33507. var onTransitionEnd = function () {
  33508. if (!_this._loadingDiv) {
  33509. return;
  33510. }
  33511. document.body.removeChild(_this._loadingDiv);
  33512. window.removeEventListener("resize", _this._resizeLoadingUI);
  33513. _this._loadingDiv = null;
  33514. };
  33515. this._loadingDiv.style.opacity = "0";
  33516. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33517. };
  33518. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33519. set: function (text) {
  33520. this._loadingText = text;
  33521. if (this._loadingTextDiv) {
  33522. this._loadingTextDiv.innerHTML = this._loadingText;
  33523. }
  33524. },
  33525. enumerable: true,
  33526. configurable: true
  33527. });
  33528. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33529. get: function () {
  33530. return this._loadingDivBackgroundColor;
  33531. },
  33532. set: function (color) {
  33533. this._loadingDivBackgroundColor = color;
  33534. if (!this._loadingDiv) {
  33535. return;
  33536. }
  33537. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33538. },
  33539. enumerable: true,
  33540. configurable: true
  33541. });
  33542. return DefaultLoadingScreen;
  33543. })();
  33544. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33545. })(BABYLON || (BABYLON = {}));
  33546. var BABYLON;
  33547. (function (BABYLON) {
  33548. var AudioEngine = (function () {
  33549. function AudioEngine() {
  33550. this._audioContext = null;
  33551. this._audioContextInitialized = false;
  33552. this.canUseWebAudio = false;
  33553. this.WarnedWebAudioUnsupported = false;
  33554. this.unlocked = false;
  33555. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33556. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33557. this.canUseWebAudio = true;
  33558. }
  33559. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33560. this._unlockiOSaudio();
  33561. }
  33562. else {
  33563. this.unlocked = true;
  33564. }
  33565. }
  33566. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33567. get: function () {
  33568. if (!this._audioContextInitialized) {
  33569. this._initializeAudioContext();
  33570. }
  33571. return this._audioContext;
  33572. },
  33573. enumerable: true,
  33574. configurable: true
  33575. });
  33576. AudioEngine.prototype._unlockiOSaudio = function () {
  33577. var _this = this;
  33578. var unlockaudio = function () {
  33579. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33580. var source = _this.audioContext.createBufferSource();
  33581. source.buffer = buffer;
  33582. source.connect(_this.audioContext.destination);
  33583. source.start(0);
  33584. setTimeout(function () {
  33585. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33586. _this.unlocked = true;
  33587. window.removeEventListener('touchend', unlockaudio, false);
  33588. if (_this.onAudioUnlocked) {
  33589. _this.onAudioUnlocked();
  33590. }
  33591. }
  33592. }, 0);
  33593. };
  33594. window.addEventListener('touchend', unlockaudio, false);
  33595. };
  33596. AudioEngine.prototype._initializeAudioContext = function () {
  33597. try {
  33598. if (this.canUseWebAudio) {
  33599. this._audioContext = new AudioContext();
  33600. // create a global volume gain node
  33601. this.masterGain = this._audioContext.createGain();
  33602. this.masterGain.gain.value = 1;
  33603. this.masterGain.connect(this._audioContext.destination);
  33604. this._audioContextInitialized = true;
  33605. }
  33606. }
  33607. catch (e) {
  33608. this.canUseWebAudio = false;
  33609. BABYLON.Tools.Error("Web Audio: " + e.message);
  33610. }
  33611. };
  33612. AudioEngine.prototype.dispose = function () {
  33613. if (this.canUseWebAudio && this._audioContextInitialized) {
  33614. if (this._connectedAnalyser) {
  33615. this._connectedAnalyser.stopDebugCanvas();
  33616. this._connectedAnalyser.dispose();
  33617. this.masterGain.disconnect();
  33618. this.masterGain.connect(this._audioContext.destination);
  33619. this._connectedAnalyser = null;
  33620. }
  33621. this.masterGain.gain.value = 1;
  33622. }
  33623. this.WarnedWebAudioUnsupported = false;
  33624. };
  33625. AudioEngine.prototype.getGlobalVolume = function () {
  33626. if (this.canUseWebAudio && this._audioContextInitialized) {
  33627. return this.masterGain.gain.value;
  33628. }
  33629. else {
  33630. return -1;
  33631. }
  33632. };
  33633. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33634. if (this.canUseWebAudio && this._audioContextInitialized) {
  33635. this.masterGain.gain.value = newVolume;
  33636. }
  33637. };
  33638. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33639. if (this._connectedAnalyser) {
  33640. this._connectedAnalyser.stopDebugCanvas();
  33641. }
  33642. if (this.canUseWebAudio && this._audioContextInitialized) {
  33643. this._connectedAnalyser = analyser;
  33644. this.masterGain.disconnect();
  33645. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33646. }
  33647. };
  33648. return AudioEngine;
  33649. })();
  33650. BABYLON.AudioEngine = AudioEngine;
  33651. })(BABYLON || (BABYLON = {}));
  33652. var BABYLON;
  33653. (function (BABYLON) {
  33654. var Sound = (function () {
  33655. /**
  33656. * Create a sound and attach it to a scene
  33657. * @param name Name of your sound
  33658. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33659. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33660. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33661. */
  33662. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33663. var _this = this;
  33664. this.autoplay = false;
  33665. this.loop = false;
  33666. this.useCustomAttenuation = false;
  33667. this.spatialSound = false;
  33668. this.refDistance = 1;
  33669. this.rolloffFactor = 1;
  33670. this.maxDistance = 100;
  33671. this.distanceModel = "linear";
  33672. this._panningModel = "equalpower";
  33673. this._playbackRate = 1;
  33674. this._streaming = false;
  33675. this._startTime = 0;
  33676. this._startOffset = 0;
  33677. this._position = BABYLON.Vector3.Zero();
  33678. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33679. this._volume = 1;
  33680. this._isLoaded = false;
  33681. this._isReadyToPlay = false;
  33682. this.isPlaying = false;
  33683. this.isPaused = false;
  33684. this._isDirectional = false;
  33685. // Used if you'd like to create a directional sound.
  33686. // If not set, the sound will be omnidirectional
  33687. this._coneInnerAngle = 360;
  33688. this._coneOuterAngle = 360;
  33689. this._coneOuterGain = 0;
  33690. this._isOutputConnected = false;
  33691. this.name = name;
  33692. this._scene = scene;
  33693. this._readyToPlayCallback = readyToPlayCallback;
  33694. // Default custom attenuation function is a linear attenuation
  33695. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33696. if (currentDistance < maxDistance) {
  33697. return currentVolume * (1 - currentDistance / maxDistance);
  33698. }
  33699. else {
  33700. return 0;
  33701. }
  33702. };
  33703. if (options) {
  33704. this.autoplay = options.autoplay || false;
  33705. this.loop = options.loop || false;
  33706. // if volume === 0, we need another way to check this option
  33707. if (options.volume !== undefined) {
  33708. this._volume = options.volume;
  33709. }
  33710. this.spatialSound = options.spatialSound || false;
  33711. this.maxDistance = options.maxDistance || 100;
  33712. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33713. this.rolloffFactor = options.rolloffFactor || 1;
  33714. this.refDistance = options.refDistance || 1;
  33715. this.distanceModel = options.distanceModel || "linear";
  33716. this._playbackRate = options.playbackRate || 1;
  33717. this._streaming = options.streaming || false;
  33718. }
  33719. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33720. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33721. this._soundGain.gain.value = this._volume;
  33722. this._inputAudioNode = this._soundGain;
  33723. this._ouputAudioNode = this._soundGain;
  33724. if (this.spatialSound) {
  33725. this._createSpatialParameters();
  33726. }
  33727. this._scene.mainSoundTrack.AddSound(this);
  33728. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33729. if (urlOrArrayBuffer) {
  33730. // If it's an URL
  33731. if (typeof (urlOrArrayBuffer) === "string") {
  33732. // Loading sound using XHR2
  33733. if (!this._streaming) {
  33734. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33735. }
  33736. else {
  33737. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33738. this._htmlAudioElement.controls = false;
  33739. this._htmlAudioElement.loop = this.loop;
  33740. this._htmlAudioElement.crossOrigin = "anonymous";
  33741. this._htmlAudioElement.preload = "auto";
  33742. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33743. _this._isReadyToPlay = true;
  33744. if (_this.autoplay) {
  33745. _this.play();
  33746. }
  33747. if (_this._readyToPlayCallback) {
  33748. _this._readyToPlayCallback();
  33749. }
  33750. });
  33751. document.body.appendChild(this._htmlAudioElement);
  33752. }
  33753. }
  33754. else {
  33755. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33756. if (urlOrArrayBuffer.byteLength > 0) {
  33757. this._soundLoaded(urlOrArrayBuffer);
  33758. }
  33759. }
  33760. else {
  33761. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33762. }
  33763. }
  33764. }
  33765. }
  33766. else {
  33767. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33768. this._scene.mainSoundTrack.AddSound(this);
  33769. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33770. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33771. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33772. }
  33773. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33774. if (this._readyToPlayCallback) {
  33775. window.setTimeout(function () {
  33776. _this._readyToPlayCallback();
  33777. }, 1000);
  33778. }
  33779. }
  33780. }
  33781. Sound.prototype.dispose = function () {
  33782. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33783. if (this.isPlaying) {
  33784. this.stop();
  33785. }
  33786. this._isReadyToPlay = false;
  33787. if (this.soundTrackId === -1) {
  33788. this._scene.mainSoundTrack.RemoveSound(this);
  33789. }
  33790. else {
  33791. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33792. }
  33793. if (this._soundGain) {
  33794. this._soundGain.disconnect();
  33795. this._soundGain = null;
  33796. }
  33797. if (this._soundPanner) {
  33798. this._soundPanner.disconnect();
  33799. this._soundPanner = null;
  33800. }
  33801. if (this._soundSource) {
  33802. this._soundSource.disconnect();
  33803. this._soundSource = null;
  33804. }
  33805. this._audioBuffer = null;
  33806. if (this._htmlAudioElement) {
  33807. this._htmlAudioElement.pause();
  33808. this._htmlAudioElement.src = "";
  33809. document.body.removeChild(this._htmlAudioElement);
  33810. }
  33811. if (this._connectedMesh) {
  33812. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33813. this._connectedMesh = null;
  33814. }
  33815. }
  33816. };
  33817. Sound.prototype._soundLoaded = function (audioData) {
  33818. var _this = this;
  33819. this._isLoaded = true;
  33820. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33821. _this._audioBuffer = buffer;
  33822. _this._isReadyToPlay = true;
  33823. if (_this.autoplay) {
  33824. _this.play();
  33825. }
  33826. if (_this._readyToPlayCallback) {
  33827. _this._readyToPlayCallback();
  33828. }
  33829. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33830. };
  33831. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33832. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33833. this._audioBuffer = audioBuffer;
  33834. this._isReadyToPlay = true;
  33835. }
  33836. };
  33837. Sound.prototype.updateOptions = function (options) {
  33838. if (options) {
  33839. this.loop = options.loop || this.loop;
  33840. this.maxDistance = options.maxDistance || this.maxDistance;
  33841. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33842. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33843. this.refDistance = options.refDistance || this.refDistance;
  33844. this.distanceModel = options.distanceModel || this.distanceModel;
  33845. this._playbackRate = options.playbackRate || this._playbackRate;
  33846. this._updateSpatialParameters();
  33847. if (this.isPlaying) {
  33848. if (this._streaming) {
  33849. this._htmlAudioElement.playbackRate = this._playbackRate;
  33850. }
  33851. else {
  33852. this._soundSource.playbackRate.value = this._playbackRate;
  33853. }
  33854. }
  33855. }
  33856. };
  33857. Sound.prototype._createSpatialParameters = function () {
  33858. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33859. if (this._scene.headphone) {
  33860. this._panningModel = "HRTF";
  33861. }
  33862. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33863. this._updateSpatialParameters();
  33864. this._soundPanner.connect(this._ouputAudioNode);
  33865. this._inputAudioNode = this._soundPanner;
  33866. }
  33867. };
  33868. Sound.prototype._updateSpatialParameters = function () {
  33869. if (this.spatialSound) {
  33870. if (this.useCustomAttenuation) {
  33871. // Tricks to disable in a way embedded Web Audio attenuation
  33872. this._soundPanner.distanceModel = "linear";
  33873. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33874. this._soundPanner.refDistance = 1;
  33875. this._soundPanner.rolloffFactor = 1;
  33876. this._soundPanner.panningModel = this._panningModel;
  33877. }
  33878. else {
  33879. this._soundPanner.distanceModel = this.distanceModel;
  33880. this._soundPanner.maxDistance = this.maxDistance;
  33881. this._soundPanner.refDistance = this.refDistance;
  33882. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33883. this._soundPanner.panningModel = this._panningModel;
  33884. }
  33885. }
  33886. };
  33887. Sound.prototype.switchPanningModelToHRTF = function () {
  33888. this._panningModel = "HRTF";
  33889. this._switchPanningModel();
  33890. };
  33891. Sound.prototype.switchPanningModelToEqualPower = function () {
  33892. this._panningModel = "equalpower";
  33893. this._switchPanningModel();
  33894. };
  33895. Sound.prototype._switchPanningModel = function () {
  33896. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33897. this._soundPanner.panningModel = this._panningModel;
  33898. }
  33899. };
  33900. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33901. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33902. if (this._isOutputConnected) {
  33903. this._ouputAudioNode.disconnect();
  33904. }
  33905. this._ouputAudioNode.connect(soundTrackAudioNode);
  33906. this._isOutputConnected = true;
  33907. }
  33908. };
  33909. /**
  33910. * Transform this sound into a directional source
  33911. * @param coneInnerAngle Size of the inner cone in degree
  33912. * @param coneOuterAngle Size of the outer cone in degree
  33913. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33914. */
  33915. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33916. if (coneOuterAngle < coneInnerAngle) {
  33917. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33918. return;
  33919. }
  33920. this._coneInnerAngle = coneInnerAngle;
  33921. this._coneOuterAngle = coneOuterAngle;
  33922. this._coneOuterGain = coneOuterGain;
  33923. this._isDirectional = true;
  33924. if (this.isPlaying && this.loop) {
  33925. this.stop();
  33926. this.play();
  33927. }
  33928. };
  33929. Sound.prototype.setPosition = function (newPosition) {
  33930. this._position = newPosition;
  33931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33932. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33933. }
  33934. };
  33935. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33936. this._localDirection = newLocalDirection;
  33937. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33938. this._updateDirection();
  33939. }
  33940. };
  33941. Sound.prototype._updateDirection = function () {
  33942. var mat = this._connectedMesh.getWorldMatrix();
  33943. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33944. direction.normalize();
  33945. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33946. };
  33947. Sound.prototype.updateDistanceFromListener = function () {
  33948. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33949. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33950. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33951. }
  33952. };
  33953. Sound.prototype.setAttenuationFunction = function (callback) {
  33954. this._customAttenuationFunction = callback;
  33955. };
  33956. /**
  33957. * Play the sound
  33958. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33959. */
  33960. Sound.prototype.play = function (time) {
  33961. var _this = this;
  33962. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33963. try {
  33964. if (this._startOffset < 0) {
  33965. time = -this._startOffset;
  33966. this._startOffset = 0;
  33967. }
  33968. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33969. if (!this._soundSource || !this._streamingSource) {
  33970. if (this.spatialSound) {
  33971. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33972. if (this._isDirectional) {
  33973. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33974. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33975. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33976. if (this._connectedMesh) {
  33977. this._updateDirection();
  33978. }
  33979. else {
  33980. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33981. }
  33982. }
  33983. }
  33984. }
  33985. if (this._streaming) {
  33986. if (!this._streamingSource) {
  33987. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33988. this._htmlAudioElement.onended = function () { _this._onended(); };
  33989. this._htmlAudioElement.playbackRate = this._playbackRate;
  33990. }
  33991. this._streamingSource.disconnect();
  33992. this._streamingSource.connect(this._inputAudioNode);
  33993. this._htmlAudioElement.play();
  33994. }
  33995. else {
  33996. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33997. this._soundSource.buffer = this._audioBuffer;
  33998. this._soundSource.connect(this._inputAudioNode);
  33999. this._soundSource.loop = this.loop;
  34000. this._soundSource.playbackRate.value = this._playbackRate;
  34001. this._soundSource.onended = function () { _this._onended(); };
  34002. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34003. }
  34004. this._startTime = startTime;
  34005. this.isPlaying = true;
  34006. this.isPaused = false;
  34007. }
  34008. catch (ex) {
  34009. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34010. }
  34011. }
  34012. };
  34013. Sound.prototype._onended = function () {
  34014. this.isPlaying = false;
  34015. if (this.onended) {
  34016. this.onended();
  34017. }
  34018. };
  34019. /**
  34020. * Stop the sound
  34021. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34022. */
  34023. Sound.prototype.stop = function (time) {
  34024. if (this.isPlaying) {
  34025. if (this._streaming) {
  34026. this._htmlAudioElement.pause();
  34027. // Test needed for Firefox or it will generate an Invalid State Error
  34028. if (this._htmlAudioElement.currentTime > 0) {
  34029. this._htmlAudioElement.currentTime = 0;
  34030. }
  34031. }
  34032. else {
  34033. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34034. this._soundSource.stop(stopTime);
  34035. if (!this.isPaused) {
  34036. this._startOffset = 0;
  34037. }
  34038. }
  34039. this.isPlaying = false;
  34040. }
  34041. };
  34042. Sound.prototype.pause = function () {
  34043. if (this.isPlaying) {
  34044. this.isPaused = true;
  34045. if (this._streaming) {
  34046. this._htmlAudioElement.pause();
  34047. }
  34048. else {
  34049. this.stop(0);
  34050. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34051. }
  34052. }
  34053. };
  34054. Sound.prototype.setVolume = function (newVolume, time) {
  34055. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34056. if (time) {
  34057. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34058. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34059. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34060. }
  34061. else {
  34062. this._soundGain.gain.value = newVolume;
  34063. }
  34064. }
  34065. this._volume = newVolume;
  34066. };
  34067. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34068. this._playbackRate = newPlaybackRate;
  34069. if (this.isPlaying) {
  34070. if (this._streaming) {
  34071. this._htmlAudioElement.playbackRate = this._playbackRate;
  34072. }
  34073. else {
  34074. this._soundSource.playbackRate.value = this._playbackRate;
  34075. }
  34076. }
  34077. };
  34078. Sound.prototype.getVolume = function () {
  34079. return this._volume;
  34080. };
  34081. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34082. var _this = this;
  34083. if (this._connectedMesh) {
  34084. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34085. this._registerFunc = null;
  34086. }
  34087. this._connectedMesh = meshToConnectTo;
  34088. if (!this.spatialSound) {
  34089. this.spatialSound = true;
  34090. this._createSpatialParameters();
  34091. if (this.isPlaying && this.loop) {
  34092. this.stop();
  34093. this.play();
  34094. }
  34095. }
  34096. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34097. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34098. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34099. };
  34100. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34101. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34102. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34103. this._updateDirection();
  34104. }
  34105. };
  34106. Sound.prototype.clone = function () {
  34107. var _this = this;
  34108. if (!this._streaming) {
  34109. var setBufferAndRun = function () {
  34110. if (_this._isReadyToPlay) {
  34111. clonedSound._audioBuffer = _this.getAudioBuffer();
  34112. clonedSound._isReadyToPlay = true;
  34113. if (clonedSound.autoplay) {
  34114. clonedSound.play();
  34115. }
  34116. }
  34117. else {
  34118. window.setTimeout(setBufferAndRun, 300);
  34119. }
  34120. };
  34121. var currentOptions = {
  34122. autoplay: this.autoplay, loop: this.loop,
  34123. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34124. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34125. refDistance: this.refDistance, distanceModel: this.distanceModel
  34126. };
  34127. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34128. if (this.useCustomAttenuation) {
  34129. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34130. }
  34131. clonedSound.setPosition(this._position);
  34132. clonedSound.setPlaybackRate(this._playbackRate);
  34133. setBufferAndRun();
  34134. return clonedSound;
  34135. }
  34136. else {
  34137. return null;
  34138. }
  34139. };
  34140. Sound.prototype.getAudioBuffer = function () {
  34141. return this._audioBuffer;
  34142. };
  34143. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34144. var soundName = parsedSound.name;
  34145. var soundUrl;
  34146. if (parsedSound.url) {
  34147. soundUrl = rootUrl + parsedSound.url;
  34148. }
  34149. else {
  34150. soundUrl = rootUrl + soundName;
  34151. }
  34152. var options = {
  34153. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34154. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34155. rolloffFactor: parsedSound.rolloffFactor,
  34156. refDistance: parsedSound.refDistance,
  34157. distanceModel: parsedSound.distanceModel,
  34158. playbackRate: parsedSound.playbackRate
  34159. };
  34160. var newSound;
  34161. if (!sourceSound) {
  34162. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34163. scene._addPendingData(newSound);
  34164. }
  34165. else {
  34166. var setBufferAndRun = function () {
  34167. if (sourceSound._isReadyToPlay) {
  34168. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34169. newSound._isReadyToPlay = true;
  34170. if (newSound.autoplay) {
  34171. newSound.play();
  34172. }
  34173. }
  34174. else {
  34175. window.setTimeout(setBufferAndRun, 300);
  34176. }
  34177. };
  34178. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34179. setBufferAndRun();
  34180. }
  34181. if (parsedSound.position) {
  34182. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34183. newSound.setPosition(soundPosition);
  34184. }
  34185. if (parsedSound.isDirectional) {
  34186. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34187. if (parsedSound.localDirectionToMesh) {
  34188. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34189. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34190. }
  34191. }
  34192. if (parsedSound.connectedMeshId) {
  34193. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34194. if (connectedMesh) {
  34195. newSound.attachToMesh(connectedMesh);
  34196. }
  34197. }
  34198. return newSound;
  34199. };
  34200. return Sound;
  34201. })();
  34202. BABYLON.Sound = Sound;
  34203. })(BABYLON || (BABYLON = {}));
  34204. var BABYLON;
  34205. (function (BABYLON) {
  34206. var SoundTrack = (function () {
  34207. function SoundTrack(scene, options) {
  34208. this.id = -1;
  34209. this._isMainTrack = false;
  34210. this._isInitialized = false;
  34211. this._scene = scene;
  34212. this.soundCollection = new Array();
  34213. this._options = options;
  34214. if (!this._isMainTrack) {
  34215. this._scene.soundTracks.push(this);
  34216. this.id = this._scene.soundTracks.length - 1;
  34217. }
  34218. }
  34219. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34220. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34221. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34222. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34223. if (this._options) {
  34224. if (this._options.volume) {
  34225. this._outputAudioNode.gain.value = this._options.volume;
  34226. }
  34227. if (this._options.mainTrack) {
  34228. this._isMainTrack = this._options.mainTrack;
  34229. }
  34230. }
  34231. this._isInitialized = true;
  34232. }
  34233. };
  34234. SoundTrack.prototype.dispose = function () {
  34235. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34236. if (this._connectedAnalyser) {
  34237. this._connectedAnalyser.stopDebugCanvas();
  34238. }
  34239. while (this.soundCollection.length) {
  34240. this.soundCollection[0].dispose();
  34241. }
  34242. if (this._outputAudioNode) {
  34243. this._outputAudioNode.disconnect();
  34244. }
  34245. this._outputAudioNode = null;
  34246. }
  34247. };
  34248. SoundTrack.prototype.AddSound = function (sound) {
  34249. if (!this._isInitialized) {
  34250. this._initializeSoundTrackAudioGraph();
  34251. }
  34252. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34253. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34254. }
  34255. if (sound.soundTrackId) {
  34256. if (sound.soundTrackId === -1) {
  34257. this._scene.mainSoundTrack.RemoveSound(sound);
  34258. }
  34259. else {
  34260. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34261. }
  34262. }
  34263. this.soundCollection.push(sound);
  34264. sound.soundTrackId = this.id;
  34265. };
  34266. SoundTrack.prototype.RemoveSound = function (sound) {
  34267. var index = this.soundCollection.indexOf(sound);
  34268. if (index !== -1) {
  34269. this.soundCollection.splice(index, 1);
  34270. }
  34271. };
  34272. SoundTrack.prototype.setVolume = function (newVolume) {
  34273. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34274. this._outputAudioNode.gain.value = newVolume;
  34275. }
  34276. };
  34277. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34278. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34279. for (var i = 0; i < this.soundCollection.length; i++) {
  34280. this.soundCollection[i].switchPanningModelToHRTF();
  34281. }
  34282. }
  34283. };
  34284. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34285. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34286. for (var i = 0; i < this.soundCollection.length; i++) {
  34287. this.soundCollection[i].switchPanningModelToEqualPower();
  34288. }
  34289. }
  34290. };
  34291. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34292. if (this._connectedAnalyser) {
  34293. this._connectedAnalyser.stopDebugCanvas();
  34294. }
  34295. this._connectedAnalyser = analyser;
  34296. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34297. this._outputAudioNode.disconnect();
  34298. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34299. }
  34300. };
  34301. return SoundTrack;
  34302. })();
  34303. BABYLON.SoundTrack = SoundTrack;
  34304. })(BABYLON || (BABYLON = {}));
  34305. var BABYLON;
  34306. (function (BABYLON) {
  34307. var SIMDVector3 = (function () {
  34308. function SIMDVector3() {
  34309. }
  34310. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34311. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34312. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34313. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34314. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34315. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34316. 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));
  34317. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34318. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34319. };
  34320. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34321. var v0 = SIMD.float32x4.splat(x);
  34322. var v1 = SIMD.float32x4.splat(y);
  34323. var v2 = SIMD.float32x4.splat(z);
  34324. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34325. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34326. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34327. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34328. 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));
  34329. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34330. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34331. };
  34332. return SIMDVector3;
  34333. })();
  34334. BABYLON.SIMDVector3 = SIMDVector3;
  34335. var SIMDMatrix = (function () {
  34336. function SIMDMatrix() {
  34337. }
  34338. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34339. if (offset === void 0) { offset = 0; }
  34340. var tm = this.m;
  34341. var om = other.m;
  34342. var om0 = SIMD.float32x4.load(om, 0);
  34343. var om1 = SIMD.float32x4.load(om, 4);
  34344. var om2 = SIMD.float32x4.load(om, 8);
  34345. var om3 = SIMD.float32x4.load(om, 12);
  34346. var tm0 = SIMD.float32x4.load(tm, 0);
  34347. 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)))));
  34348. var tm1 = SIMD.float32x4.load(tm, 4);
  34349. 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)))));
  34350. var tm2 = SIMD.float32x4.load(tm, 8);
  34351. 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)))));
  34352. var tm3 = SIMD.float32x4.load(tm, 12);
  34353. 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)))));
  34354. };
  34355. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34356. var src = this.m;
  34357. var dest = other.m;
  34358. var row0, row1, row2, row3;
  34359. var tmp1;
  34360. var minor0, minor1, minor2, minor3;
  34361. var det;
  34362. // Load the 4 rows
  34363. var src0 = SIMD.float32x4.load(src, 0);
  34364. var src1 = SIMD.float32x4.load(src, 4);
  34365. var src2 = SIMD.float32x4.load(src, 8);
  34366. var src3 = SIMD.float32x4.load(src, 12);
  34367. // Transpose the source matrix. Sort of. Not a true transpose operation
  34368. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34369. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34370. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34371. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34372. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34373. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34374. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34375. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34376. // This is a true transposition, but it will lead to an incorrect result
  34377. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34378. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34379. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34380. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34381. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34382. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34383. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34384. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34385. // ----
  34386. tmp1 = SIMD.float32x4.mul(row2, row3);
  34387. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34388. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34389. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34390. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34391. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34392. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34393. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34394. // ----
  34395. tmp1 = SIMD.float32x4.mul(row1, row2);
  34396. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34397. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34398. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34399. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34400. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34401. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34402. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34403. // ----
  34404. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34405. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34406. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34407. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34408. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34409. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34410. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34411. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34412. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34413. // ----
  34414. tmp1 = SIMD.float32x4.mul(row0, row1);
  34415. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34416. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34417. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34418. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34419. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34420. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34421. // ----
  34422. tmp1 = SIMD.float32x4.mul(row0, row3);
  34423. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34424. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34425. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34426. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34427. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34428. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34429. // ----
  34430. tmp1 = SIMD.float32x4.mul(row0, row2);
  34431. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34432. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34433. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34434. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34435. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34436. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34437. // Compute determinant
  34438. det = SIMD.float32x4.mul(row0, minor0);
  34439. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34440. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34441. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34442. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34443. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34444. // These shuffles aren't necessary if the faulty transposition is done
  34445. // up at the top of this function.
  34446. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34447. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34448. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34449. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34450. // Compute final values by multiplying with 1/det
  34451. minor0 = SIMD.float32x4.mul(det, minor0);
  34452. minor1 = SIMD.float32x4.mul(det, minor1);
  34453. minor2 = SIMD.float32x4.mul(det, minor2);
  34454. minor3 = SIMD.float32x4.mul(det, minor3);
  34455. SIMD.float32x4.store(dest, 0, minor0);
  34456. SIMD.float32x4.store(dest, 4, minor1);
  34457. SIMD.float32x4.store(dest, 8, minor2);
  34458. SIMD.float32x4.store(dest, 12, minor3);
  34459. return this;
  34460. };
  34461. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34462. var out = result.m;
  34463. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34464. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34465. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34466. // cc.kmVec3Subtract(f, pCenter, pEye);
  34467. var f = SIMD.float32x4.sub(center, eye);
  34468. // cc.kmVec3Normalize(f, f);
  34469. var tmp = SIMD.float32x4.mul(f, f);
  34470. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34471. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34472. // cc.kmVec3Assign(up, pUp);
  34473. // cc.kmVec3Normalize(up, up);
  34474. tmp = SIMD.float32x4.mul(up, up);
  34475. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34476. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34477. // cc.kmVec3Cross(s, f, up);
  34478. 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)));
  34479. // cc.kmVec3Normalize(s, s);
  34480. tmp = SIMD.float32x4.mul(s, s);
  34481. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34482. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34483. // cc.kmVec3Cross(u, s, f);
  34484. 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)));
  34485. // cc.kmVec3Normalize(s, s);
  34486. tmp = SIMD.float32x4.mul(s, s);
  34487. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34488. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34489. var zero = SIMD.float32x4.splat(0.0);
  34490. s = SIMD.float32x4.neg(s);
  34491. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34492. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34493. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34494. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34495. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34496. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34497. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34498. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34499. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34500. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34501. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34502. var b3 = SIMD.float32x4.neg(eye);
  34503. b3 = SIMD.float32x4.withW(b3, 1.0);
  34504. 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)))));
  34505. 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)))));
  34506. 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)))));
  34507. 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)))));
  34508. };
  34509. return SIMDMatrix;
  34510. })();
  34511. BABYLON.SIMDMatrix = SIMDMatrix;
  34512. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34513. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34514. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34515. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34516. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34517. var SIMDHelper = (function () {
  34518. function SIMDHelper() {
  34519. }
  34520. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34521. get: function () {
  34522. return SIMDHelper._isEnabled;
  34523. },
  34524. enumerable: true,
  34525. configurable: true
  34526. });
  34527. SIMDHelper.DisableSIMD = function () {
  34528. // Replace functions
  34529. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34530. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34531. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34532. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34533. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34534. SIMDHelper._isEnabled = false;
  34535. };
  34536. SIMDHelper.EnableSIMD = function () {
  34537. if (window.SIMD === undefined) {
  34538. return;
  34539. }
  34540. // Replace functions
  34541. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34542. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34543. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34544. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34546. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34547. get: function () { return this._data[0]; },
  34548. set: function (value) {
  34549. if (!this._data) {
  34550. this._data = new Float32Array(3);
  34551. }
  34552. this._data[0] = value;
  34553. }
  34554. });
  34555. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34556. get: function () { return this._data[1]; },
  34557. set: function (value) {
  34558. this._data[1] = value;
  34559. }
  34560. });
  34561. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34562. get: function () { return this._data[2]; },
  34563. set: function (value) {
  34564. this._data[2] = value;
  34565. }
  34566. });
  34567. SIMDHelper._isEnabled = true;
  34568. };
  34569. SIMDHelper._isEnabled = false;
  34570. return SIMDHelper;
  34571. })();
  34572. BABYLON.SIMDHelper = SIMDHelper;
  34573. })(BABYLON || (BABYLON = {}));
  34574. var BABYLON;
  34575. (function (BABYLON) {
  34576. /**
  34577. * This class describe a rectangle that were added to the map.
  34578. * You have access to its coordinates either in pixel or normalized (UV)
  34579. */
  34580. var PackedRect = (function () {
  34581. function PackedRect(root, parent, pos, size) {
  34582. this._pos = pos;
  34583. this._size = size;
  34584. this._root = root;
  34585. this._parent = parent;
  34586. }
  34587. Object.defineProperty(PackedRect.prototype, "pos", {
  34588. /**
  34589. * @returns the position of this node into the map
  34590. */
  34591. get: function () {
  34592. return this._pos;
  34593. },
  34594. enumerable: true,
  34595. configurable: true
  34596. });
  34597. Object.defineProperty(PackedRect.prototype, "contentSize", {
  34598. /**
  34599. * @returns the size of the rectangle this node handles
  34600. */
  34601. get: function () {
  34602. return this._contentSize;
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. Object.defineProperty(PackedRect.prototype, "UVs", {
  34608. /**
  34609. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  34610. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  34611. */
  34612. get: function () {
  34613. var mainWidth = this._root._size.width;
  34614. var mainHeight = this._root._size.height;
  34615. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  34616. var rightBottom = new BABYLON.Vector2((this._pos.x + this._contentSize.width - 1) / mainWidth, (this._pos.y + this._contentSize.height - 1) / mainHeight);
  34617. var uvs = new Array();
  34618. uvs.push(topLeft);
  34619. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  34620. uvs.push(rightBottom);
  34621. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  34622. return uvs;
  34623. },
  34624. enumerable: true,
  34625. configurable: true
  34626. });
  34627. /**
  34628. * Free this rectangle from the map.
  34629. * Call this method when you no longer need the rectangle to be in the map.
  34630. */
  34631. PackedRect.prototype.freeContent = function () {
  34632. if (!this.contentSize) {
  34633. return;
  34634. }
  34635. this._contentSize = null;
  34636. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  34637. this.attemptDefrag();
  34638. };
  34639. Object.defineProperty(PackedRect.prototype, "isUsed", {
  34640. get: function () {
  34641. return this._contentSize != null || this._leftNode != null;
  34642. },
  34643. enumerable: true,
  34644. configurable: true
  34645. });
  34646. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  34647. var node = this.findNode(contentSize);
  34648. // Not enought space...
  34649. if (!node) {
  34650. return null;
  34651. }
  34652. node.splitNode(contentSize);
  34653. return node;
  34654. };
  34655. PackedRect.prototype.findNode = function (size) {
  34656. var resNode = null;
  34657. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  34658. if (this.isUsed) {
  34659. if (this._leftNode) {
  34660. resNode = this._leftNode.findNode(size);
  34661. }
  34662. if (!resNode && this._rightNode) {
  34663. resNode = this._rightNode.findNode(size);
  34664. }
  34665. if (!resNode && this._bottomNode) {
  34666. resNode = this._bottomNode.findNode(size);
  34667. }
  34668. }
  34669. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  34670. resNode = this;
  34671. }
  34672. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  34673. resNode = this;
  34674. }
  34675. return resNode;
  34676. };
  34677. PackedRect.prototype.splitNode = function (contentSize) {
  34678. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  34679. if (!this._contentSize && this._initialSize) {
  34680. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  34681. return this._leftNode.splitNode(contentSize);
  34682. }
  34683. else {
  34684. this._contentSize = contentSize.clone();
  34685. this._initialSize = contentSize.clone();
  34686. if (contentSize.width !== this._size.width) {
  34687. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  34688. }
  34689. if (contentSize.height !== this._size.height) {
  34690. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  34691. }
  34692. return this;
  34693. }
  34694. };
  34695. PackedRect.prototype.attemptDefrag = function () {
  34696. if (!this.isUsed && this.isRecursiveFree) {
  34697. this.clearNode();
  34698. if (this._parent) {
  34699. this._parent.attemptDefrag();
  34700. }
  34701. }
  34702. };
  34703. PackedRect.prototype.clearNode = function () {
  34704. this._initialSize = null;
  34705. this._rightNode = null;
  34706. this._bottomNode = null;
  34707. };
  34708. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  34709. get: function () {
  34710. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  34711. },
  34712. enumerable: true,
  34713. configurable: true
  34714. });
  34715. PackedRect.prototype.evalFreeSize = function (size) {
  34716. var levelSize = 0;
  34717. if (!this.isUsed) {
  34718. if (this._initialSize) {
  34719. levelSize = this._initialSize.surface;
  34720. }
  34721. else {
  34722. levelSize = this._size.surface;
  34723. }
  34724. }
  34725. if (this._rightNode) {
  34726. levelSize += this._rightNode.evalFreeSize(0);
  34727. }
  34728. if (this._bottomNode) {
  34729. levelSize += this._bottomNode.evalFreeSize(0);
  34730. }
  34731. return levelSize + size;
  34732. };
  34733. return PackedRect;
  34734. })();
  34735. BABYLON.PackedRect = PackedRect;
  34736. /**
  34737. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimaly as possible.
  34738. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  34739. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their lifecycle.
  34740. */
  34741. var RectPackingMap = (function (_super) {
  34742. __extends(RectPackingMap, _super);
  34743. /**
  34744. * Create an instance of the object with a dimension using the given size
  34745. * @param size The dimension of the rectangle that will contain all the sub ones.
  34746. */
  34747. function RectPackingMap(size) {
  34748. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  34749. this._root = this;
  34750. }
  34751. /**
  34752. * Add a rectangle, finding the best location to store it into the map
  34753. * @param size the dimension of the rectangle to store
  34754. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  34755. */
  34756. RectPackingMap.prototype.addRect = function (size) {
  34757. var node = this.findAndSplitNode(size);
  34758. return node;
  34759. };
  34760. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  34761. /**
  34762. * Return the current space free normalized between [0;1]
  34763. * @returns {}
  34764. */
  34765. get: function () {
  34766. var freeSize = 0;
  34767. freeSize = this.evalFreeSize(freeSize);
  34768. return freeSize / (this._size.width * this._size.height);
  34769. },
  34770. enumerable: true,
  34771. configurable: true
  34772. });
  34773. return RectPackingMap;
  34774. })(PackedRect);
  34775. BABYLON.RectPackingMap = RectPackingMap;
  34776. })(BABYLON || (BABYLON = {}));
  34777. var BABYLON;
  34778. (function (BABYLON) {
  34779. var DynamicFloatArrayElementInfo = (function () {
  34780. function DynamicFloatArrayElementInfo() {
  34781. }
  34782. return DynamicFloatArrayElementInfo;
  34783. })();
  34784. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  34785. /**
  34786. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  34787. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  34788. * It was first built to effiently maintain the WebGlBuffer that contain instancing based data.
  34789. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  34790. * Beware, calling pack() may change the offset of some Entries because this method will defrag the Float32Array to replace empty elements by moving allocated ones at their location.
  34791. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there're no "free holes".
  34792. */
  34793. var DynamicFloatArray = (function () {
  34794. /**
  34795. * Construct an instance of the dynamic float array
  34796. * @param stride size of one element in float (i.e. not bytes!)
  34797. * @param initialElementCount the number of available entries at construction
  34798. */
  34799. function DynamicFloatArray(stride, initialElementCount) {
  34800. this._stride = stride;
  34801. this.buffer = new Float32Array(stride * initialElementCount);
  34802. this._lastUsed = 0;
  34803. this._firstFree = 0;
  34804. this._allEntries = new Array(initialElementCount);
  34805. this._freeEntries = new Array(initialElementCount);
  34806. for (var i = 0; i < initialElementCount; i++) {
  34807. var element = new DynamicFloatArrayElementInfo();
  34808. element.offset = i * stride;
  34809. this._allEntries[i] = element;
  34810. this._freeEntries[initialElementCount - i - 1] = element;
  34811. }
  34812. }
  34813. /**
  34814. * Allocate an element in the array.
  34815. * @return the element info instance that contains the offset into the main buffer of the element's location.
  34816. * Beware, this offset may change when you call pack()
  34817. */
  34818. DynamicFloatArray.prototype.allocElement = function () {
  34819. if (this._freeEntries.length === 0) {
  34820. this._growBuffer();
  34821. }
  34822. var el = this._freeEntries.pop();
  34823. this._lastUsed = Math.max(el.offset, this._lastUsed);
  34824. if (el.offset === this._firstFree) {
  34825. if (this._freeEntries.length > 0) {
  34826. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  34827. }
  34828. else {
  34829. this._firstFree += this._stride;
  34830. }
  34831. }
  34832. return el;
  34833. };
  34834. /**
  34835. * Free the element corresponding to the given element info
  34836. * @param elInfo the element that describe the allocated element
  34837. */
  34838. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  34839. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  34840. this._freeEntries.push(elInfo);
  34841. };
  34842. /**
  34843. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  34844. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  34845. * @return the subarray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  34846. */
  34847. DynamicFloatArray.prototype.pack = function () {
  34848. // no free slot? no need to pack
  34849. if (this._freeEntries.length === 0) {
  34850. return this.buffer;
  34851. }
  34852. // If the buffer is already packed the last used will always be lower than the first free
  34853. if (this._lastUsed < this._firstFree) {
  34854. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  34855. return elementsBuffer_1;
  34856. }
  34857. var s = this._stride;
  34858. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  34859. var lastFree = new DynamicFloatArrayElementInfo();
  34860. lastFree.offset = this.totalElementCount * s;
  34861. this._freeEntries.push(lastFree);
  34862. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  34863. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  34864. var firstFreeSlotOffset = sortedFree[0].offset;
  34865. var freeZoneSize = 1;
  34866. // The sortedFree array is sorted in reverse, first free at the end, last free at the beginning, so we loop from the end to beginning
  34867. var prevOffset = sortedFree[0].offset;
  34868. for (var i = 1; i < sortedFree.length; i++) {
  34869. var curFree = sortedFree[i];
  34870. var curOffset = curFree.offset;
  34871. // Compute the distance between this offset and the previous
  34872. var distance = curOffset - prevOffset;
  34873. // If the distance is the stride size, they are adjacents, it good, move to the next
  34874. if (distance === s) {
  34875. // Free zone is one element bigger
  34876. ++freeZoneSize;
  34877. // as we're about to iterate to the next, the cur becomes the prev...
  34878. prevOffset = curOffset;
  34879. continue;
  34880. }
  34881. // Distance is bigger, which means there's x element between the previous free and this one
  34882. var usedRange = (distance / s) - 1;
  34883. // Two cases the free zone is smaller than the data to move or bigger
  34884. // Copy what can fit in the free zone
  34885. var curMoveOffset = curOffset - s;
  34886. var copyCount = Math.min(freeZoneSize, usedRange);
  34887. for (var j = 0; j < copyCount; j++) {
  34888. var freeI = firstFreeSlotOffset / s;
  34889. var curI = curMoveOffset / s;
  34890. var moveEl = sortedAll[curI];
  34891. this._moveElement(moveEl, firstFreeSlotOffset);
  34892. var replacedEl = sortedAll[freeI];
  34893. // set the offset of the element element we replace with a value that will make it discard at the end of the method
  34894. replacedEl.offset = curMoveOffset;
  34895. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  34896. sortedAll[freeI] = moveEl;
  34897. sortedAll[curI] = replacedEl;
  34898. curMoveOffset -= s;
  34899. firstFreeSlotOffset += s;
  34900. }
  34901. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  34902. if (freeZoneSize <= usedRange) {
  34903. firstFreeSlotOffset = curOffset;
  34904. freeZoneSize = 1;
  34905. }
  34906. else {
  34907. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  34908. }
  34909. // as we're about to iterate to the next, the cur becomes the prev...
  34910. prevOffset = curOffset;
  34911. }
  34912. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  34913. this._lastUsed = firstFreeSlotOffset - s;
  34914. this._firstFree = firstFreeSlotOffset;
  34915. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  34916. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  34917. this._allEntries = sortedAll;
  34918. return elementsBuffer;
  34919. };
  34920. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  34921. for (var i = 0; i < this._stride; i++) {
  34922. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  34923. }
  34924. element.offset = destOffset;
  34925. };
  34926. DynamicFloatArray.prototype._growBuffer = function () {
  34927. // Allocate the new buffer with 50% more entries, copy the content of the current one
  34928. var newElCount = this.totalElementCount * 1.5;
  34929. var newBuffer = new Float32Array(newElCount * this._stride);
  34930. newBuffer.set(this.buffer);
  34931. var addedCount = newElCount - this.totalElementCount;
  34932. this._allEntries.length += addedCount;
  34933. this._freeEntries.length += addedCount;
  34934. for (var i = this.totalElementCount; i < newElCount; i++) {
  34935. var el = new DynamicFloatArrayElementInfo();
  34936. el.offset = i * this._stride;
  34937. this._allEntries[i] = el;
  34938. this._freeEntries[i] = el;
  34939. }
  34940. this.buffer = newBuffer;
  34941. };
  34942. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  34943. /**
  34944. * Get the total count of entries that can fit in the current buffer
  34945. * @returns the elements count
  34946. */
  34947. get: function () {
  34948. return this._allEntries.length;
  34949. },
  34950. enumerable: true,
  34951. configurable: true
  34952. });
  34953. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  34954. /**
  34955. * Get the count of free entries that can still be allocated without resizing the buffer
  34956. * @returns the free elements count
  34957. */
  34958. get: function () {
  34959. return this._freeEntries.length;
  34960. },
  34961. enumerable: true,
  34962. configurable: true
  34963. });
  34964. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  34965. /**
  34966. * Get the count of allocated elements
  34967. * @returns the allocated elements count
  34968. */
  34969. get: function () {
  34970. return this._allEntries.length - this._freeEntries.length;
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  34976. /**
  34977. * Return the size of one element in float
  34978. * @returns the size in float
  34979. */
  34980. get: function () {
  34981. return this._stride;
  34982. },
  34983. enumerable: true,
  34984. configurable: true
  34985. });
  34986. return DynamicFloatArray;
  34987. })();
  34988. BABYLON.DynamicFloatArray = DynamicFloatArray;
  34989. })(BABYLON || (BABYLON = {}));
  34990. var BABYLON;
  34991. (function (BABYLON) {
  34992. var ShaderMaterial = (function (_super) {
  34993. __extends(ShaderMaterial, _super);
  34994. function ShaderMaterial(name, scene, shaderPath, options) {
  34995. _super.call(this, name, scene);
  34996. this._textures = {};
  34997. this._floats = {};
  34998. this._floatsArrays = {};
  34999. this._colors3 = {};
  35000. this._colors4 = {};
  35001. this._vectors2 = {};
  35002. this._vectors3 = {};
  35003. this._vectors4 = {};
  35004. this._matrices = {};
  35005. this._matrices3x3 = {};
  35006. this._matrices2x2 = {};
  35007. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  35008. this._shaderPath = shaderPath;
  35009. options.needAlphaBlending = options.needAlphaBlending || false;
  35010. options.needAlphaTesting = options.needAlphaTesting || false;
  35011. options.attributes = options.attributes || ["position", "normal", "uv"];
  35012. options.uniforms = options.uniforms || ["worldViewProjection"];
  35013. options.samplers = options.samplers || [];
  35014. options.defines = options.defines || [];
  35015. this._options = options;
  35016. }
  35017. ShaderMaterial.prototype.needAlphaBlending = function () {
  35018. return this._options.needAlphaBlending;
  35019. };
  35020. ShaderMaterial.prototype.needAlphaTesting = function () {
  35021. return this._options.needAlphaTesting;
  35022. };
  35023. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  35024. if (this._options.uniforms.indexOf(uniformName) === -1) {
  35025. this._options.uniforms.push(uniformName);
  35026. }
  35027. };
  35028. ShaderMaterial.prototype.setTexture = function (name, texture) {
  35029. if (this._options.samplers.indexOf(name) === -1) {
  35030. this._options.samplers.push(name);
  35031. }
  35032. this._textures[name] = texture;
  35033. return this;
  35034. };
  35035. ShaderMaterial.prototype.setFloat = function (name, value) {
  35036. this._checkUniform(name);
  35037. this._floats[name] = value;
  35038. return this;
  35039. };
  35040. ShaderMaterial.prototype.setFloats = function (name, value) {
  35041. this._checkUniform(name);
  35042. this._floatsArrays[name] = value;
  35043. return this;
  35044. };
  35045. ShaderMaterial.prototype.setColor3 = function (name, value) {
  35046. this._checkUniform(name);
  35047. this._colors3[name] = value;
  35048. return this;
  35049. };
  35050. ShaderMaterial.prototype.setColor4 = function (name, value) {
  35051. this._checkUniform(name);
  35052. this._colors4[name] = value;
  35053. return this;
  35054. };
  35055. ShaderMaterial.prototype.setVector2 = function (name, value) {
  35056. this._checkUniform(name);
  35057. this._vectors2[name] = value;
  35058. return this;
  35059. };
  35060. ShaderMaterial.prototype.setVector3 = function (name, value) {
  35061. this._checkUniform(name);
  35062. this._vectors3[name] = value;
  35063. return this;
  35064. };
  35065. ShaderMaterial.prototype.setVector4 = function (name, value) {
  35066. this._checkUniform(name);
  35067. this._vectors4[name] = value;
  35068. return this;
  35069. };
  35070. ShaderMaterial.prototype.setMatrix = function (name, value) {
  35071. this._checkUniform(name);
  35072. this._matrices[name] = value;
  35073. return this;
  35074. };
  35075. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  35076. this._checkUniform(name);
  35077. this._matrices3x3[name] = value;
  35078. return this;
  35079. };
  35080. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  35081. this._checkUniform(name);
  35082. this._matrices2x2[name] = value;
  35083. return this;
  35084. };
  35085. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  35086. var scene = this.getScene();
  35087. var engine = scene.getEngine();
  35088. if (!this.checkReadyOnEveryCall) {
  35089. if (this._renderId === scene.getRenderId()) {
  35090. return true;
  35091. }
  35092. }
  35093. // Instances
  35094. var defines = [];
  35095. var fallbacks = new BABYLON.EffectFallbacks();
  35096. if (useInstances) {
  35097. defines.push("#define INSTANCES");
  35098. }
  35099. for (var index = 0; index < this._options.defines.length; index++) {
  35100. defines.push(this._options.defines[index]);
  35101. }
  35102. // Bones
  35103. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35104. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35105. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35106. fallbacks.addCPUSkinningFallback(0, mesh);
  35107. }
  35108. // Alpha test
  35109. if (engine.getAlphaTesting()) {
  35110. defines.push("#define ALPHATEST");
  35111. }
  35112. var previousEffect = this._effect;
  35113. var join = defines.join("\n");
  35114. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  35115. if (!this._effect.isReady()) {
  35116. return false;
  35117. }
  35118. if (previousEffect !== this._effect) {
  35119. scene.resetCachedMaterial();
  35120. }
  35121. this._renderId = scene.getRenderId();
  35122. return true;
  35123. };
  35124. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35125. var scene = this.getScene();
  35126. if (this._options.uniforms.indexOf("world") !== -1) {
  35127. this._effect.setMatrix("world", world);
  35128. }
  35129. if (this._options.uniforms.indexOf("worldView") !== -1) {
  35130. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  35131. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  35132. }
  35133. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  35134. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  35135. }
  35136. };
  35137. ShaderMaterial.prototype.bind = function (world, mesh) {
  35138. // Std values
  35139. this.bindOnlyWorldMatrix(world);
  35140. if (this.getScene().getCachedMaterial() !== this) {
  35141. if (this._options.uniforms.indexOf("view") !== -1) {
  35142. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  35143. }
  35144. if (this._options.uniforms.indexOf("projection") !== -1) {
  35145. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  35146. }
  35147. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  35148. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35149. }
  35150. // Bones
  35151. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35152. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35153. }
  35154. // Texture
  35155. for (var name in this._textures) {
  35156. this._effect.setTexture(name, this._textures[name]);
  35157. }
  35158. // Float
  35159. for (name in this._floats) {
  35160. this._effect.setFloat(name, this._floats[name]);
  35161. }
  35162. // Float s
  35163. for (name in this._floatsArrays) {
  35164. this._effect.setArray(name, this._floatsArrays[name]);
  35165. }
  35166. // Color3
  35167. for (name in this._colors3) {
  35168. this._effect.setColor3(name, this._colors3[name]);
  35169. }
  35170. // Color4
  35171. for (name in this._colors4) {
  35172. var color = this._colors4[name];
  35173. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  35174. }
  35175. // Vector2
  35176. for (name in this._vectors2) {
  35177. this._effect.setVector2(name, this._vectors2[name]);
  35178. }
  35179. // Vector3
  35180. for (name in this._vectors3) {
  35181. this._effect.setVector3(name, this._vectors3[name]);
  35182. }
  35183. // Vector4
  35184. for (name in this._vectors4) {
  35185. this._effect.setVector4(name, this._vectors4[name]);
  35186. }
  35187. // Matrix
  35188. for (name in this._matrices) {
  35189. this._effect.setMatrix(name, this._matrices[name]);
  35190. }
  35191. // Matrix 3x3
  35192. for (name in this._matrices3x3) {
  35193. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  35194. }
  35195. // Matrix 2x2
  35196. for (name in this._matrices2x2) {
  35197. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  35198. }
  35199. }
  35200. _super.prototype.bind.call(this, world, mesh);
  35201. };
  35202. ShaderMaterial.prototype.clone = function (name) {
  35203. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  35204. return newShaderMaterial;
  35205. };
  35206. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35207. if (forceDisposeTextures) {
  35208. for (var name in this._textures) {
  35209. this._textures[name].dispose();
  35210. }
  35211. }
  35212. this._textures = {};
  35213. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35214. };
  35215. ShaderMaterial.prototype.serialize = function () {
  35216. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35217. serializationObject.customType = "BABYLON.ShaderMaterial";
  35218. serializationObject.options = this._options;
  35219. serializationObject.shaderPath = this._shaderPath;
  35220. // Texture
  35221. serializationObject.textures = {};
  35222. for (var name in this._textures) {
  35223. serializationObject.textures[name] = this._textures[name].serialize();
  35224. }
  35225. // Float
  35226. serializationObject.floats = {};
  35227. for (name in this._floats) {
  35228. serializationObject.floats[name] = this._floats[name];
  35229. }
  35230. // Float s
  35231. serializationObject.floatArrays = {};
  35232. for (name in this._floatsArrays) {
  35233. serializationObject.floatArrays[name] = this._floatsArrays[name];
  35234. }
  35235. // Color3
  35236. serializationObject.colors3 = {};
  35237. for (name in this._colors3) {
  35238. serializationObject.colors3[name] = this._colors3[name].asArray();
  35239. }
  35240. // Color4
  35241. serializationObject.colors4 = {};
  35242. for (name in this._colors4) {
  35243. serializationObject.colors4[name] = this._colors4[name].asArray();
  35244. }
  35245. // Vector2
  35246. serializationObject.vectors2 = {};
  35247. for (name in this._vectors2) {
  35248. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  35249. }
  35250. // Vector3
  35251. serializationObject.vectors3 = {};
  35252. for (name in this._vectors3) {
  35253. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  35254. }
  35255. // Vector4
  35256. serializationObject.vectors4 = {};
  35257. for (name in this._vectors4) {
  35258. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  35259. }
  35260. // Matrix
  35261. serializationObject.matrices = {};
  35262. for (name in this._matrices) {
  35263. serializationObject.matrices[name] = this._matrices[name].asArray();
  35264. }
  35265. // Matrix 3x3
  35266. serializationObject.matrices3x3 = {};
  35267. for (name in this._matrices3x3) {
  35268. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  35269. }
  35270. // Matrix 2x2
  35271. serializationObject.matrices2x2 = {};
  35272. for (name in this._matrices2x2) {
  35273. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  35274. }
  35275. return serializationObject;
  35276. };
  35277. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  35278. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  35279. // Texture
  35280. for (var name in source.textures) {
  35281. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  35282. }
  35283. // Float
  35284. for (name in source.floats) {
  35285. material.setFloat(name, source.floats[name]);
  35286. }
  35287. // Float s
  35288. for (name in source.floatsArrays) {
  35289. material.setFloats(name, source.floatsArrays[name]);
  35290. }
  35291. // Color3
  35292. for (name in source.colors3) {
  35293. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  35294. }
  35295. // Color4
  35296. for (name in source.colors4) {
  35297. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  35298. }
  35299. // Vector2
  35300. for (name in source.vectors2) {
  35301. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  35302. }
  35303. // Vector3
  35304. for (name in source.vectors3) {
  35305. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  35306. }
  35307. // Vector4
  35308. for (name in source.vectors4) {
  35309. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  35310. }
  35311. // Matrix
  35312. for (name in source.matrices) {
  35313. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  35314. }
  35315. // Matrix 3x3
  35316. for (name in source.matrices3x3) {
  35317. material.setMatrix3x3(name, source.matrices3x3[name]);
  35318. }
  35319. // Matrix 2x2
  35320. for (name in source.matrices2x2) {
  35321. material.setMatrix2x2(name, source.matrices2x2[name]);
  35322. }
  35323. return material;
  35324. };
  35325. return ShaderMaterial;
  35326. })(BABYLON.Material);
  35327. BABYLON.ShaderMaterial = ShaderMaterial;
  35328. })(BABYLON || (BABYLON = {}));
  35329. var BABYLON;
  35330. (function (BABYLON) {
  35331. var Internals;
  35332. (function (Internals) {
  35333. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  35334. // All values and structures referenced from:
  35335. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  35336. var DDS_MAGIC = 0x20534444;
  35337. 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;
  35338. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  35339. 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;
  35340. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  35341. function FourCCToInt32(value) {
  35342. return value.charCodeAt(0) +
  35343. (value.charCodeAt(1) << 8) +
  35344. (value.charCodeAt(2) << 16) +
  35345. (value.charCodeAt(3) << 24);
  35346. }
  35347. function Int32ToFourCC(value) {
  35348. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  35349. }
  35350. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  35351. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  35352. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  35353. var headerLengthInt = 31; // The header length in 32 bit ints
  35354. // Offsets into the header array
  35355. var off_magic = 0;
  35356. var off_size = 1;
  35357. var off_flags = 2;
  35358. var off_height = 3;
  35359. var off_width = 4;
  35360. var off_mipmapCount = 7;
  35361. var off_pfFlags = 20;
  35362. var off_pfFourCC = 21;
  35363. var off_RGBbpp = 22;
  35364. var off_RMask = 23;
  35365. var off_GMask = 24;
  35366. var off_BMask = 25;
  35367. var off_AMask = 26;
  35368. var off_caps1 = 27;
  35369. var off_caps2 = 28;
  35370. ;
  35371. var DDSTools = (function () {
  35372. function DDSTools() {
  35373. }
  35374. DDSTools.GetDDSInfo = function (arrayBuffer) {
  35375. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  35376. var mipmapCount = 1;
  35377. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  35378. mipmapCount = Math.max(1, header[off_mipmapCount]);
  35379. }
  35380. return {
  35381. width: header[off_width],
  35382. height: header[off_height],
  35383. mipmapCount: mipmapCount,
  35384. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  35385. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  35386. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  35387. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  35388. };
  35389. };
  35390. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  35391. var byteArray = new Uint8Array(dataLength);
  35392. var srcData = new Uint8Array(arrayBuffer);
  35393. var index = 0;
  35394. for (var y = height - 1; y >= 0; y--) {
  35395. for (var x = 0; x < width; x++) {
  35396. var srcPos = dataOffset + (x + y * width) * 4;
  35397. byteArray[index + 2] = srcData[srcPos];
  35398. byteArray[index + 1] = srcData[srcPos + 1];
  35399. byteArray[index] = srcData[srcPos + 2];
  35400. byteArray[index + 3] = srcData[srcPos + 3];
  35401. index += 4;
  35402. }
  35403. }
  35404. return byteArray;
  35405. };
  35406. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  35407. var byteArray = new Uint8Array(dataLength);
  35408. var srcData = new Uint8Array(arrayBuffer);
  35409. var index = 0;
  35410. for (var y = height - 1; y >= 0; y--) {
  35411. for (var x = 0; x < width; x++) {
  35412. var srcPos = dataOffset + (x + y * width) * 3;
  35413. byteArray[index + 2] = srcData[srcPos];
  35414. byteArray[index + 1] = srcData[srcPos + 1];
  35415. byteArray[index] = srcData[srcPos + 2];
  35416. index += 3;
  35417. }
  35418. }
  35419. return byteArray;
  35420. };
  35421. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  35422. var byteArray = new Uint8Array(dataLength);
  35423. var srcData = new Uint8Array(arrayBuffer);
  35424. var index = 0;
  35425. for (var y = height - 1; y >= 0; y--) {
  35426. for (var x = 0; x < width; x++) {
  35427. var srcPos = dataOffset + (x + y * width);
  35428. byteArray[index] = srcData[srcPos];
  35429. index++;
  35430. }
  35431. }
  35432. return byteArray;
  35433. };
  35434. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  35435. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  35436. if (header[off_magic] != DDS_MAGIC) {
  35437. BABYLON.Tools.Error("Invalid magic number in DDS header");
  35438. return;
  35439. }
  35440. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  35441. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  35442. return;
  35443. }
  35444. if (info.isFourCC) {
  35445. fourCC = header[off_pfFourCC];
  35446. switch (fourCC) {
  35447. case FOURCC_DXT1:
  35448. blockBytes = 8;
  35449. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  35450. break;
  35451. case FOURCC_DXT3:
  35452. blockBytes = 16;
  35453. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  35454. break;
  35455. case FOURCC_DXT5:
  35456. blockBytes = 16;
  35457. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  35458. break;
  35459. default:
  35460. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  35461. return;
  35462. }
  35463. }
  35464. mipmapCount = 1;
  35465. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  35466. mipmapCount = Math.max(1, header[off_mipmapCount]);
  35467. }
  35468. var bpp = header[off_RGBbpp];
  35469. for (var face = 0; face < faces; face++) {
  35470. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  35471. width = header[off_width];
  35472. height = header[off_height];
  35473. dataOffset = header[off_size] + 4;
  35474. for (i = 0; i < mipmapCount; ++i) {
  35475. if (info.isRGB) {
  35476. if (bpp === 24) {
  35477. dataLength = width * height * 3;
  35478. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  35479. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  35480. }
  35481. else {
  35482. dataLength = width * height * 4;
  35483. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  35484. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  35485. }
  35486. }
  35487. else if (info.isLuminance) {
  35488. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  35489. var unpaddedRowSize = width;
  35490. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  35491. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  35492. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  35493. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  35494. }
  35495. else {
  35496. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  35497. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  35498. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  35499. }
  35500. dataOffset += dataLength;
  35501. width *= 0.5;
  35502. height *= 0.5;
  35503. width = Math.max(1.0, width);
  35504. height = Math.max(1.0, height);
  35505. }
  35506. }
  35507. };
  35508. return DDSTools;
  35509. })();
  35510. Internals.DDSTools = DDSTools;
  35511. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35512. })(BABYLON || (BABYLON = {}));
  35513. var BABYLON;
  35514. (function (BABYLON) {
  35515. var CannonJSPlugin = (function () {
  35516. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  35517. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  35518. if (iterations === void 0) { iterations = 10; }
  35519. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  35520. this.name = "CannonJSPlugin";
  35521. this._physicsMaterials = [];
  35522. this._fixedTimeStep = 1 / 60;
  35523. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  35524. this._currentCollisionGroup = 2;
  35525. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  35526. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  35527. this._tmpPosition = BABYLON.Vector3.Zero();
  35528. this._tmpQuaternion = new BABYLON.Quaternion();
  35529. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  35530. this._tmpDeltaRotation = new BABYLON.Quaternion();
  35531. this._tmpUnityRotation = new BABYLON.Quaternion();
  35532. if (!this.isSupported()) {
  35533. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  35534. return;
  35535. }
  35536. this.world = new CANNON.World();
  35537. this.world.broadphase = new CANNON.NaiveBroadphase();
  35538. this.world.solver.iterations = iterations;
  35539. }
  35540. CannonJSPlugin.prototype.setGravity = function (gravity) {
  35541. this.world.gravity.copy(gravity);
  35542. };
  35543. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  35544. this._fixedTimeStep = timeStep;
  35545. };
  35546. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  35547. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  35548. };
  35549. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35550. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  35551. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  35552. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  35553. };
  35554. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35555. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  35556. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  35557. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  35558. };
  35559. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35560. //parent-child relationship. Does this impostor has a parent impostor?
  35561. if (impostor.parent) {
  35562. if (impostor.physicsBody) {
  35563. this.removePhysicsBody(impostor);
  35564. //TODO is that needed?
  35565. impostor.forceUpdate();
  35566. }
  35567. return;
  35568. }
  35569. //should a new body be created for this impostor?
  35570. if (impostor.isBodyInitRequired()) {
  35571. var shape = this._createShape(impostor);
  35572. //unregister events, if body is being changed
  35573. var oldBody = impostor.physicsBody;
  35574. if (oldBody) {
  35575. this.removePhysicsBody(impostor);
  35576. }
  35577. //create the body and material
  35578. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  35579. var bodyCreationObject = {
  35580. mass: impostor.getParam("mass"),
  35581. material: material
  35582. };
  35583. // A simple extend, in case native options were used.
  35584. var nativeOptions = impostor.getParam("nativeOptions");
  35585. for (var key in nativeOptions) {
  35586. if (nativeOptions.hasOwnProperty(key)) {
  35587. bodyCreationObject[key] = nativeOptions[key];
  35588. }
  35589. }
  35590. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  35591. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  35592. this.world.addEventListener("preStep", impostor.beforeStep);
  35593. this.world.addEventListener("postStep", impostor.afterStep);
  35594. impostor.physicsBody.addShape(shape);
  35595. this.world.add(impostor.physicsBody);
  35596. //try to keep the body moving in the right direction by taking old properties.
  35597. //Should be tested!
  35598. if (oldBody) {
  35599. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  35600. impostor.physicsBody[param].copy(oldBody[param]);
  35601. });
  35602. }
  35603. this._processChildMeshes(impostor);
  35604. }
  35605. //now update the body's transformation
  35606. this._updatePhysicsBodyTransformation(impostor);
  35607. };
  35608. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  35609. var _this = this;
  35610. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  35611. if (meshChildren.length) {
  35612. var processMesh = function (localPosition, mesh) {
  35613. var childImpostor = mesh.getPhysicsImpostor();
  35614. if (childImpostor) {
  35615. var parent = childImpostor.parent;
  35616. if (parent !== mainImpostor) {
  35617. var localPosition = mesh.position;
  35618. if (childImpostor.physicsBody) {
  35619. _this.removePhysicsBody(childImpostor);
  35620. childImpostor.physicsBody = null;
  35621. }
  35622. childImpostor.parent = mainImpostor;
  35623. childImpostor.resetUpdateFlags();
  35624. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  35625. //Add the mass of the children.
  35626. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  35627. }
  35628. }
  35629. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  35630. };
  35631. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  35632. }
  35633. };
  35634. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35635. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  35636. this.world.removeEventListener("preStep", impostor.beforeStep);
  35637. this.world.removeEventListener("postStep", impostor.afterStep);
  35638. this.world.remove(impostor.physicsBody);
  35639. };
  35640. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35641. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35642. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35643. if (!mainBody || !connectedBody) {
  35644. return;
  35645. }
  35646. var constraint;
  35647. var jointData = impostorJoint.joint.jointData;
  35648. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  35649. var constraintData = {
  35650. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  35651. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  35652. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  35653. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  35654. maxForce: jointData.nativeParams.maxForce,
  35655. collideConnected: !!jointData.collision
  35656. };
  35657. //Not needed, Cannon has a collideConnected flag
  35658. /*if (!jointData.collision) {
  35659. //add 1st body to a collision group of its own, if it is not in 1
  35660. if (mainBody.collisionFilterGroup === 1) {
  35661. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  35662. this._currentCollisionGroup <<= 1;
  35663. }
  35664. if (connectedBody.collisionFilterGroup === 1) {
  35665. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  35666. this._currentCollisionGroup <<= 1;
  35667. }
  35668. //add their mask to the collisionFilterMask of each other:
  35669. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  35670. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  35671. }*/
  35672. switch (impostorJoint.joint.type) {
  35673. case BABYLON.PhysicsJoint.HingeJoint:
  35674. case BABYLON.PhysicsJoint.Hinge2Joint:
  35675. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  35676. break;
  35677. case BABYLON.PhysicsJoint.DistanceJoint:
  35678. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  35679. break;
  35680. case BABYLON.PhysicsJoint.SpringJoint:
  35681. var springData = jointData;
  35682. constraint = new CANNON.Spring(mainBody, connectedBody, {
  35683. restLength: springData.length,
  35684. stiffness: springData.stiffness,
  35685. damping: springData.damping,
  35686. localAnchorA: constraintData.pivotA,
  35687. localAnchorB: constraintData.pivotB
  35688. });
  35689. break;
  35690. case BABYLON.PhysicsJoint.PointToPointJoint:
  35691. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35692. default:
  35693. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  35694. break;
  35695. }
  35696. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  35697. constraint.collideConnected = !!jointData.collision;
  35698. impostorJoint.joint.physicsJoint = constraint;
  35699. //don't add spring as constraint, as it is not one.
  35700. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  35701. this.world.addConstraint(constraint);
  35702. }
  35703. else {
  35704. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  35705. constraint.applyForce();
  35706. });
  35707. }
  35708. };
  35709. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  35710. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  35711. };
  35712. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  35713. var index;
  35714. var mat;
  35715. for (index = 0; index < this._physicsMaterials.length; index++) {
  35716. mat = this._physicsMaterials[index];
  35717. if (mat.friction === friction && mat.restitution === restitution) {
  35718. return mat;
  35719. }
  35720. }
  35721. var currentMat = new CANNON.Material(name);
  35722. currentMat.friction = friction;
  35723. currentMat.restitution = restitution;
  35724. this._physicsMaterials.push(currentMat);
  35725. return currentMat;
  35726. };
  35727. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  35728. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  35729. };
  35730. CannonJSPlugin.prototype._createShape = function (impostor) {
  35731. var object = impostor.object;
  35732. var returnValue;
  35733. var extendSize = impostor.getObjectExtendSize();
  35734. switch (impostor.type) {
  35735. case BABYLON.PhysicsEngine.SphereImpostor:
  35736. var radiusX = extendSize.x;
  35737. var radiusY = extendSize.y;
  35738. var radiusZ = extendSize.z;
  35739. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  35740. break;
  35741. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  35742. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35743. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  35744. break;
  35745. case BABYLON.PhysicsImpostor.BoxImpostor:
  35746. var box = extendSize.scale(0.5);
  35747. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  35748. break;
  35749. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35750. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  35751. returnValue = new CANNON.Plane();
  35752. break;
  35753. case BABYLON.PhysicsImpostor.MeshImpostor:
  35754. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  35755. var rawFaces = object.getIndices ? object.getIndices() : [];
  35756. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  35757. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  35758. break;
  35759. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  35760. returnValue = this._createHeightmap(object);
  35761. break;
  35762. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35763. returnValue = new CANNON.Particle();
  35764. break;
  35765. }
  35766. return returnValue;
  35767. };
  35768. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  35769. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35770. var matrix = [];
  35771. //For now pointDepth will not be used and will be automatically calculated.
  35772. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  35773. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  35774. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  35775. var elementSize = dim * 2 / arraySize;
  35776. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  35777. for (var i = 0; i < pos.length; i = i + 3) {
  35778. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  35779. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  35780. var y = pos[i + 1] + minY;
  35781. if (!matrix[x]) {
  35782. matrix[x] = [];
  35783. }
  35784. if (!matrix[x][z]) {
  35785. matrix[x][z] = y;
  35786. }
  35787. matrix[x][z] = Math.max(y, matrix[x][z]);
  35788. }
  35789. for (var x = 0; x <= arraySize; ++x) {
  35790. if (!matrix[x]) {
  35791. var loc = 1;
  35792. while (!matrix[(x + loc) % arraySize]) {
  35793. loc++;
  35794. }
  35795. matrix[x] = matrix[(x + loc) % arraySize].slice();
  35796. }
  35797. for (var z = 0; z <= arraySize; ++z) {
  35798. if (!matrix[x][z]) {
  35799. var loc = 1;
  35800. var newValue;
  35801. while (newValue === undefined) {
  35802. newValue = matrix[x][(z + loc++) % arraySize];
  35803. }
  35804. matrix[x][z] = newValue;
  35805. }
  35806. }
  35807. }
  35808. var shape = new CANNON.Heightfield(matrix, {
  35809. elementSize: elementSize
  35810. });
  35811. //For future reference, needed for body transformation
  35812. shape.minY = minY;
  35813. return shape;
  35814. };
  35815. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  35816. var object = impostor.object;
  35817. //make sure it is updated...
  35818. object.computeWorldMatrix && object.computeWorldMatrix(true);
  35819. // The delta between the mesh position and the mesh bounding box center
  35820. var center = impostor.getObjectCenter();
  35821. var extendSize = impostor.getObjectExtendSize();
  35822. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  35823. this._tmpPosition.copyFrom(center);
  35824. var quaternion = object.rotationQuaternion;
  35825. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  35826. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  35827. //-90 DEG in X, precalculated
  35828. quaternion = quaternion.multiply(this._minus90X);
  35829. //Invert! (Precalculated, 90 deg in X)
  35830. //No need to clone. this will never change.
  35831. impostor.setDeltaRotation(this._plus90X);
  35832. }
  35833. //If it is a heightfield, if should be centered.
  35834. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  35835. var mesh = object;
  35836. //calculate the correct body position:
  35837. var rotationQuaternion = mesh.rotationQuaternion;
  35838. mesh.rotationQuaternion = this._tmpUnityRotation;
  35839. mesh.computeWorldMatrix(true);
  35840. //get original center with no rotation
  35841. var c = center.clone();
  35842. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  35843. //rotation is back
  35844. mesh.rotationQuaternion = rotationQuaternion;
  35845. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  35846. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  35847. mesh.setPivotMatrix(p);
  35848. mesh.computeWorldMatrix(true);
  35849. //calculate the translation
  35850. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  35851. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  35852. //add it inverted to the delta
  35853. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  35854. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  35855. mesh.setPivotMatrix(oldPivot);
  35856. mesh.computeWorldMatrix(true);
  35857. }
  35858. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  35859. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  35860. this._tmpPosition.copyFrom(object.position);
  35861. }
  35862. impostor.setDeltaPosition(this._tmpDeltaPosition);
  35863. //Now update the impostor object
  35864. impostor.physicsBody.position.copy(this._tmpPosition);
  35865. impostor.physicsBody.quaternion.copy(quaternion);
  35866. };
  35867. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35868. impostor.object.position.copyFrom(impostor.physicsBody.position);
  35869. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  35870. };
  35871. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35872. impostor.physicsBody.position.copy(newPosition);
  35873. impostor.physicsBody.quaternion.copy(newRotation);
  35874. };
  35875. CannonJSPlugin.prototype.isSupported = function () {
  35876. return window.CANNON !== undefined;
  35877. };
  35878. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35879. impostor.physicsBody.velocity.copy(velocity);
  35880. };
  35881. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35882. impostor.physicsBody.angularVelocity.copy(velocity);
  35883. };
  35884. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35885. var v = impostor.physicsBody.velocity;
  35886. if (!v)
  35887. return null;
  35888. return new BABYLON.Vector3(v.x, v.y, v.z);
  35889. };
  35890. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35891. var v = impostor.physicsBody.angularVelocity;
  35892. if (!v)
  35893. return null;
  35894. return new BABYLON.Vector3(v.x, v.y, v.z);
  35895. };
  35896. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35897. impostor.physicsBody.mass = mass;
  35898. impostor.physicsBody.updateMassProperties();
  35899. };
  35900. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  35901. impostor.physicsBody.sleep();
  35902. };
  35903. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  35904. impostor.physicsBody.wakeUp();
  35905. };
  35906. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35907. joint.physicsJoint.distance = maxDistance;
  35908. };
  35909. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  35910. if (!motorIndex) {
  35911. joint.physicsJoint.enableMotor();
  35912. }
  35913. };
  35914. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  35915. if (!motorIndex) {
  35916. joint.physicsJoint.disableMotor();
  35917. }
  35918. };
  35919. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35920. if (!motorIndex) {
  35921. joint.physicsJoint.enableMotor();
  35922. joint.physicsJoint.setMotorSpeed(speed);
  35923. if (maxForce) {
  35924. this.setLimit(joint, maxForce);
  35925. }
  35926. }
  35927. };
  35928. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  35929. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  35930. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  35931. };
  35932. CannonJSPlugin.prototype.dispose = function () {
  35933. //nothing to do, actually.
  35934. };
  35935. return CannonJSPlugin;
  35936. })();
  35937. BABYLON.CannonJSPlugin = CannonJSPlugin;
  35938. })(BABYLON || (BABYLON = {}));
  35939. var BABYLON;
  35940. (function (BABYLON) {
  35941. var OimoJSPlugin = (function () {
  35942. function OimoJSPlugin(iterations) {
  35943. this.name = "OimoJSPlugin";
  35944. this._tmpImpostorsArray = [];
  35945. this._tmpPositionVector = BABYLON.Vector3.Zero();
  35946. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  35947. this.world.clear();
  35948. //making sure no stats are calculated
  35949. this.world.isNoStat = true;
  35950. }
  35951. OimoJSPlugin.prototype.setGravity = function (gravity) {
  35952. this.world.gravity.copy(gravity);
  35953. };
  35954. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  35955. this.world.timeStep = timeStep;
  35956. };
  35957. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  35958. var _this = this;
  35959. impostors.forEach(function (impostor) {
  35960. impostor.beforeStep();
  35961. });
  35962. this.world.step();
  35963. impostors.forEach(function (impostor) {
  35964. impostor.afterStep();
  35965. //update the ordered impostors array
  35966. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  35967. });
  35968. //check for collisions
  35969. var contact = this.world.contacts;
  35970. while (contact !== null) {
  35971. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  35972. contact = contact.next;
  35973. continue;
  35974. }
  35975. //is this body colliding with any other? get the impostor
  35976. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  35977. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  35978. if (!mainImpostor || !collidingImpostor) {
  35979. contact = contact.next;
  35980. continue;
  35981. }
  35982. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  35983. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  35984. contact = contact.next;
  35985. }
  35986. };
  35987. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35988. var mass = impostor.physicsBody.massInfo.mass;
  35989. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  35990. };
  35991. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35992. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  35993. this.applyImpulse(impostor, force, contactPoint);
  35994. };
  35995. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35996. var _this = this;
  35997. //parent-child relationship. Does this impostor has a parent impostor?
  35998. if (impostor.parent) {
  35999. if (impostor.physicsBody) {
  36000. this.removePhysicsBody(impostor);
  36001. //TODO is that needed?
  36002. impostor.forceUpdate();
  36003. }
  36004. return;
  36005. }
  36006. if (impostor.isBodyInitRequired()) {
  36007. var bodyConfig = {
  36008. name: impostor.uniqueId,
  36009. //Oimo must have mass, also for static objects.
  36010. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  36011. size: [],
  36012. type: [],
  36013. pos: [],
  36014. rot: [],
  36015. move: impostor.getParam("mass") !== 0,
  36016. //Supporting older versions of Oimo
  36017. world: this.world
  36018. };
  36019. var impostors = [impostor];
  36020. function addToArray(parent) {
  36021. if (!parent.getChildMeshes)
  36022. return;
  36023. parent.getChildMeshes().forEach(function (m) {
  36024. if (m.physicsImpostor) {
  36025. impostors.push(m.physicsImpostor);
  36026. m.physicsImpostor._init();
  36027. }
  36028. });
  36029. }
  36030. addToArray(impostor.object);
  36031. function checkWithEpsilon(value) {
  36032. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  36033. }
  36034. impostors.forEach(function (i) {
  36035. //get the correct bounding box
  36036. var oldQuaternion = i.object.rotationQuaternion;
  36037. var rot = new OIMO.Euler().setFromQuaternion({
  36038. x: impostor.object.rotationQuaternion.x,
  36039. y: impostor.object.rotationQuaternion.y,
  36040. z: impostor.object.rotationQuaternion.z,
  36041. s: impostor.object.rotationQuaternion.w
  36042. });
  36043. var extendSize = i.getObjectExtendSize();
  36044. if (i === impostor) {
  36045. var center = impostor.getObjectCenter();
  36046. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  36047. //Can also use Array.prototype.push.apply
  36048. bodyConfig.pos.push(center.x);
  36049. bodyConfig.pos.push(center.y);
  36050. bodyConfig.pos.push(center.z);
  36051. //tmp solution
  36052. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  36053. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  36054. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  36055. }
  36056. else {
  36057. bodyConfig.pos.push(i.object.position.x);
  36058. bodyConfig.pos.push(i.object.position.y);
  36059. bodyConfig.pos.push(i.object.position.z);
  36060. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  36061. bodyConfig.rot.push(0);
  36062. bodyConfig.rot.push(0);
  36063. bodyConfig.rot.push(0);
  36064. }
  36065. // register mesh
  36066. switch (i.type) {
  36067. case BABYLON.PhysicsImpostor.ParticleImpostor:
  36068. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  36069. case BABYLON.PhysicsImpostor.SphereImpostor:
  36070. var radiusX = extendSize.x;
  36071. var radiusY = extendSize.y;
  36072. var radiusZ = extendSize.z;
  36073. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  36074. bodyConfig.type.push('sphere');
  36075. //due to the way oimo works with compounds, add 3 times
  36076. bodyConfig.size.push(size);
  36077. bodyConfig.size.push(size);
  36078. bodyConfig.size.push(size);
  36079. break;
  36080. case BABYLON.PhysicsImpostor.CylinderImpostor:
  36081. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  36082. var sizeY = checkWithEpsilon(extendSize.y);
  36083. bodyConfig.type.push('cylinder');
  36084. bodyConfig.size.push(sizeX);
  36085. bodyConfig.size.push(sizeY);
  36086. //due to the way oimo works with compounds, add one more value.
  36087. bodyConfig.size.push(sizeY);
  36088. break;
  36089. case BABYLON.PhysicsImpostor.PlaneImpostor:
  36090. case BABYLON.PhysicsImpostor.BoxImpostor:
  36091. default:
  36092. var sizeX = checkWithEpsilon(extendSize.x);
  36093. var sizeY = checkWithEpsilon(extendSize.y);
  36094. var sizeZ = checkWithEpsilon(extendSize.z);
  36095. bodyConfig.type.push('box');
  36096. bodyConfig.size.push(sizeX);
  36097. bodyConfig.size.push(sizeY);
  36098. bodyConfig.size.push(sizeZ);
  36099. break;
  36100. }
  36101. //actually not needed, but hey...
  36102. i.object.rotationQuaternion = oldQuaternion;
  36103. });
  36104. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  36105. }
  36106. else {
  36107. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  36108. }
  36109. impostor.setDeltaPosition(this._tmpPositionVector);
  36110. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  36111. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  36112. };
  36113. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  36114. //impostor.physicsBody.dispose();
  36115. //Same as : (older oimo versions)
  36116. this.world.removeRigidBody(impostor.physicsBody);
  36117. };
  36118. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  36119. var mainBody = impostorJoint.mainImpostor.physicsBody;
  36120. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  36121. if (!mainBody || !connectedBody) {
  36122. return;
  36123. }
  36124. var jointData = impostorJoint.joint.jointData;
  36125. var options = jointData.nativeParams || {};
  36126. var type;
  36127. var nativeJointData = {
  36128. body1: mainBody,
  36129. body2: connectedBody,
  36130. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  36131. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  36132. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  36133. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  36134. min: options.min,
  36135. max: options.max,
  36136. collision: options.collision || jointData.collision,
  36137. spring: options.spring,
  36138. //supporting older version of Oimo
  36139. world: this.world
  36140. };
  36141. switch (impostorJoint.joint.type) {
  36142. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  36143. type = "jointBall";
  36144. break;
  36145. case BABYLON.PhysicsJoint.SpringJoint:
  36146. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  36147. var springData = jointData;
  36148. nativeJointData.min = springData.length || nativeJointData.min;
  36149. //Max should also be set, just make sure it is at least min
  36150. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  36151. case BABYLON.PhysicsJoint.DistanceJoint:
  36152. type = "jointDistance";
  36153. nativeJointData.max = jointData.maxDistance;
  36154. break;
  36155. case BABYLON.PhysicsJoint.PrismaticJoint:
  36156. type = "jointPrisme";
  36157. break;
  36158. case BABYLON.PhysicsJoint.SliderJoint:
  36159. type = "jointSlide";
  36160. break;
  36161. case BABYLON.PhysicsJoint.WheelJoint:
  36162. type = "jointWheel";
  36163. break;
  36164. case BABYLON.PhysicsJoint.HingeJoint:
  36165. default:
  36166. type = "jointHinge";
  36167. break;
  36168. }
  36169. nativeJointData.type = type;
  36170. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  36171. };
  36172. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  36173. //Bug in Oimo prevents us from disposing a joint in the playground
  36174. //joint.joint.physicsJoint.dispose();
  36175. //So we will bruteforce it!
  36176. try {
  36177. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  36178. }
  36179. catch (e) {
  36180. BABYLON.Tools.Warn(e);
  36181. }
  36182. };
  36183. OimoJSPlugin.prototype.isSupported = function () {
  36184. return OIMO !== undefined;
  36185. };
  36186. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  36187. if (!impostor.physicsBody.sleeping) {
  36188. //TODO check that
  36189. if (impostor.physicsBody.shapes.next) {
  36190. var parentShape = this._getLastShape(impostor.physicsBody);
  36191. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  36192. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  36193. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  36194. }
  36195. else {
  36196. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  36197. }
  36198. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  36199. }
  36200. };
  36201. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  36202. var body = impostor.physicsBody;
  36203. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  36204. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  36205. body.syncShapes();
  36206. body.awake();
  36207. };
  36208. OimoJSPlugin.prototype._getLastShape = function (body) {
  36209. var lastShape = body.shapes;
  36210. while (lastShape.next) {
  36211. lastShape = lastShape.next;
  36212. }
  36213. return lastShape;
  36214. };
  36215. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  36216. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  36217. };
  36218. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  36219. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  36220. };
  36221. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  36222. var v = impostor.physicsBody.linearVelocity;
  36223. if (!v)
  36224. return null;
  36225. return new BABYLON.Vector3(v.x, v.y, v.z);
  36226. };
  36227. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  36228. var v = impostor.physicsBody.angularVelocity;
  36229. if (!v)
  36230. return null;
  36231. return new BABYLON.Vector3(v.x, v.y, v.z);
  36232. };
  36233. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  36234. var staticBody = mass === 0;
  36235. //this will actually set the body's density and not its mass.
  36236. //But this is how oimo treats the mass variable.
  36237. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  36238. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  36239. };
  36240. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  36241. impostor.physicsBody.sleep();
  36242. };
  36243. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  36244. impostor.physicsBody.awake();
  36245. };
  36246. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  36247. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  36248. if (minDistance !== void 0) {
  36249. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  36250. }
  36251. };
  36252. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  36253. //TODO separate rotational and transational motors.
  36254. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  36255. if (motor) {
  36256. motor.setMotor(speed, maxForce);
  36257. }
  36258. };
  36259. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  36260. //TODO separate rotational and transational motors.
  36261. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  36262. if (motor) {
  36263. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  36264. }
  36265. };
  36266. OimoJSPlugin.prototype.dispose = function () {
  36267. this.world.clear();
  36268. };
  36269. return OimoJSPlugin;
  36270. })();
  36271. BABYLON.OimoJSPlugin = OimoJSPlugin;
  36272. })(BABYLON || (BABYLON = {}));
  36273. var BABYLON;
  36274. (function (BABYLON) {
  36275. var DisplayPassPostProcess = (function (_super) {
  36276. __extends(DisplayPassPostProcess, _super);
  36277. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  36278. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  36279. }
  36280. return DisplayPassPostProcess;
  36281. })(BABYLON.PostProcess);
  36282. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  36283. })(BABYLON || (BABYLON = {}));
  36284. var BABYLON;
  36285. (function (BABYLON) {
  36286. var SimplificationSettings = (function () {
  36287. function SimplificationSettings(quality, distance, optimizeMesh) {
  36288. this.quality = quality;
  36289. this.distance = distance;
  36290. this.optimizeMesh = optimizeMesh;
  36291. }
  36292. return SimplificationSettings;
  36293. })();
  36294. BABYLON.SimplificationSettings = SimplificationSettings;
  36295. var SimplificationQueue = (function () {
  36296. function SimplificationQueue() {
  36297. this.running = false;
  36298. this._simplificationArray = [];
  36299. }
  36300. SimplificationQueue.prototype.addTask = function (task) {
  36301. this._simplificationArray.push(task);
  36302. };
  36303. SimplificationQueue.prototype.executeNext = function () {
  36304. var task = this._simplificationArray.pop();
  36305. if (task) {
  36306. this.running = true;
  36307. this.runSimplification(task);
  36308. }
  36309. else {
  36310. this.running = false;
  36311. }
  36312. };
  36313. SimplificationQueue.prototype.runSimplification = function (task) {
  36314. var _this = this;
  36315. if (task.parallelProcessing) {
  36316. //parallel simplifier
  36317. task.settings.forEach(function (setting) {
  36318. var simplifier = _this.getSimplifier(task);
  36319. simplifier.simplify(setting, function (newMesh) {
  36320. task.mesh.addLODLevel(setting.distance, newMesh);
  36321. newMesh.isVisible = true;
  36322. //check if it is the last
  36323. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  36324. //all done, run the success callback.
  36325. task.successCallback();
  36326. }
  36327. _this.executeNext();
  36328. });
  36329. });
  36330. }
  36331. else {
  36332. //single simplifier.
  36333. var simplifier = this.getSimplifier(task);
  36334. var runDecimation = function (setting, callback) {
  36335. simplifier.simplify(setting, function (newMesh) {
  36336. task.mesh.addLODLevel(setting.distance, newMesh);
  36337. newMesh.isVisible = true;
  36338. //run the next quality level
  36339. callback();
  36340. });
  36341. };
  36342. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  36343. runDecimation(task.settings[loop.index], function () {
  36344. loop.executeNext();
  36345. });
  36346. }, function () {
  36347. //execution ended, run the success callback.
  36348. if (task.successCallback) {
  36349. task.successCallback();
  36350. }
  36351. _this.executeNext();
  36352. });
  36353. }
  36354. };
  36355. SimplificationQueue.prototype.getSimplifier = function (task) {
  36356. switch (task.simplificationType) {
  36357. case SimplificationType.QUADRATIC:
  36358. default:
  36359. return new QuadraticErrorSimplification(task.mesh);
  36360. }
  36361. };
  36362. return SimplificationQueue;
  36363. })();
  36364. BABYLON.SimplificationQueue = SimplificationQueue;
  36365. /**
  36366. * The implemented types of simplification.
  36367. * At the moment only Quadratic Error Decimation is implemented.
  36368. */
  36369. (function (SimplificationType) {
  36370. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  36371. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  36372. var SimplificationType = BABYLON.SimplificationType;
  36373. var DecimationTriangle = (function () {
  36374. function DecimationTriangle(vertices) {
  36375. this.vertices = vertices;
  36376. this.error = new Array(4);
  36377. this.deleted = false;
  36378. this.isDirty = false;
  36379. this.deletePending = false;
  36380. this.borderFactor = 0;
  36381. }
  36382. return DecimationTriangle;
  36383. })();
  36384. BABYLON.DecimationTriangle = DecimationTriangle;
  36385. var DecimationVertex = (function () {
  36386. function DecimationVertex(position, id) {
  36387. this.position = position;
  36388. this.id = id;
  36389. this.isBorder = true;
  36390. this.q = new QuadraticMatrix();
  36391. this.triangleCount = 0;
  36392. this.triangleStart = 0;
  36393. this.originalOffsets = [];
  36394. }
  36395. DecimationVertex.prototype.updatePosition = function (newPosition) {
  36396. this.position.copyFrom(newPosition);
  36397. };
  36398. return DecimationVertex;
  36399. })();
  36400. BABYLON.DecimationVertex = DecimationVertex;
  36401. var QuadraticMatrix = (function () {
  36402. function QuadraticMatrix(data) {
  36403. this.data = new Array(10);
  36404. for (var i = 0; i < 10; ++i) {
  36405. if (data && data[i]) {
  36406. this.data[i] = data[i];
  36407. }
  36408. else {
  36409. this.data[i] = 0;
  36410. }
  36411. }
  36412. }
  36413. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  36414. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  36415. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  36416. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  36417. return det;
  36418. };
  36419. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  36420. for (var i = 0; i < 10; ++i) {
  36421. this.data[i] += matrix.data[i];
  36422. }
  36423. };
  36424. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  36425. for (var i = 0; i < 10; ++i) {
  36426. this.data[i] += data[i];
  36427. }
  36428. };
  36429. QuadraticMatrix.prototype.add = function (matrix) {
  36430. var m = new QuadraticMatrix();
  36431. for (var i = 0; i < 10; ++i) {
  36432. m.data[i] = this.data[i] + matrix.data[i];
  36433. }
  36434. return m;
  36435. };
  36436. QuadraticMatrix.FromData = function (a, b, c, d) {
  36437. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  36438. };
  36439. //returning an array to avoid garbage collection
  36440. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  36441. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  36442. };
  36443. return QuadraticMatrix;
  36444. })();
  36445. BABYLON.QuadraticMatrix = QuadraticMatrix;
  36446. var Reference = (function () {
  36447. function Reference(vertexId, triangleId) {
  36448. this.vertexId = vertexId;
  36449. this.triangleId = triangleId;
  36450. }
  36451. return Reference;
  36452. })();
  36453. BABYLON.Reference = Reference;
  36454. /**
  36455. * An implementation of the Quadratic Error simplification algorithm.
  36456. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  36457. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  36458. * @author RaananW
  36459. */
  36460. var QuadraticErrorSimplification = (function () {
  36461. function QuadraticErrorSimplification(_mesh) {
  36462. this._mesh = _mesh;
  36463. this.initialized = false;
  36464. this.syncIterations = 5000;
  36465. this.aggressiveness = 7;
  36466. this.decimationIterations = 100;
  36467. this.boundingBoxEpsilon = BABYLON.Epsilon;
  36468. }
  36469. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  36470. var _this = this;
  36471. this.initDecimatedMesh();
  36472. //iterating through the submeshes array, one after the other.
  36473. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  36474. _this.initWithMesh(loop.index, function () {
  36475. _this.runDecimation(settings, loop.index, function () {
  36476. loop.executeNext();
  36477. });
  36478. }, settings.optimizeMesh);
  36479. }, function () {
  36480. setTimeout(function () {
  36481. successCallback(_this._reconstructedMesh);
  36482. }, 0);
  36483. });
  36484. };
  36485. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  36486. var _this = this;
  36487. var gCount = 0;
  36488. triangle.vertices.forEach(function (vertex) {
  36489. var count = 0;
  36490. var vPos = vertex.position;
  36491. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  36492. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  36493. ++count;
  36494. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  36495. ++count;
  36496. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  36497. ++count;
  36498. if (count > 1) {
  36499. ++gCount;
  36500. }
  36501. ;
  36502. });
  36503. if (gCount > 1) {
  36504. console.log(triangle, gCount);
  36505. }
  36506. return gCount > 1;
  36507. };
  36508. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  36509. var _this = this;
  36510. var targetCount = ~~(this.triangles.length * settings.quality);
  36511. var deletedTriangles = 0;
  36512. var triangleCount = this.triangles.length;
  36513. var iterationFunction = function (iteration, callback) {
  36514. setTimeout(function () {
  36515. if (iteration % 5 === 0) {
  36516. _this.updateMesh(iteration === 0);
  36517. }
  36518. for (var i = 0; i < _this.triangles.length; ++i) {
  36519. _this.triangles[i].isDirty = false;
  36520. }
  36521. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  36522. var trianglesIterator = function (i) {
  36523. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  36524. var t = _this.triangles[tIdx];
  36525. if (!t)
  36526. return;
  36527. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  36528. return;
  36529. }
  36530. for (var j = 0; j < 3; ++j) {
  36531. if (t.error[j] < threshold) {
  36532. var deleted0 = [];
  36533. var deleted1 = [];
  36534. var v0 = t.vertices[j];
  36535. var v1 = t.vertices[(j + 1) % 3];
  36536. if (v0.isBorder || v1.isBorder)
  36537. continue;
  36538. var p = BABYLON.Vector3.Zero();
  36539. var n = BABYLON.Vector3.Zero();
  36540. var uv = BABYLON.Vector2.Zero();
  36541. var color = new BABYLON.Color4(0, 0, 0, 1);
  36542. _this.calculateError(v0, v1, p, n, uv, color);
  36543. var delTr = [];
  36544. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  36545. continue;
  36546. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  36547. continue;
  36548. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  36549. continue;
  36550. var uniqueArray = [];
  36551. delTr.forEach(function (deletedT) {
  36552. if (uniqueArray.indexOf(deletedT) === -1) {
  36553. deletedT.deletePending = true;
  36554. uniqueArray.push(deletedT);
  36555. }
  36556. });
  36557. if (uniqueArray.length % 2 !== 0) {
  36558. continue;
  36559. }
  36560. v0.q = v1.q.add(v0.q);
  36561. v0.updatePosition(p);
  36562. var tStart = _this.references.length;
  36563. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  36564. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  36565. var tCount = _this.references.length - tStart;
  36566. if (tCount <= v0.triangleCount) {
  36567. if (tCount) {
  36568. for (var c = 0; c < tCount; c++) {
  36569. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  36570. }
  36571. }
  36572. }
  36573. else {
  36574. v0.triangleStart = tStart;
  36575. }
  36576. v0.triangleCount = tCount;
  36577. break;
  36578. }
  36579. }
  36580. };
  36581. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  36582. }, 0);
  36583. };
  36584. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  36585. if (triangleCount - deletedTriangles <= targetCount)
  36586. loop.breakLoop();
  36587. else {
  36588. iterationFunction(loop.index, function () {
  36589. loop.executeNext();
  36590. });
  36591. }
  36592. }, function () {
  36593. setTimeout(function () {
  36594. //reconstruct this part of the mesh
  36595. _this.reconstructMesh(submeshIndex);
  36596. successCallback();
  36597. }, 0);
  36598. });
  36599. };
  36600. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  36601. var _this = this;
  36602. this.vertices = [];
  36603. this.triangles = [];
  36604. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36605. var indices = this._mesh.getIndices();
  36606. var submesh = this._mesh.subMeshes[submeshIndex];
  36607. var findInVertices = function (positionToSearch) {
  36608. if (optimizeMesh) {
  36609. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  36610. if (_this.vertices[ii].position.equals(positionToSearch)) {
  36611. return _this.vertices[ii];
  36612. }
  36613. }
  36614. }
  36615. return null;
  36616. };
  36617. var vertexReferences = [];
  36618. var vertexInit = function (i) {
  36619. var offset = i + submesh.verticesStart;
  36620. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  36621. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  36622. vertex.originalOffsets.push(offset);
  36623. if (vertex.id === _this.vertices.length) {
  36624. _this.vertices.push(vertex);
  36625. }
  36626. vertexReferences.push(vertex.id);
  36627. };
  36628. //var totalVertices = mesh.getTotalVertices();
  36629. var totalVertices = submesh.verticesCount;
  36630. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  36631. var indicesInit = function (i) {
  36632. var offset = (submesh.indexStart / 3) + i;
  36633. var pos = (offset * 3);
  36634. var i0 = indices[pos + 0];
  36635. var i1 = indices[pos + 1];
  36636. var i2 = indices[pos + 2];
  36637. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  36638. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  36639. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  36640. var triangle = new DecimationTriangle([v0, v1, v2]);
  36641. triangle.originalOffset = pos;
  36642. _this.triangles.push(triangle);
  36643. };
  36644. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  36645. _this.init(callback);
  36646. });
  36647. });
  36648. };
  36649. QuadraticErrorSimplification.prototype.init = function (callback) {
  36650. var _this = this;
  36651. var triangleInit1 = function (i) {
  36652. var t = _this.triangles[i];
  36653. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  36654. for (var j = 0; j < 3; j++) {
  36655. 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))));
  36656. }
  36657. };
  36658. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  36659. var triangleInit2 = function (i) {
  36660. var t = _this.triangles[i];
  36661. for (var j = 0; j < 3; ++j) {
  36662. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  36663. }
  36664. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  36665. };
  36666. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  36667. _this.initialized = true;
  36668. callback();
  36669. });
  36670. });
  36671. };
  36672. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  36673. var newTriangles = [];
  36674. var i;
  36675. for (i = 0; i < this.vertices.length; ++i) {
  36676. this.vertices[i].triangleCount = 0;
  36677. }
  36678. var t;
  36679. var j;
  36680. for (i = 0; i < this.triangles.length; ++i) {
  36681. if (!this.triangles[i].deleted) {
  36682. t = this.triangles[i];
  36683. for (j = 0; j < 3; ++j) {
  36684. t.vertices[j].triangleCount = 1;
  36685. }
  36686. newTriangles.push(t);
  36687. }
  36688. }
  36689. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  36690. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  36691. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  36692. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  36693. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36694. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36695. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36696. var vertexCount = 0;
  36697. for (i = 0; i < this.vertices.length; ++i) {
  36698. var vertex = this.vertices[i];
  36699. vertex.id = vertexCount;
  36700. if (vertex.triangleCount) {
  36701. vertex.originalOffsets.forEach(function (originalOffset) {
  36702. newPositionData.push(vertex.position.x);
  36703. newPositionData.push(vertex.position.y);
  36704. newPositionData.push(vertex.position.z);
  36705. newNormalData.push(normalData[originalOffset * 3]);
  36706. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  36707. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  36708. if (uvs && uvs.length) {
  36709. newUVsData.push(uvs[(originalOffset * 2)]);
  36710. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  36711. }
  36712. else if (colorsData && colorsData.length) {
  36713. newColorsData.push(colorsData[(originalOffset * 4)]);
  36714. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  36715. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  36716. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  36717. }
  36718. ++vertexCount;
  36719. });
  36720. }
  36721. }
  36722. var startingIndex = this._reconstructedMesh.getTotalIndices();
  36723. var startingVertex = this._reconstructedMesh.getTotalVertices();
  36724. var submeshesArray = this._reconstructedMesh.subMeshes;
  36725. this._reconstructedMesh.subMeshes = [];
  36726. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  36727. var originalIndices = this._mesh.getIndices();
  36728. for (i = 0; i < newTriangles.length; ++i) {
  36729. t = newTriangles[i]; //now get the new referencing point for each vertex
  36730. [0, 1, 2].forEach(function (idx) {
  36731. var id = originalIndices[t.originalOffset + idx];
  36732. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  36733. if (offset < 0)
  36734. offset = 0;
  36735. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  36736. });
  36737. }
  36738. //overwriting the old vertex buffers and indices.
  36739. this._reconstructedMesh.setIndices(newIndicesArray);
  36740. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  36741. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  36742. if (newUVsData.length > 0)
  36743. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  36744. if (newColorsData.length > 0)
  36745. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  36746. //create submesh
  36747. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  36748. if (submeshIndex > 0) {
  36749. this._reconstructedMesh.subMeshes = [];
  36750. submeshesArray.forEach(function (submesh) {
  36751. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  36752. });
  36753. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  36754. }
  36755. };
  36756. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  36757. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  36758. this._reconstructedMesh.material = this._mesh.material;
  36759. this._reconstructedMesh.parent = this._mesh.parent;
  36760. this._reconstructedMesh.isVisible = false;
  36761. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  36762. };
  36763. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  36764. for (var i = 0; i < vertex1.triangleCount; ++i) {
  36765. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  36766. if (t.deleted)
  36767. continue;
  36768. var s = this.references[vertex1.triangleStart + i].vertexId;
  36769. var v1 = t.vertices[(s + 1) % 3];
  36770. var v2 = t.vertices[(s + 2) % 3];
  36771. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  36772. deletedArray[i] = true;
  36773. delTr.push(t);
  36774. continue;
  36775. }
  36776. var d1 = v1.position.subtract(point);
  36777. d1 = d1.normalize();
  36778. var d2 = v2.position.subtract(point);
  36779. d2 = d2.normalize();
  36780. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  36781. return true;
  36782. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  36783. deletedArray[i] = false;
  36784. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  36785. return true;
  36786. }
  36787. return false;
  36788. };
  36789. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  36790. var newDeleted = deletedTriangles;
  36791. for (var i = 0; i < vertex.triangleCount; ++i) {
  36792. var ref = this.references[vertex.triangleStart + i];
  36793. var t = this.triangles[ref.triangleId];
  36794. if (t.deleted)
  36795. continue;
  36796. if (deletedArray[i] && t.deletePending) {
  36797. t.deleted = true;
  36798. newDeleted++;
  36799. continue;
  36800. }
  36801. t.vertices[ref.vertexId] = origVertex;
  36802. t.isDirty = true;
  36803. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  36804. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  36805. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  36806. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  36807. this.references.push(ref);
  36808. }
  36809. return newDeleted;
  36810. };
  36811. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  36812. for (var i = 0; i < this.vertices.length; ++i) {
  36813. var vCount = [];
  36814. var vId = [];
  36815. var v = this.vertices[i];
  36816. var j;
  36817. for (j = 0; j < v.triangleCount; ++j) {
  36818. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  36819. for (var ii = 0; ii < 3; ii++) {
  36820. var ofs = 0;
  36821. var vv = triangle.vertices[ii];
  36822. while (ofs < vCount.length) {
  36823. if (vId[ofs] === vv.id)
  36824. break;
  36825. ++ofs;
  36826. }
  36827. if (ofs === vCount.length) {
  36828. vCount.push(1);
  36829. vId.push(vv.id);
  36830. }
  36831. else {
  36832. vCount[ofs]++;
  36833. }
  36834. }
  36835. }
  36836. for (j = 0; j < vCount.length; ++j) {
  36837. if (vCount[j] === 1) {
  36838. this.vertices[vId[j]].isBorder = true;
  36839. }
  36840. else {
  36841. this.vertices[vId[j]].isBorder = false;
  36842. }
  36843. }
  36844. }
  36845. };
  36846. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  36847. if (identifyBorders === void 0) { identifyBorders = false; }
  36848. var i;
  36849. if (!identifyBorders) {
  36850. var newTrianglesVector = [];
  36851. for (i = 0; i < this.triangles.length; ++i) {
  36852. if (!this.triangles[i].deleted) {
  36853. newTrianglesVector.push(this.triangles[i]);
  36854. }
  36855. }
  36856. this.triangles = newTrianglesVector;
  36857. }
  36858. for (i = 0; i < this.vertices.length; ++i) {
  36859. this.vertices[i].triangleCount = 0;
  36860. this.vertices[i].triangleStart = 0;
  36861. }
  36862. var t;
  36863. var j;
  36864. var v;
  36865. for (i = 0; i < this.triangles.length; ++i) {
  36866. t = this.triangles[i];
  36867. for (j = 0; j < 3; ++j) {
  36868. v = t.vertices[j];
  36869. v.triangleCount++;
  36870. }
  36871. }
  36872. var tStart = 0;
  36873. for (i = 0; i < this.vertices.length; ++i) {
  36874. this.vertices[i].triangleStart = tStart;
  36875. tStart += this.vertices[i].triangleCount;
  36876. this.vertices[i].triangleCount = 0;
  36877. }
  36878. var newReferences = new Array(this.triangles.length * 3);
  36879. for (i = 0; i < this.triangles.length; ++i) {
  36880. t = this.triangles[i];
  36881. for (j = 0; j < 3; ++j) {
  36882. v = t.vertices[j];
  36883. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  36884. v.triangleCount++;
  36885. }
  36886. }
  36887. this.references = newReferences;
  36888. if (identifyBorders) {
  36889. this.identifyBorder();
  36890. }
  36891. };
  36892. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  36893. var x = point.x;
  36894. var y = point.y;
  36895. var z = point.z;
  36896. 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
  36897. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  36898. };
  36899. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  36900. var q = vertex1.q.add(vertex2.q);
  36901. var border = vertex1.isBorder && vertex2.isBorder;
  36902. var error = 0;
  36903. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  36904. if (qDet !== 0 && !border) {
  36905. if (!pointResult) {
  36906. pointResult = BABYLON.Vector3.Zero();
  36907. }
  36908. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  36909. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  36910. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  36911. error = this.vertexError(q, pointResult);
  36912. }
  36913. else {
  36914. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  36915. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  36916. var error1 = this.vertexError(q, vertex1.position);
  36917. var error2 = this.vertexError(q, vertex2.position);
  36918. var error3 = this.vertexError(q, p3);
  36919. error = Math.min(error1, error2, error3);
  36920. if (error === error1) {
  36921. if (pointResult) {
  36922. pointResult.copyFrom(vertex1.position);
  36923. }
  36924. }
  36925. else if (error === error2) {
  36926. if (pointResult) {
  36927. pointResult.copyFrom(vertex2.position);
  36928. }
  36929. }
  36930. else {
  36931. if (pointResult) {
  36932. pointResult.copyFrom(p3);
  36933. }
  36934. }
  36935. }
  36936. return error;
  36937. };
  36938. return QuadraticErrorSimplification;
  36939. })();
  36940. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  36941. })(BABYLON || (BABYLON = {}));
  36942. var BABYLON;
  36943. (function (BABYLON) {
  36944. var serializedGeometries = [];
  36945. var serializeGeometry = function (geometry, serializationGeometries) {
  36946. if (serializedGeometries[geometry.id]) {
  36947. return;
  36948. }
  36949. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  36950. serializationGeometries.boxes.push(geometry.serialize());
  36951. }
  36952. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  36953. serializationGeometries.spheres.push(geometry.serialize());
  36954. }
  36955. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  36956. serializationGeometries.cylinders.push(geometry.serialize());
  36957. }
  36958. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  36959. serializationGeometries.toruses.push(geometry.serialize());
  36960. }
  36961. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  36962. serializationGeometries.grounds.push(geometry.serialize());
  36963. }
  36964. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  36965. serializationGeometries.planes.push(geometry.serialize());
  36966. }
  36967. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  36968. serializationGeometries.torusKnots.push(geometry.serialize());
  36969. }
  36970. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  36971. throw new Error("Unknown primitive type");
  36972. }
  36973. else {
  36974. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  36975. }
  36976. serializedGeometries[geometry.id] = true;
  36977. };
  36978. var serializeMesh = function (mesh, serializationScene) {
  36979. var serializationObject = {};
  36980. serializationObject.name = mesh.name;
  36981. serializationObject.id = mesh.id;
  36982. if (BABYLON.Tags.HasTags(mesh)) {
  36983. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  36984. }
  36985. serializationObject.position = mesh.position.asArray();
  36986. if (mesh.rotationQuaternion) {
  36987. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  36988. }
  36989. else if (mesh.rotation) {
  36990. serializationObject.rotation = mesh.rotation.asArray();
  36991. }
  36992. serializationObject.scaling = mesh.scaling.asArray();
  36993. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  36994. serializationObject.isEnabled = mesh.isEnabled();
  36995. serializationObject.isVisible = mesh.isVisible;
  36996. serializationObject.infiniteDistance = mesh.infiniteDistance;
  36997. serializationObject.pickable = mesh.isPickable;
  36998. serializationObject.receiveShadows = mesh.receiveShadows;
  36999. serializationObject.billboardMode = mesh.billboardMode;
  37000. serializationObject.visibility = mesh.visibility;
  37001. serializationObject.checkCollisions = mesh.checkCollisions;
  37002. // Parent
  37003. if (mesh.parent) {
  37004. serializationObject.parentId = mesh.parent.id;
  37005. }
  37006. // Geometry
  37007. var geometry = mesh._geometry;
  37008. if (geometry) {
  37009. var geometryId = geometry.id;
  37010. serializationObject.geometryId = geometryId;
  37011. if (!mesh.getScene().getGeometryByID(geometryId)) {
  37012. // 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
  37013. serializeGeometry(geometry, serializationScene.geometries);
  37014. }
  37015. // SubMeshes
  37016. serializationObject.subMeshes = [];
  37017. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37018. var subMesh = mesh.subMeshes[subIndex];
  37019. serializationObject.subMeshes.push({
  37020. materialIndex: subMesh.materialIndex,
  37021. verticesStart: subMesh.verticesStart,
  37022. verticesCount: subMesh.verticesCount,
  37023. indexStart: subMesh.indexStart,
  37024. indexCount: subMesh.indexCount
  37025. });
  37026. }
  37027. }
  37028. // Material
  37029. if (mesh.material) {
  37030. serializationObject.materialId = mesh.material.id;
  37031. }
  37032. else {
  37033. mesh.material = null;
  37034. }
  37035. // Skeleton
  37036. if (mesh.skeleton) {
  37037. serializationObject.skeletonId = mesh.skeleton.id;
  37038. }
  37039. // Physics
  37040. //TODO implement correct serialization for physics impostors.
  37041. if (mesh.getPhysicsImpostor()) {
  37042. serializationObject.physicsMass = mesh.getPhysicsMass();
  37043. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  37044. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  37045. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  37046. }
  37047. // Instances
  37048. serializationObject.instances = [];
  37049. for (var index = 0; index < mesh.instances.length; index++) {
  37050. var instance = mesh.instances[index];
  37051. var serializationInstance = {
  37052. name: instance.name,
  37053. position: instance.position.asArray(),
  37054. scaling: instance.scaling.asArray()
  37055. };
  37056. if (instance.rotationQuaternion) {
  37057. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  37058. }
  37059. else if (instance.rotation) {
  37060. serializationInstance.rotation = instance.rotation.asArray();
  37061. }
  37062. serializationObject.instances.push(serializationInstance);
  37063. // Animations
  37064. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  37065. serializationInstance.ranges = instance.serializeAnimationRanges();
  37066. }
  37067. // Animations
  37068. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  37069. serializationObject.ranges = mesh.serializeAnimationRanges();
  37070. // Layer mask
  37071. serializationObject.layerMask = mesh.layerMask;
  37072. // Action Manager
  37073. if (mesh.actionManager) {
  37074. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  37075. }
  37076. return serializationObject;
  37077. };
  37078. var finalizeSingleMesh = function (mesh, serializationObject) {
  37079. //only works if the mesh is already loaded
  37080. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  37081. //serialize material
  37082. if (mesh.material) {
  37083. if (mesh.material instanceof BABYLON.StandardMaterial) {
  37084. serializationObject.materials = serializationObject.materials || [];
  37085. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  37086. serializationObject.materials.push(mesh.material.serialize());
  37087. }
  37088. }
  37089. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  37090. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  37091. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  37092. serializationObject.multiMaterials.push(mesh.material.serialize());
  37093. }
  37094. }
  37095. }
  37096. //serialize geometry
  37097. var geometry = mesh._geometry;
  37098. if (geometry) {
  37099. if (!serializationObject.geometries) {
  37100. serializationObject.geometries = {};
  37101. serializationObject.geometries.boxes = [];
  37102. serializationObject.geometries.spheres = [];
  37103. serializationObject.geometries.cylinders = [];
  37104. serializationObject.geometries.toruses = [];
  37105. serializationObject.geometries.grounds = [];
  37106. serializationObject.geometries.planes = [];
  37107. serializationObject.geometries.torusKnots = [];
  37108. serializationObject.geometries.vertexData = [];
  37109. }
  37110. serializeGeometry(geometry, serializationObject.geometries);
  37111. }
  37112. // Skeletons
  37113. if (mesh.skeleton) {
  37114. serializationObject.skeletons = serializationObject.skeletons || [];
  37115. serializationObject.skeletons.push(mesh.skeleton.serialize());
  37116. }
  37117. //serialize the actual mesh
  37118. serializationObject.meshes = serializationObject.meshes || [];
  37119. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  37120. }
  37121. };
  37122. var SceneSerializer = (function () {
  37123. function SceneSerializer() {
  37124. }
  37125. SceneSerializer.ClearCache = function () {
  37126. serializedGeometries = [];
  37127. };
  37128. SceneSerializer.Serialize = function (scene) {
  37129. var serializationObject = {};
  37130. // Scene
  37131. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  37132. serializationObject.autoClear = scene.autoClear;
  37133. serializationObject.clearColor = scene.clearColor.asArray();
  37134. serializationObject.ambientColor = scene.ambientColor.asArray();
  37135. serializationObject.gravity = scene.gravity.asArray();
  37136. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  37137. serializationObject.workerCollisions = scene.workerCollisions;
  37138. // Fog
  37139. if (scene.fogMode && scene.fogMode !== 0) {
  37140. serializationObject.fogMode = scene.fogMode;
  37141. serializationObject.fogColor = scene.fogColor.asArray();
  37142. serializationObject.fogStart = scene.fogStart;
  37143. serializationObject.fogEnd = scene.fogEnd;
  37144. serializationObject.fogDensity = scene.fogDensity;
  37145. }
  37146. //Physics
  37147. if (scene.isPhysicsEnabled()) {
  37148. serializationObject.physicsEnabled = true;
  37149. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  37150. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  37151. }
  37152. // Lights
  37153. serializationObject.lights = [];
  37154. var index;
  37155. var light;
  37156. for (index = 0; index < scene.lights.length; index++) {
  37157. light = scene.lights[index];
  37158. serializationObject.lights.push(light.serialize());
  37159. }
  37160. // Cameras
  37161. serializationObject.cameras = [];
  37162. for (index = 0; index < scene.cameras.length; index++) {
  37163. var camera = scene.cameras[index];
  37164. serializationObject.cameras.push(camera.serialize());
  37165. }
  37166. if (scene.activeCamera) {
  37167. serializationObject.activeCameraID = scene.activeCamera.id;
  37168. }
  37169. // Animations
  37170. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  37171. // Materials
  37172. serializationObject.materials = [];
  37173. serializationObject.multiMaterials = [];
  37174. var material;
  37175. for (index = 0; index < scene.materials.length; index++) {
  37176. material = scene.materials[index];
  37177. serializationObject.materials.push(material.serialize());
  37178. }
  37179. // MultiMaterials
  37180. serializationObject.multiMaterials = [];
  37181. for (index = 0; index < scene.multiMaterials.length; index++) {
  37182. var multiMaterial = scene.multiMaterials[index];
  37183. serializationObject.multiMaterials.push(multiMaterial.serialize());
  37184. }
  37185. // Skeletons
  37186. serializationObject.skeletons = [];
  37187. for (index = 0; index < scene.skeletons.length; index++) {
  37188. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  37189. }
  37190. // Geometries
  37191. serializationObject.geometries = {};
  37192. serializationObject.geometries.boxes = [];
  37193. serializationObject.geometries.spheres = [];
  37194. serializationObject.geometries.cylinders = [];
  37195. serializationObject.geometries.toruses = [];
  37196. serializationObject.geometries.grounds = [];
  37197. serializationObject.geometries.planes = [];
  37198. serializationObject.geometries.torusKnots = [];
  37199. serializationObject.geometries.vertexData = [];
  37200. serializedGeometries = [];
  37201. var geometries = scene.getGeometries();
  37202. for (index = 0; index < geometries.length; index++) {
  37203. var geometry = geometries[index];
  37204. if (geometry.isReady()) {
  37205. serializeGeometry(geometry, serializationObject.geometries);
  37206. }
  37207. }
  37208. // Meshes
  37209. serializationObject.meshes = [];
  37210. for (index = 0; index < scene.meshes.length; index++) {
  37211. var abstractMesh = scene.meshes[index];
  37212. if (abstractMesh instanceof BABYLON.Mesh) {
  37213. var mesh = abstractMesh;
  37214. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  37215. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  37216. }
  37217. }
  37218. }
  37219. // Particles Systems
  37220. serializationObject.particleSystems = [];
  37221. for (index = 0; index < scene.particleSystems.length; index++) {
  37222. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  37223. }
  37224. // Lens flares
  37225. serializationObject.lensFlareSystems = [];
  37226. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  37227. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  37228. }
  37229. // Shadows
  37230. serializationObject.shadowGenerators = [];
  37231. for (index = 0; index < scene.lights.length; index++) {
  37232. light = scene.lights[index];
  37233. if (light.getShadowGenerator()) {
  37234. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  37235. }
  37236. }
  37237. // Action Manager
  37238. if (scene.actionManager) {
  37239. serializationObject.actions = scene.actionManager.serialize("scene");
  37240. }
  37241. return serializationObject;
  37242. };
  37243. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  37244. if (withParents === void 0) { withParents = false; }
  37245. if (withChildren === void 0) { withChildren = false; }
  37246. var serializationObject = {};
  37247. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  37248. if (withParents || withChildren) {
  37249. //deliberate for loop! not for each, appended should be processed as well.
  37250. for (var i = 0; i < toSerialize.length; ++i) {
  37251. if (withChildren) {
  37252. toSerialize[i].getDescendants().forEach(function (node) {
  37253. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  37254. toSerialize.push(node);
  37255. }
  37256. });
  37257. }
  37258. //make sure the array doesn't contain the object already
  37259. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  37260. toSerialize.push(toSerialize[i].parent);
  37261. }
  37262. }
  37263. }
  37264. toSerialize.forEach(function (mesh) {
  37265. finalizeSingleMesh(mesh, serializationObject);
  37266. });
  37267. return serializationObject;
  37268. };
  37269. return SceneSerializer;
  37270. })();
  37271. BABYLON.SceneSerializer = SceneSerializer;
  37272. })(BABYLON || (BABYLON = {}));
  37273. var BABYLON;
  37274. (function (BABYLON) {
  37275. // Unique ID when we import meshes from Babylon to CSG
  37276. var currentCSGMeshId = 0;
  37277. // # class Vertex
  37278. // Represents a vertex of a polygon. Use your own vertex class instead of this
  37279. // one to provide additional features like texture coordinates and vertex
  37280. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  37281. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  37282. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  37283. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  37284. // is not used anywhere else.
  37285. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  37286. var Vertex = (function () {
  37287. function Vertex(pos, normal, uv) {
  37288. this.pos = pos;
  37289. this.normal = normal;
  37290. this.uv = uv;
  37291. }
  37292. Vertex.prototype.clone = function () {
  37293. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  37294. };
  37295. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  37296. // orientation of a polygon is flipped.
  37297. Vertex.prototype.flip = function () {
  37298. this.normal = this.normal.scale(-1);
  37299. };
  37300. // Create a new vertex between this vertex and `other` by linearly
  37301. // interpolating all properties using a parameter of `t`. Subclasses should
  37302. // override this to interpolate additional properties.
  37303. Vertex.prototype.interpolate = function (other, t) {
  37304. 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));
  37305. };
  37306. return Vertex;
  37307. })();
  37308. // # class Plane
  37309. // Represents a plane in 3D space.
  37310. var Plane = (function () {
  37311. function Plane(normal, w) {
  37312. this.normal = normal;
  37313. this.w = w;
  37314. }
  37315. Plane.FromPoints = function (a, b, c) {
  37316. var v0 = c.subtract(a);
  37317. var v1 = b.subtract(a);
  37318. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  37319. return null;
  37320. }
  37321. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  37322. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  37323. };
  37324. Plane.prototype.clone = function () {
  37325. return new Plane(this.normal.clone(), this.w);
  37326. };
  37327. Plane.prototype.flip = function () {
  37328. this.normal.scaleInPlace(-1);
  37329. this.w = -this.w;
  37330. };
  37331. // Split `polygon` by this plane if needed, then put the polygon or polygon
  37332. // fragments in the appropriate lists. Coplanar polygons go into either
  37333. // `coplanarFront` or `coplanarBack` depending on their orientation with
  37334. // respect to this plane. Polygons in front or in back of this plane go into
  37335. // either `front` or `back`.
  37336. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  37337. var COPLANAR = 0;
  37338. var FRONT = 1;
  37339. var BACK = 2;
  37340. var SPANNING = 3;
  37341. // Classify each point as well as the entire polygon into one of the above
  37342. // four classes.
  37343. var polygonType = 0;
  37344. var types = [];
  37345. var i;
  37346. var t;
  37347. for (i = 0; i < polygon.vertices.length; i++) {
  37348. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  37349. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  37350. polygonType |= type;
  37351. types.push(type);
  37352. }
  37353. // Put the polygon in the correct list, splitting it when necessary.
  37354. switch (polygonType) {
  37355. case COPLANAR:
  37356. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  37357. break;
  37358. case FRONT:
  37359. front.push(polygon);
  37360. break;
  37361. case BACK:
  37362. back.push(polygon);
  37363. break;
  37364. case SPANNING:
  37365. var f = [], b = [];
  37366. for (i = 0; i < polygon.vertices.length; i++) {
  37367. var j = (i + 1) % polygon.vertices.length;
  37368. var ti = types[i], tj = types[j];
  37369. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  37370. if (ti !== BACK)
  37371. f.push(vi);
  37372. if (ti !== FRONT)
  37373. b.push(ti !== BACK ? vi.clone() : vi);
  37374. if ((ti | tj) === SPANNING) {
  37375. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  37376. var v = vi.interpolate(vj, t);
  37377. f.push(v);
  37378. b.push(v.clone());
  37379. }
  37380. }
  37381. var poly;
  37382. if (f.length >= 3) {
  37383. poly = new Polygon(f, polygon.shared);
  37384. if (poly.plane)
  37385. front.push(poly);
  37386. }
  37387. if (b.length >= 3) {
  37388. poly = new Polygon(b, polygon.shared);
  37389. if (poly.plane)
  37390. back.push(poly);
  37391. }
  37392. break;
  37393. }
  37394. };
  37395. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  37396. // point is on the plane.
  37397. Plane.EPSILON = 1e-5;
  37398. return Plane;
  37399. })();
  37400. // # class Polygon
  37401. // Represents a convex polygon. The vertices used to initialize a polygon must
  37402. // be coplanar and form a convex loop.
  37403. //
  37404. // Each convex polygon has a `shared` property, which is shared between all
  37405. // polygons that are clones of each other or were split from the same polygon.
  37406. // This can be used to define per-polygon properties (such as surface color).
  37407. var Polygon = (function () {
  37408. function Polygon(vertices, shared) {
  37409. this.vertices = vertices;
  37410. this.shared = shared;
  37411. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  37412. }
  37413. Polygon.prototype.clone = function () {
  37414. var vertices = this.vertices.map(function (v) { return v.clone(); });
  37415. return new Polygon(vertices, this.shared);
  37416. };
  37417. Polygon.prototype.flip = function () {
  37418. this.vertices.reverse().map(function (v) { v.flip(); });
  37419. this.plane.flip();
  37420. };
  37421. return Polygon;
  37422. })();
  37423. // # class Node
  37424. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  37425. // by picking a polygon to split along. That polygon (and all other coplanar
  37426. // polygons) are added directly to that node and the other polygons are added to
  37427. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  37428. // no distinction between internal and leaf nodes.
  37429. var Node = (function () {
  37430. function Node(polygons) {
  37431. this.plane = null;
  37432. this.front = null;
  37433. this.back = null;
  37434. this.polygons = [];
  37435. if (polygons) {
  37436. this.build(polygons);
  37437. }
  37438. }
  37439. Node.prototype.clone = function () {
  37440. var node = new Node();
  37441. node.plane = this.plane && this.plane.clone();
  37442. node.front = this.front && this.front.clone();
  37443. node.back = this.back && this.back.clone();
  37444. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  37445. return node;
  37446. };
  37447. // Convert solid space to empty space and empty space to solid space.
  37448. Node.prototype.invert = function () {
  37449. for (var i = 0; i < this.polygons.length; i++) {
  37450. this.polygons[i].flip();
  37451. }
  37452. if (this.plane) {
  37453. this.plane.flip();
  37454. }
  37455. if (this.front) {
  37456. this.front.invert();
  37457. }
  37458. if (this.back) {
  37459. this.back.invert();
  37460. }
  37461. var temp = this.front;
  37462. this.front = this.back;
  37463. this.back = temp;
  37464. };
  37465. // Recursively remove all polygons in `polygons` that are inside this BSP
  37466. // tree.
  37467. Node.prototype.clipPolygons = function (polygons) {
  37468. if (!this.plane)
  37469. return polygons.slice();
  37470. var front = [], back = [];
  37471. for (var i = 0; i < polygons.length; i++) {
  37472. this.plane.splitPolygon(polygons[i], front, back, front, back);
  37473. }
  37474. if (this.front) {
  37475. front = this.front.clipPolygons(front);
  37476. }
  37477. if (this.back) {
  37478. back = this.back.clipPolygons(back);
  37479. }
  37480. else {
  37481. back = [];
  37482. }
  37483. return front.concat(back);
  37484. };
  37485. // Remove all polygons in this BSP tree that are inside the other BSP tree
  37486. // `bsp`.
  37487. Node.prototype.clipTo = function (bsp) {
  37488. this.polygons = bsp.clipPolygons(this.polygons);
  37489. if (this.front)
  37490. this.front.clipTo(bsp);
  37491. if (this.back)
  37492. this.back.clipTo(bsp);
  37493. };
  37494. // Return a list of all polygons in this BSP tree.
  37495. Node.prototype.allPolygons = function () {
  37496. var polygons = this.polygons.slice();
  37497. if (this.front)
  37498. polygons = polygons.concat(this.front.allPolygons());
  37499. if (this.back)
  37500. polygons = polygons.concat(this.back.allPolygons());
  37501. return polygons;
  37502. };
  37503. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  37504. // new polygons are filtered down to the bottom of the tree and become new
  37505. // nodes there. Each set of polygons is partitioned using the first polygon
  37506. // (no heuristic is used to pick a good split).
  37507. Node.prototype.build = function (polygons) {
  37508. if (!polygons.length)
  37509. return;
  37510. if (!this.plane)
  37511. this.plane = polygons[0].plane.clone();
  37512. var front = [], back = [];
  37513. for (var i = 0; i < polygons.length; i++) {
  37514. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  37515. }
  37516. if (front.length) {
  37517. if (!this.front)
  37518. this.front = new Node();
  37519. this.front.build(front);
  37520. }
  37521. if (back.length) {
  37522. if (!this.back)
  37523. this.back = new Node();
  37524. this.back.build(back);
  37525. }
  37526. };
  37527. return Node;
  37528. })();
  37529. var CSG = (function () {
  37530. function CSG() {
  37531. this.polygons = new Array();
  37532. }
  37533. // Convert BABYLON.Mesh to BABYLON.CSG
  37534. CSG.FromMesh = function (mesh) {
  37535. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  37536. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  37537. if (mesh instanceof BABYLON.Mesh) {
  37538. mesh.computeWorldMatrix(true);
  37539. matrix = mesh.getWorldMatrix();
  37540. meshPosition = mesh.position.clone();
  37541. meshRotation = mesh.rotation.clone();
  37542. if (mesh.rotationQuaternion) {
  37543. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  37544. }
  37545. meshScaling = mesh.scaling.clone();
  37546. }
  37547. else {
  37548. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  37549. }
  37550. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37551. var subMeshes = mesh.subMeshes;
  37552. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  37553. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  37554. vertices = [];
  37555. for (var j = 0; j < 3; j++) {
  37556. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  37557. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  37558. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  37559. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  37560. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  37561. vertex = new Vertex(position, normal, uv);
  37562. vertices.push(vertex);
  37563. }
  37564. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  37565. // To handle the case of degenerated triangle
  37566. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  37567. if (polygon.plane)
  37568. polygons.push(polygon);
  37569. }
  37570. }
  37571. var csg = CSG.FromPolygons(polygons);
  37572. csg.matrix = matrix;
  37573. csg.position = meshPosition;
  37574. csg.rotation = meshRotation;
  37575. csg.scaling = meshScaling;
  37576. csg.rotationQuaternion = meshRotationQuaternion;
  37577. currentCSGMeshId++;
  37578. return csg;
  37579. };
  37580. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  37581. CSG.FromPolygons = function (polygons) {
  37582. var csg = new CSG();
  37583. csg.polygons = polygons;
  37584. return csg;
  37585. };
  37586. CSG.prototype.clone = function () {
  37587. var csg = new CSG();
  37588. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  37589. csg.copyTransformAttributes(this);
  37590. return csg;
  37591. };
  37592. CSG.prototype.toPolygons = function () {
  37593. return this.polygons;
  37594. };
  37595. CSG.prototype.union = function (csg) {
  37596. var a = new Node(this.clone().polygons);
  37597. var b = new Node(csg.clone().polygons);
  37598. a.clipTo(b);
  37599. b.clipTo(a);
  37600. b.invert();
  37601. b.clipTo(a);
  37602. b.invert();
  37603. a.build(b.allPolygons());
  37604. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37605. };
  37606. CSG.prototype.unionInPlace = function (csg) {
  37607. var a = new Node(this.polygons);
  37608. var b = new Node(csg.polygons);
  37609. a.clipTo(b);
  37610. b.clipTo(a);
  37611. b.invert();
  37612. b.clipTo(a);
  37613. b.invert();
  37614. a.build(b.allPolygons());
  37615. this.polygons = a.allPolygons();
  37616. };
  37617. CSG.prototype.subtract = function (csg) {
  37618. var a = new Node(this.clone().polygons);
  37619. var b = new Node(csg.clone().polygons);
  37620. a.invert();
  37621. a.clipTo(b);
  37622. b.clipTo(a);
  37623. b.invert();
  37624. b.clipTo(a);
  37625. b.invert();
  37626. a.build(b.allPolygons());
  37627. a.invert();
  37628. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37629. };
  37630. CSG.prototype.subtractInPlace = function (csg) {
  37631. var a = new Node(this.polygons);
  37632. var b = new Node(csg.polygons);
  37633. a.invert();
  37634. a.clipTo(b);
  37635. b.clipTo(a);
  37636. b.invert();
  37637. b.clipTo(a);
  37638. b.invert();
  37639. a.build(b.allPolygons());
  37640. a.invert();
  37641. this.polygons = a.allPolygons();
  37642. };
  37643. CSG.prototype.intersect = function (csg) {
  37644. var a = new Node(this.clone().polygons);
  37645. var b = new Node(csg.clone().polygons);
  37646. a.invert();
  37647. b.clipTo(a);
  37648. b.invert();
  37649. a.clipTo(b);
  37650. b.clipTo(a);
  37651. a.build(b.allPolygons());
  37652. a.invert();
  37653. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37654. };
  37655. CSG.prototype.intersectInPlace = function (csg) {
  37656. var a = new Node(this.polygons);
  37657. var b = new Node(csg.polygons);
  37658. a.invert();
  37659. b.clipTo(a);
  37660. b.invert();
  37661. a.clipTo(b);
  37662. b.clipTo(a);
  37663. a.build(b.allPolygons());
  37664. a.invert();
  37665. this.polygons = a.allPolygons();
  37666. };
  37667. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  37668. // not modified.
  37669. CSG.prototype.inverse = function () {
  37670. var csg = this.clone();
  37671. csg.inverseInPlace();
  37672. return csg;
  37673. };
  37674. CSG.prototype.inverseInPlace = function () {
  37675. this.polygons.map(function (p) { p.flip(); });
  37676. };
  37677. // This is used to keep meshes transformations so they can be restored
  37678. // when we build back a Babylon Mesh
  37679. // NB : All CSG operations are performed in world coordinates
  37680. CSG.prototype.copyTransformAttributes = function (csg) {
  37681. this.matrix = csg.matrix;
  37682. this.position = csg.position;
  37683. this.rotation = csg.rotation;
  37684. this.scaling = csg.scaling;
  37685. this.rotationQuaternion = csg.rotationQuaternion;
  37686. return this;
  37687. };
  37688. // Build Raw mesh from CSG
  37689. // Coordinates here are in world space
  37690. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  37691. var matrix = this.matrix.clone();
  37692. matrix.invert();
  37693. 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;
  37694. if (keepSubMeshes) {
  37695. // Sort Polygons, since subMeshes are indices range
  37696. polygons.sort(function (a, b) {
  37697. if (a.shared.meshId === b.shared.meshId) {
  37698. return a.shared.subMeshId - b.shared.subMeshId;
  37699. }
  37700. else {
  37701. return a.shared.meshId - b.shared.meshId;
  37702. }
  37703. });
  37704. }
  37705. for (var i = 0, il = polygons.length; i < il; i++) {
  37706. polygon = polygons[i];
  37707. // Building SubMeshes
  37708. if (!subMesh_dict[polygon.shared.meshId]) {
  37709. subMesh_dict[polygon.shared.meshId] = {};
  37710. }
  37711. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  37712. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  37713. indexStart: +Infinity,
  37714. indexEnd: -Infinity,
  37715. materialIndex: polygon.shared.materialIndex
  37716. };
  37717. }
  37718. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  37719. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  37720. polygonIndices[0] = 0;
  37721. polygonIndices[1] = j - 1;
  37722. polygonIndices[2] = j;
  37723. for (var k = 0; k < 3; k++) {
  37724. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  37725. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  37726. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  37727. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  37728. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  37729. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  37730. // Check if 2 points can be merged
  37731. if (!(typeof vertex_idx !== 'undefined' &&
  37732. normals[vertex_idx * 3] === localNormal.x &&
  37733. normals[vertex_idx * 3 + 1] === localNormal.y &&
  37734. normals[vertex_idx * 3 + 2] === localNormal.z &&
  37735. uvs[vertex_idx * 2] === uv.x &&
  37736. uvs[vertex_idx * 2 + 1] === uv.y)) {
  37737. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  37738. uvs.push(uv.x, uv.y);
  37739. normals.push(normal.x, normal.y, normal.z);
  37740. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  37741. }
  37742. indices.push(vertex_idx);
  37743. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  37744. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  37745. currentIndex++;
  37746. }
  37747. }
  37748. }
  37749. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  37750. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  37751. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  37752. mesh.setIndices(indices);
  37753. if (keepSubMeshes) {
  37754. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  37755. var materialIndexOffset = 0, materialMaxIndex;
  37756. mesh.subMeshes = new Array();
  37757. for (var m in subMesh_dict) {
  37758. materialMaxIndex = -1;
  37759. for (var sm in subMesh_dict[m]) {
  37760. subMesh_obj = subMesh_dict[m][sm];
  37761. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  37762. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  37763. }
  37764. materialIndexOffset += ++materialMaxIndex;
  37765. }
  37766. }
  37767. return mesh;
  37768. };
  37769. // Build Mesh from CSG taking material and transforms into account
  37770. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  37771. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  37772. mesh.material = material;
  37773. mesh.position.copyFrom(this.position);
  37774. mesh.rotation.copyFrom(this.rotation);
  37775. if (this.rotationQuaternion) {
  37776. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  37777. }
  37778. mesh.scaling.copyFrom(this.scaling);
  37779. mesh.computeWorldMatrix(true);
  37780. return mesh;
  37781. };
  37782. return CSG;
  37783. })();
  37784. BABYLON.CSG = CSG;
  37785. })(BABYLON || (BABYLON = {}));
  37786. var BABYLON;
  37787. (function (BABYLON) {
  37788. var VRDistortionCorrectionPostProcess = (function (_super) {
  37789. __extends(VRDistortionCorrectionPostProcess, _super);
  37790. //ANY
  37791. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  37792. var _this = this;
  37793. _super.call(this, name, "vrDistortionCorrection", [
  37794. 'LensCenter',
  37795. 'Scale',
  37796. 'ScaleIn',
  37797. 'HmdWarpParam'
  37798. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  37799. this._isRightEye = isRightEye;
  37800. this._distortionFactors = vrMetrics.distortionK;
  37801. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  37802. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  37803. this.onSizeChanged = function () {
  37804. _this.aspectRatio = _this.width * .5 / _this.height;
  37805. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  37806. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  37807. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  37808. };
  37809. this.onApply = function (effect) {
  37810. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  37811. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  37812. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  37813. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  37814. };
  37815. }
  37816. return VRDistortionCorrectionPostProcess;
  37817. })(BABYLON.PostProcess);
  37818. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  37819. })(BABYLON || (BABYLON = {}));
  37820. // Mainly based on these 2 articles :
  37821. // 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
  37822. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  37823. var BABYLON;
  37824. (function (BABYLON) {
  37825. (function (JoystickAxis) {
  37826. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  37827. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  37828. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  37829. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  37830. var JoystickAxis = BABYLON.JoystickAxis;
  37831. var VirtualJoystick = (function () {
  37832. function VirtualJoystick(leftJoystick) {
  37833. var _this = this;
  37834. if (leftJoystick) {
  37835. this._leftJoystick = true;
  37836. }
  37837. else {
  37838. this._leftJoystick = false;
  37839. }
  37840. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  37841. VirtualJoystick._globalJoystickIndex++;
  37842. // By default left & right arrow keys are moving the X
  37843. // and up & down keys are moving the Y
  37844. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37845. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37846. this.reverseLeftRight = false;
  37847. this.reverseUpDown = false;
  37848. // collections of pointers
  37849. this._touches = new BABYLON.StringDictionary();
  37850. this.deltaPosition = BABYLON.Vector3.Zero();
  37851. this._joystickSensibility = 25;
  37852. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  37853. this._rotationSpeed = 25;
  37854. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  37855. this._rotateOnAxisRelativeToMesh = false;
  37856. this._onResize = function (evt) {
  37857. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  37858. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  37859. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  37860. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  37861. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  37862. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  37863. };
  37864. // injecting a canvas element on top of the canvas 3D game
  37865. if (!VirtualJoystick.vjCanvas) {
  37866. window.addEventListener("resize", this._onResize, false);
  37867. VirtualJoystick.vjCanvas = document.createElement("canvas");
  37868. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  37869. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  37870. VirtualJoystick.vjCanvas.width = window.innerWidth;
  37871. VirtualJoystick.vjCanvas.height = window.innerHeight;
  37872. VirtualJoystick.vjCanvas.style.width = "100%";
  37873. VirtualJoystick.vjCanvas.style.height = "100%";
  37874. VirtualJoystick.vjCanvas.style.position = "absolute";
  37875. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  37876. VirtualJoystick.vjCanvas.style.top = "0px";
  37877. VirtualJoystick.vjCanvas.style.left = "0px";
  37878. VirtualJoystick.vjCanvas.style.zIndex = "5";
  37879. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  37880. // Support for jQuery PEP polyfill
  37881. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  37882. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  37883. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  37884. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37885. document.body.appendChild(VirtualJoystick.vjCanvas);
  37886. }
  37887. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  37888. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  37889. this.pressed = false;
  37890. // default joystick color
  37891. this._joystickColor = "cyan";
  37892. this._joystickPointerID = -1;
  37893. // current joystick position
  37894. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  37895. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  37896. // origin joystick position
  37897. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  37898. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  37899. this._onPointerDownHandlerRef = function (evt) {
  37900. _this._onPointerDown(evt);
  37901. };
  37902. this._onPointerMoveHandlerRef = function (evt) {
  37903. _this._onPointerMove(evt);
  37904. };
  37905. this._onPointerOutHandlerRef = function (evt) {
  37906. _this._onPointerUp(evt);
  37907. };
  37908. this._onPointerUpHandlerRef = function (evt) {
  37909. _this._onPointerUp(evt);
  37910. };
  37911. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  37912. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  37913. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  37914. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  37915. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  37916. evt.preventDefault(); // Disables system menu
  37917. }, false);
  37918. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37919. }
  37920. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  37921. this._joystickSensibility = newJoystickSensibility;
  37922. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  37923. };
  37924. VirtualJoystick.prototype._onPointerDown = function (e) {
  37925. var positionOnScreenCondition;
  37926. e.preventDefault();
  37927. if (this._leftJoystick === true) {
  37928. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  37929. }
  37930. else {
  37931. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  37932. }
  37933. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  37934. // First contact will be dedicated to the virtual joystick
  37935. this._joystickPointerID = e.pointerId;
  37936. this._joystickPointerStartPos.x = e.clientX;
  37937. this._joystickPointerStartPos.y = e.clientY;
  37938. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  37939. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  37940. this._deltaJoystickVector.x = 0;
  37941. this._deltaJoystickVector.y = 0;
  37942. this.pressed = true;
  37943. this._touches.add(e.pointerId.toString(), e);
  37944. }
  37945. else {
  37946. // You can only trigger the action buttons with a joystick declared
  37947. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  37948. this._action();
  37949. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  37950. }
  37951. }
  37952. };
  37953. VirtualJoystick.prototype._onPointerMove = function (e) {
  37954. // If the current pointer is the one associated to the joystick (first touch contact)
  37955. if (this._joystickPointerID == e.pointerId) {
  37956. this._joystickPointerPos.x = e.clientX;
  37957. this._joystickPointerPos.y = e.clientY;
  37958. this._deltaJoystickVector = this._joystickPointerPos.clone();
  37959. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  37960. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  37961. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  37962. switch (this._axisTargetedByLeftAndRight) {
  37963. case JoystickAxis.X:
  37964. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  37965. break;
  37966. case JoystickAxis.Y:
  37967. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  37968. break;
  37969. case JoystickAxis.Z:
  37970. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  37971. break;
  37972. }
  37973. var directionUpDown = this.reverseUpDown ? 1 : -1;
  37974. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  37975. switch (this._axisTargetedByUpAndDown) {
  37976. case JoystickAxis.X:
  37977. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  37978. break;
  37979. case JoystickAxis.Y:
  37980. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  37981. break;
  37982. case JoystickAxis.Z:
  37983. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  37984. break;
  37985. }
  37986. }
  37987. else {
  37988. var data = this._touches.get(e.pointerId.toString());
  37989. if (data) {
  37990. data.x = e.clientX;
  37991. data.y = e.clientY;
  37992. }
  37993. }
  37994. };
  37995. VirtualJoystick.prototype._onPointerUp = function (e) {
  37996. if (this._joystickPointerID == e.pointerId) {
  37997. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  37998. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  37999. this._joystickPointerID = -1;
  38000. this.pressed = false;
  38001. }
  38002. else {
  38003. var touch = this._touches.get(e.pointerId.toString());
  38004. if (touch) {
  38005. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  38006. }
  38007. }
  38008. this._deltaJoystickVector.x = 0;
  38009. this._deltaJoystickVector.y = 0;
  38010. this._touches.remove(e.pointerId.toString());
  38011. };
  38012. /**
  38013. * Change the color of the virtual joystick
  38014. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  38015. */
  38016. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  38017. this._joystickColor = newColor;
  38018. };
  38019. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  38020. this._action = action;
  38021. };
  38022. // Define which axis you'd like to control for left & right
  38023. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  38024. switch (axis) {
  38025. case JoystickAxis.X:
  38026. case JoystickAxis.Y:
  38027. case JoystickAxis.Z:
  38028. this._axisTargetedByLeftAndRight = axis;
  38029. break;
  38030. default:
  38031. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  38032. break;
  38033. }
  38034. };
  38035. // Define which axis you'd like to control for up & down
  38036. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  38037. switch (axis) {
  38038. case JoystickAxis.X:
  38039. case JoystickAxis.Y:
  38040. case JoystickAxis.Z:
  38041. this._axisTargetedByUpAndDown = axis;
  38042. break;
  38043. default:
  38044. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  38045. break;
  38046. }
  38047. };
  38048. VirtualJoystick.prototype._clearCanvas = function () {
  38049. if (this._leftJoystick) {
  38050. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  38051. }
  38052. else {
  38053. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  38054. }
  38055. };
  38056. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  38057. var _this = this;
  38058. if (this.pressed) {
  38059. this._touches.forEach(function (touch) {
  38060. if (touch.pointerId === _this._joystickPointerID) {
  38061. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  38062. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  38063. VirtualJoystick.vjCanvasContext.beginPath();
  38064. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  38065. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  38066. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  38067. VirtualJoystick.vjCanvasContext.stroke();
  38068. VirtualJoystick.vjCanvasContext.closePath();
  38069. VirtualJoystick.vjCanvasContext.beginPath();
  38070. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  38071. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  38072. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  38073. VirtualJoystick.vjCanvasContext.stroke();
  38074. VirtualJoystick.vjCanvasContext.closePath();
  38075. VirtualJoystick.vjCanvasContext.beginPath();
  38076. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  38077. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  38078. VirtualJoystick.vjCanvasContext.stroke();
  38079. VirtualJoystick.vjCanvasContext.closePath();
  38080. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  38081. }
  38082. else {
  38083. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  38084. VirtualJoystick.vjCanvasContext.beginPath();
  38085. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  38086. VirtualJoystick.vjCanvasContext.beginPath();
  38087. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  38088. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  38089. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  38090. VirtualJoystick.vjCanvasContext.stroke();
  38091. VirtualJoystick.vjCanvasContext.closePath();
  38092. touch.prevX = touch.x;
  38093. touch.prevY = touch.y;
  38094. }
  38095. ;
  38096. });
  38097. }
  38098. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  38099. };
  38100. VirtualJoystick.prototype.releaseCanvas = function () {
  38101. if (VirtualJoystick.vjCanvas) {
  38102. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  38103. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  38104. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  38105. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  38106. window.removeEventListener("resize", this._onResize);
  38107. document.body.removeChild(VirtualJoystick.vjCanvas);
  38108. VirtualJoystick.vjCanvas = null;
  38109. }
  38110. };
  38111. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  38112. VirtualJoystick._globalJoystickIndex = 0;
  38113. return VirtualJoystick;
  38114. })();
  38115. BABYLON.VirtualJoystick = VirtualJoystick;
  38116. })(BABYLON || (BABYLON = {}));
  38117. var BABYLON;
  38118. (function (BABYLON) {
  38119. // We're mainly based on the logic defined into the FreeCamera code
  38120. var VirtualJoysticksCamera = (function (_super) {
  38121. __extends(VirtualJoysticksCamera, _super);
  38122. function VirtualJoysticksCamera(name, position, scene) {
  38123. _super.call(this, name, position, scene);
  38124. this.inputs.addVirtualJoystick();
  38125. }
  38126. return VirtualJoysticksCamera;
  38127. })(BABYLON.FreeCamera);
  38128. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  38129. })(BABYLON || (BABYLON = {}));
  38130. var BABYLON;
  38131. (function (BABYLON) {
  38132. var AnaglyphPostProcess = (function (_super) {
  38133. __extends(AnaglyphPostProcess, _super);
  38134. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38135. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  38136. }
  38137. return AnaglyphPostProcess;
  38138. })(BABYLON.PostProcess);
  38139. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  38140. })(BABYLON || (BABYLON = {}));
  38141. var BABYLON;
  38142. (function (BABYLON) {
  38143. var OutlineRenderer = (function () {
  38144. function OutlineRenderer(scene) {
  38145. this._scene = scene;
  38146. }
  38147. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  38148. var _this = this;
  38149. if (useOverlay === void 0) { useOverlay = false; }
  38150. var scene = this._scene;
  38151. var engine = this._scene.getEngine();
  38152. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38153. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  38154. return;
  38155. }
  38156. var mesh = subMesh.getRenderingMesh();
  38157. var material = subMesh.getMaterial();
  38158. engine.enableEffect(this._effect);
  38159. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  38160. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  38161. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  38162. // Bones
  38163. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38164. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38165. }
  38166. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  38167. // Alpha test
  38168. if (material && material.needAlphaTesting()) {
  38169. var alphaTexture = material.getAlphaTestTexture();
  38170. this._effect.setTexture("diffuseSampler", alphaTexture);
  38171. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38172. }
  38173. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  38174. };
  38175. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  38176. var defines = [];
  38177. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  38178. var mesh = subMesh.getMesh();
  38179. var material = subMesh.getMaterial();
  38180. // Alpha test
  38181. if (material && material.needAlphaTesting()) {
  38182. defines.push("#define ALPHATEST");
  38183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38184. attribs.push(BABYLON.VertexBuffer.UVKind);
  38185. defines.push("#define UV1");
  38186. }
  38187. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38188. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38189. defines.push("#define UV2");
  38190. }
  38191. }
  38192. // Bones
  38193. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38194. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38195. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38196. if (mesh.numBoneInfluencers > 4) {
  38197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38199. }
  38200. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38201. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38202. }
  38203. else {
  38204. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38205. }
  38206. // Instances
  38207. if (useInstances) {
  38208. defines.push("#define INSTANCES");
  38209. attribs.push("world0");
  38210. attribs.push("world1");
  38211. attribs.push("world2");
  38212. attribs.push("world3");
  38213. }
  38214. // Get correct effect
  38215. var join = defines.join("\n");
  38216. if (this._cachedDefines !== join) {
  38217. this._cachedDefines = join;
  38218. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  38219. }
  38220. return this._effect.isReady();
  38221. };
  38222. return OutlineRenderer;
  38223. })();
  38224. BABYLON.OutlineRenderer = OutlineRenderer;
  38225. })(BABYLON || (BABYLON = {}));
  38226. var BABYLON;
  38227. (function (BABYLON) {
  38228. var MeshAssetTask = (function () {
  38229. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  38230. this.name = name;
  38231. this.meshesNames = meshesNames;
  38232. this.rootUrl = rootUrl;
  38233. this.sceneFilename = sceneFilename;
  38234. this.isCompleted = false;
  38235. }
  38236. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38237. var _this = this;
  38238. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  38239. _this.loadedMeshes = meshes;
  38240. _this.loadedParticleSystems = particleSystems;
  38241. _this.loadedSkeletons = skeletons;
  38242. _this.isCompleted = true;
  38243. if (_this.onSuccess) {
  38244. _this.onSuccess(_this);
  38245. }
  38246. onSuccess();
  38247. }, null, function () {
  38248. if (_this.onError) {
  38249. _this.onError(_this);
  38250. }
  38251. onError();
  38252. });
  38253. };
  38254. return MeshAssetTask;
  38255. })();
  38256. BABYLON.MeshAssetTask = MeshAssetTask;
  38257. var TextFileAssetTask = (function () {
  38258. function TextFileAssetTask(name, url) {
  38259. this.name = name;
  38260. this.url = url;
  38261. this.isCompleted = false;
  38262. }
  38263. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38264. var _this = this;
  38265. BABYLON.Tools.LoadFile(this.url, function (data) {
  38266. _this.text = data;
  38267. _this.isCompleted = true;
  38268. if (_this.onSuccess) {
  38269. _this.onSuccess(_this);
  38270. }
  38271. onSuccess();
  38272. }, null, scene.database, false, function () {
  38273. if (_this.onError) {
  38274. _this.onError(_this);
  38275. }
  38276. onError();
  38277. });
  38278. };
  38279. return TextFileAssetTask;
  38280. })();
  38281. BABYLON.TextFileAssetTask = TextFileAssetTask;
  38282. var BinaryFileAssetTask = (function () {
  38283. function BinaryFileAssetTask(name, url) {
  38284. this.name = name;
  38285. this.url = url;
  38286. this.isCompleted = false;
  38287. }
  38288. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38289. var _this = this;
  38290. BABYLON.Tools.LoadFile(this.url, function (data) {
  38291. _this.data = data;
  38292. _this.isCompleted = true;
  38293. if (_this.onSuccess) {
  38294. _this.onSuccess(_this);
  38295. }
  38296. onSuccess();
  38297. }, null, scene.database, true, function () {
  38298. if (_this.onError) {
  38299. _this.onError(_this);
  38300. }
  38301. onError();
  38302. });
  38303. };
  38304. return BinaryFileAssetTask;
  38305. })();
  38306. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  38307. var ImageAssetTask = (function () {
  38308. function ImageAssetTask(name, url) {
  38309. this.name = name;
  38310. this.url = url;
  38311. this.isCompleted = false;
  38312. }
  38313. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38314. var _this = this;
  38315. var img = new Image();
  38316. img.onload = function () {
  38317. _this.image = img;
  38318. _this.isCompleted = true;
  38319. if (_this.onSuccess) {
  38320. _this.onSuccess(_this);
  38321. }
  38322. onSuccess();
  38323. };
  38324. img.onerror = function () {
  38325. if (_this.onError) {
  38326. _this.onError(_this);
  38327. }
  38328. onError();
  38329. };
  38330. img.src = this.url;
  38331. };
  38332. return ImageAssetTask;
  38333. })();
  38334. BABYLON.ImageAssetTask = ImageAssetTask;
  38335. var TextureAssetTask = (function () {
  38336. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  38337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38338. this.name = name;
  38339. this.url = url;
  38340. this.noMipmap = noMipmap;
  38341. this.invertY = invertY;
  38342. this.samplingMode = samplingMode;
  38343. this.isCompleted = false;
  38344. }
  38345. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38346. var _this = this;
  38347. var onload = function () {
  38348. _this.isCompleted = true;
  38349. if (_this.onSuccess) {
  38350. _this.onSuccess(_this);
  38351. }
  38352. onSuccess();
  38353. };
  38354. var onerror = function () {
  38355. if (_this.onError) {
  38356. _this.onError(_this);
  38357. }
  38358. onError();
  38359. };
  38360. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  38361. };
  38362. return TextureAssetTask;
  38363. })();
  38364. BABYLON.TextureAssetTask = TextureAssetTask;
  38365. var AssetsManager = (function () {
  38366. function AssetsManager(scene) {
  38367. this._tasks = new Array();
  38368. this._waitingTasksCount = 0;
  38369. this.useDefaultLoadingScreen = true;
  38370. this._scene = scene;
  38371. }
  38372. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  38373. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  38374. this._tasks.push(task);
  38375. return task;
  38376. };
  38377. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  38378. var task = new TextFileAssetTask(taskName, url);
  38379. this._tasks.push(task);
  38380. return task;
  38381. };
  38382. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  38383. var task = new BinaryFileAssetTask(taskName, url);
  38384. this._tasks.push(task);
  38385. return task;
  38386. };
  38387. AssetsManager.prototype.addImageTask = function (taskName, url) {
  38388. var task = new ImageAssetTask(taskName, url);
  38389. this._tasks.push(task);
  38390. return task;
  38391. };
  38392. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  38393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38394. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  38395. this._tasks.push(task);
  38396. return task;
  38397. };
  38398. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  38399. this._waitingTasksCount--;
  38400. if (this._waitingTasksCount === 0) {
  38401. if (this.onFinish) {
  38402. this.onFinish(this._tasks);
  38403. }
  38404. this._scene.getEngine().hideLoadingUI();
  38405. }
  38406. };
  38407. AssetsManager.prototype._runTask = function (task) {
  38408. var _this = this;
  38409. task.run(this._scene, function () {
  38410. if (_this.onTaskSuccess) {
  38411. _this.onTaskSuccess(task);
  38412. }
  38413. _this._decreaseWaitingTasksCount();
  38414. }, function () {
  38415. if (_this.onTaskError) {
  38416. _this.onTaskError(task);
  38417. }
  38418. _this._decreaseWaitingTasksCount();
  38419. });
  38420. };
  38421. AssetsManager.prototype.reset = function () {
  38422. this._tasks = new Array();
  38423. return this;
  38424. };
  38425. AssetsManager.prototype.load = function () {
  38426. this._waitingTasksCount = this._tasks.length;
  38427. if (this._waitingTasksCount === 0) {
  38428. if (this.onFinish) {
  38429. this.onFinish(this._tasks);
  38430. }
  38431. return this;
  38432. }
  38433. if (this.useDefaultLoadingScreen) {
  38434. this._scene.getEngine().displayLoadingUI();
  38435. }
  38436. for (var index = 0; index < this._tasks.length; index++) {
  38437. var task = this._tasks[index];
  38438. this._runTask(task);
  38439. }
  38440. return this;
  38441. };
  38442. return AssetsManager;
  38443. })();
  38444. BABYLON.AssetsManager = AssetsManager;
  38445. })(BABYLON || (BABYLON = {}));
  38446. var BABYLON;
  38447. (function (BABYLON) {
  38448. var VRCameraMetrics = (function () {
  38449. function VRCameraMetrics() {
  38450. this.compensateDistortion = true;
  38451. }
  38452. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  38453. get: function () {
  38454. return this.hResolution / (2 * this.vResolution);
  38455. },
  38456. enumerable: true,
  38457. configurable: true
  38458. });
  38459. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  38460. get: function () {
  38461. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  38462. },
  38463. enumerable: true,
  38464. configurable: true
  38465. });
  38466. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  38467. get: function () {
  38468. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  38469. var h = (4 * meters) / this.hScreenSize;
  38470. return BABYLON.Matrix.Translation(h, 0, 0);
  38471. },
  38472. enumerable: true,
  38473. configurable: true
  38474. });
  38475. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  38476. get: function () {
  38477. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  38478. var h = (4 * meters) / this.hScreenSize;
  38479. return BABYLON.Matrix.Translation(-h, 0, 0);
  38480. },
  38481. enumerable: true,
  38482. configurable: true
  38483. });
  38484. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  38485. get: function () {
  38486. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  38487. },
  38488. enumerable: true,
  38489. configurable: true
  38490. });
  38491. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  38492. get: function () {
  38493. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. VRCameraMetrics.GetDefault = function () {
  38499. var result = new VRCameraMetrics();
  38500. result.hResolution = 1280;
  38501. result.vResolution = 800;
  38502. result.hScreenSize = 0.149759993;
  38503. result.vScreenSize = 0.0935999975;
  38504. result.vScreenCenter = 0.0467999987,
  38505. result.eyeToScreenDistance = 0.0410000011;
  38506. result.lensSeparationDistance = 0.0635000020;
  38507. result.interpupillaryDistance = 0.0640000030;
  38508. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  38509. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  38510. result.postProcessScaleFactor = 1.714605507808412;
  38511. result.lensCenterOffset = 0.151976421;
  38512. return result;
  38513. };
  38514. return VRCameraMetrics;
  38515. })();
  38516. BABYLON.VRCameraMetrics = VRCameraMetrics;
  38517. })(BABYLON || (BABYLON = {}));
  38518. var BABYLON;
  38519. (function (BABYLON) {
  38520. var VRDeviceOrientationFreeCamera = (function (_super) {
  38521. __extends(VRDeviceOrientationFreeCamera, _super);
  38522. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  38523. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38524. _super.call(this, name, position, scene);
  38525. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38526. metrics.compensateDistortion = compensateDistortion;
  38527. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38528. this.inputs.addVRDeviceOrientation();
  38529. }
  38530. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  38531. return "VRDeviceOrientationFreeCamera";
  38532. };
  38533. return VRDeviceOrientationFreeCamera;
  38534. })(BABYLON.FreeCamera);
  38535. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  38536. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  38537. __extends(VRDeviceOrientationArcRotateCamera, _super);
  38538. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  38539. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38540. _super.call(this, name, alpha, beta, radius, target, scene);
  38541. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38542. metrics.compensateDistortion = compensateDistortion;
  38543. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38544. this.inputs.addVRDeviceOrientation();
  38545. }
  38546. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  38547. return "VRDeviceOrientationArcRotateCamera";
  38548. };
  38549. return VRDeviceOrientationArcRotateCamera;
  38550. })(BABYLON.ArcRotateCamera);
  38551. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  38552. })(BABYLON || (BABYLON = {}));
  38553. var BABYLON;
  38554. (function (BABYLON) {
  38555. var WebVRFreeCamera = (function (_super) {
  38556. __extends(WebVRFreeCamera, _super);
  38557. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  38558. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38559. _super.call(this, name, position, scene);
  38560. this._hmdDevice = null;
  38561. this._sensorDevice = null;
  38562. this._cacheState = null;
  38563. this._cacheQuaternion = new BABYLON.Quaternion();
  38564. this._cacheRotation = BABYLON.Vector3.Zero();
  38565. this._vrEnabled = false;
  38566. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38567. metrics.compensateDistortion = compensateDistortion;
  38568. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38569. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  38570. }
  38571. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  38572. var size = devices.length;
  38573. var i = 0;
  38574. // Reset devices.
  38575. this._sensorDevice = null;
  38576. this._hmdDevice = null;
  38577. // Search for a HmdDevice.
  38578. while (i < size && this._hmdDevice === null) {
  38579. if (devices[i] instanceof HMDVRDevice) {
  38580. this._hmdDevice = devices[i];
  38581. }
  38582. i++;
  38583. }
  38584. i = 0;
  38585. while (i < size && this._sensorDevice === null) {
  38586. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  38587. this._sensorDevice = devices[i];
  38588. }
  38589. i++;
  38590. }
  38591. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  38592. };
  38593. WebVRFreeCamera.prototype._checkInputs = function () {
  38594. if (this._vrEnabled) {
  38595. this._cacheState = this._sensorDevice.getState();
  38596. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  38597. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  38598. this.rotation.x = -this._cacheRotation.x;
  38599. this.rotation.y = -this._cacheRotation.y;
  38600. this.rotation.z = this._cacheRotation.z;
  38601. }
  38602. _super.prototype._checkInputs.call(this);
  38603. };
  38604. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38605. _super.prototype.attachControl.call(this, element, noPreventDefault);
  38606. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38607. if (navigator.getVRDevices) {
  38608. navigator.getVRDevices().then(this._getWebVRDevices);
  38609. }
  38610. else if (navigator.mozGetVRDevices) {
  38611. navigator.mozGetVRDevices(this._getWebVRDevices);
  38612. }
  38613. };
  38614. WebVRFreeCamera.prototype.detachControl = function (element) {
  38615. _super.prototype.detachControl.call(this, element);
  38616. this._vrEnabled = false;
  38617. };
  38618. WebVRFreeCamera.prototype.getTypeName = function () {
  38619. return "WebVRFreeCamera";
  38620. };
  38621. return WebVRFreeCamera;
  38622. })(BABYLON.FreeCamera);
  38623. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  38624. })(BABYLON || (BABYLON = {}));
  38625. var BABYLON;
  38626. (function (BABYLON) {
  38627. // Standard optimizations
  38628. var SceneOptimization = (function () {
  38629. function SceneOptimization(priority) {
  38630. if (priority === void 0) { priority = 0; }
  38631. this.priority = priority;
  38632. this.apply = function (scene) {
  38633. return true; // Return true if everything that can be done was applied
  38634. };
  38635. }
  38636. return SceneOptimization;
  38637. })();
  38638. BABYLON.SceneOptimization = SceneOptimization;
  38639. var TextureOptimization = (function (_super) {
  38640. __extends(TextureOptimization, _super);
  38641. function TextureOptimization(priority, maximumSize) {
  38642. var _this = this;
  38643. if (priority === void 0) { priority = 0; }
  38644. if (maximumSize === void 0) { maximumSize = 1024; }
  38645. _super.call(this, priority);
  38646. this.priority = priority;
  38647. this.maximumSize = maximumSize;
  38648. this.apply = function (scene) {
  38649. var allDone = true;
  38650. for (var index = 0; index < scene.textures.length; index++) {
  38651. var texture = scene.textures[index];
  38652. if (!texture.canRescale) {
  38653. continue;
  38654. }
  38655. var currentSize = texture.getSize();
  38656. var maxDimension = Math.max(currentSize.width, currentSize.height);
  38657. if (maxDimension > _this.maximumSize) {
  38658. texture.scale(0.5);
  38659. allDone = false;
  38660. }
  38661. }
  38662. return allDone;
  38663. };
  38664. }
  38665. return TextureOptimization;
  38666. })(SceneOptimization);
  38667. BABYLON.TextureOptimization = TextureOptimization;
  38668. var HardwareScalingOptimization = (function (_super) {
  38669. __extends(HardwareScalingOptimization, _super);
  38670. function HardwareScalingOptimization(priority, maximumScale) {
  38671. var _this = this;
  38672. if (priority === void 0) { priority = 0; }
  38673. if (maximumScale === void 0) { maximumScale = 2; }
  38674. _super.call(this, priority);
  38675. this.priority = priority;
  38676. this.maximumScale = maximumScale;
  38677. this._currentScale = 1;
  38678. this.apply = function (scene) {
  38679. _this._currentScale++;
  38680. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  38681. return _this._currentScale >= _this.maximumScale;
  38682. };
  38683. }
  38684. return HardwareScalingOptimization;
  38685. })(SceneOptimization);
  38686. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  38687. var ShadowsOptimization = (function (_super) {
  38688. __extends(ShadowsOptimization, _super);
  38689. function ShadowsOptimization() {
  38690. _super.apply(this, arguments);
  38691. this.apply = function (scene) {
  38692. scene.shadowsEnabled = false;
  38693. return true;
  38694. };
  38695. }
  38696. return ShadowsOptimization;
  38697. })(SceneOptimization);
  38698. BABYLON.ShadowsOptimization = ShadowsOptimization;
  38699. var PostProcessesOptimization = (function (_super) {
  38700. __extends(PostProcessesOptimization, _super);
  38701. function PostProcessesOptimization() {
  38702. _super.apply(this, arguments);
  38703. this.apply = function (scene) {
  38704. scene.postProcessesEnabled = false;
  38705. return true;
  38706. };
  38707. }
  38708. return PostProcessesOptimization;
  38709. })(SceneOptimization);
  38710. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  38711. var LensFlaresOptimization = (function (_super) {
  38712. __extends(LensFlaresOptimization, _super);
  38713. function LensFlaresOptimization() {
  38714. _super.apply(this, arguments);
  38715. this.apply = function (scene) {
  38716. scene.lensFlaresEnabled = false;
  38717. return true;
  38718. };
  38719. }
  38720. return LensFlaresOptimization;
  38721. })(SceneOptimization);
  38722. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  38723. var ParticlesOptimization = (function (_super) {
  38724. __extends(ParticlesOptimization, _super);
  38725. function ParticlesOptimization() {
  38726. _super.apply(this, arguments);
  38727. this.apply = function (scene) {
  38728. scene.particlesEnabled = false;
  38729. return true;
  38730. };
  38731. }
  38732. return ParticlesOptimization;
  38733. })(SceneOptimization);
  38734. BABYLON.ParticlesOptimization = ParticlesOptimization;
  38735. var RenderTargetsOptimization = (function (_super) {
  38736. __extends(RenderTargetsOptimization, _super);
  38737. function RenderTargetsOptimization() {
  38738. _super.apply(this, arguments);
  38739. this.apply = function (scene) {
  38740. scene.renderTargetsEnabled = false;
  38741. return true;
  38742. };
  38743. }
  38744. return RenderTargetsOptimization;
  38745. })(SceneOptimization);
  38746. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  38747. var MergeMeshesOptimization = (function (_super) {
  38748. __extends(MergeMeshesOptimization, _super);
  38749. function MergeMeshesOptimization() {
  38750. var _this = this;
  38751. _super.apply(this, arguments);
  38752. this._canBeMerged = function (abstractMesh) {
  38753. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  38754. return false;
  38755. }
  38756. var mesh = abstractMesh;
  38757. if (!mesh.isVisible || !mesh.isEnabled()) {
  38758. return false;
  38759. }
  38760. if (mesh.instances.length > 0) {
  38761. return false;
  38762. }
  38763. if (mesh.skeleton || mesh.hasLODLevels) {
  38764. return false;
  38765. }
  38766. if (mesh.parent) {
  38767. return false;
  38768. }
  38769. return true;
  38770. };
  38771. this.apply = function (scene, updateSelectionTree) {
  38772. var globalPool = scene.meshes.slice(0);
  38773. var globalLength = globalPool.length;
  38774. for (var index = 0; index < globalLength; index++) {
  38775. var currentPool = new Array();
  38776. var current = globalPool[index];
  38777. // Checks
  38778. if (!_this._canBeMerged(current)) {
  38779. continue;
  38780. }
  38781. currentPool.push(current);
  38782. // Find compatible meshes
  38783. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  38784. var otherMesh = globalPool[subIndex];
  38785. if (!_this._canBeMerged(otherMesh)) {
  38786. continue;
  38787. }
  38788. if (otherMesh.material !== current.material) {
  38789. continue;
  38790. }
  38791. if (otherMesh.checkCollisions !== current.checkCollisions) {
  38792. continue;
  38793. }
  38794. currentPool.push(otherMesh);
  38795. globalLength--;
  38796. globalPool.splice(subIndex, 1);
  38797. subIndex--;
  38798. }
  38799. if (currentPool.length < 2) {
  38800. continue;
  38801. }
  38802. // Merge meshes
  38803. BABYLON.Mesh.MergeMeshes(currentPool);
  38804. }
  38805. if (updateSelectionTree != undefined) {
  38806. if (updateSelectionTree) {
  38807. scene.createOrUpdateSelectionOctree();
  38808. }
  38809. }
  38810. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  38811. scene.createOrUpdateSelectionOctree();
  38812. }
  38813. return true;
  38814. };
  38815. }
  38816. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  38817. get: function () {
  38818. return MergeMeshesOptimization._UpdateSelectionTree;
  38819. },
  38820. set: function (value) {
  38821. MergeMeshesOptimization._UpdateSelectionTree = value;
  38822. },
  38823. enumerable: true,
  38824. configurable: true
  38825. });
  38826. MergeMeshesOptimization._UpdateSelectionTree = false;
  38827. return MergeMeshesOptimization;
  38828. })(SceneOptimization);
  38829. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  38830. // Options
  38831. var SceneOptimizerOptions = (function () {
  38832. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  38833. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  38834. if (trackerDuration === void 0) { trackerDuration = 2000; }
  38835. this.targetFrameRate = targetFrameRate;
  38836. this.trackerDuration = trackerDuration;
  38837. this.optimizations = new Array();
  38838. }
  38839. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  38840. var result = new SceneOptimizerOptions(targetFrameRate);
  38841. var priority = 0;
  38842. result.optimizations.push(new MergeMeshesOptimization(priority));
  38843. result.optimizations.push(new ShadowsOptimization(priority));
  38844. result.optimizations.push(new LensFlaresOptimization(priority));
  38845. // Next priority
  38846. priority++;
  38847. result.optimizations.push(new PostProcessesOptimization(priority));
  38848. result.optimizations.push(new ParticlesOptimization(priority));
  38849. // Next priority
  38850. priority++;
  38851. result.optimizations.push(new TextureOptimization(priority, 1024));
  38852. return result;
  38853. };
  38854. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  38855. var result = new SceneOptimizerOptions(targetFrameRate);
  38856. var priority = 0;
  38857. result.optimizations.push(new MergeMeshesOptimization(priority));
  38858. result.optimizations.push(new ShadowsOptimization(priority));
  38859. result.optimizations.push(new LensFlaresOptimization(priority));
  38860. // Next priority
  38861. priority++;
  38862. result.optimizations.push(new PostProcessesOptimization(priority));
  38863. result.optimizations.push(new ParticlesOptimization(priority));
  38864. // Next priority
  38865. priority++;
  38866. result.optimizations.push(new TextureOptimization(priority, 512));
  38867. // Next priority
  38868. priority++;
  38869. result.optimizations.push(new RenderTargetsOptimization(priority));
  38870. // Next priority
  38871. priority++;
  38872. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  38873. return result;
  38874. };
  38875. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  38876. var result = new SceneOptimizerOptions(targetFrameRate);
  38877. var priority = 0;
  38878. result.optimizations.push(new MergeMeshesOptimization(priority));
  38879. result.optimizations.push(new ShadowsOptimization(priority));
  38880. result.optimizations.push(new LensFlaresOptimization(priority));
  38881. // Next priority
  38882. priority++;
  38883. result.optimizations.push(new PostProcessesOptimization(priority));
  38884. result.optimizations.push(new ParticlesOptimization(priority));
  38885. // Next priority
  38886. priority++;
  38887. result.optimizations.push(new TextureOptimization(priority, 256));
  38888. // Next priority
  38889. priority++;
  38890. result.optimizations.push(new RenderTargetsOptimization(priority));
  38891. // Next priority
  38892. priority++;
  38893. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  38894. return result;
  38895. };
  38896. return SceneOptimizerOptions;
  38897. })();
  38898. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  38899. // Scene optimizer tool
  38900. var SceneOptimizer = (function () {
  38901. function SceneOptimizer() {
  38902. }
  38903. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  38904. // TODO: add an epsilon
  38905. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  38906. if (onSuccess) {
  38907. onSuccess();
  38908. }
  38909. return;
  38910. }
  38911. // Apply current level of optimizations
  38912. var allDone = true;
  38913. var noOptimizationApplied = true;
  38914. for (var index = 0; index < options.optimizations.length; index++) {
  38915. var optimization = options.optimizations[index];
  38916. if (optimization.priority === currentPriorityLevel) {
  38917. noOptimizationApplied = false;
  38918. allDone = allDone && optimization.apply(scene);
  38919. }
  38920. }
  38921. // If no optimization was applied, this is a failure :(
  38922. if (noOptimizationApplied) {
  38923. if (onFailure) {
  38924. onFailure();
  38925. }
  38926. return;
  38927. }
  38928. // If all optimizations were done, move to next level
  38929. if (allDone) {
  38930. currentPriorityLevel++;
  38931. }
  38932. // Let's the system running for a specific amount of time before checking FPS
  38933. scene.executeWhenReady(function () {
  38934. setTimeout(function () {
  38935. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  38936. }, options.trackerDuration);
  38937. });
  38938. };
  38939. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  38940. if (!options) {
  38941. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  38942. }
  38943. // Let's the system running for a specific amount of time before checking FPS
  38944. scene.executeWhenReady(function () {
  38945. setTimeout(function () {
  38946. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  38947. }, options.trackerDuration);
  38948. });
  38949. };
  38950. return SceneOptimizer;
  38951. })();
  38952. BABYLON.SceneOptimizer = SceneOptimizer;
  38953. })(BABYLON || (BABYLON = {}));
  38954. var BABYLON;
  38955. (function (BABYLON) {
  38956. var Internals;
  38957. (function (Internals) {
  38958. var MeshLODLevel = (function () {
  38959. function MeshLODLevel(distance, mesh) {
  38960. this.distance = distance;
  38961. this.mesh = mesh;
  38962. }
  38963. return MeshLODLevel;
  38964. })();
  38965. Internals.MeshLODLevel = MeshLODLevel;
  38966. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38967. })(BABYLON || (BABYLON = {}));
  38968. var BABYLON;
  38969. (function (BABYLON) {
  38970. var RawTexture = (function (_super) {
  38971. __extends(RawTexture, _super);
  38972. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  38973. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38974. if (invertY === void 0) { invertY = false; }
  38975. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38976. _super.call(this, null, scene, !generateMipMaps, invertY);
  38977. this.format = format;
  38978. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  38979. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38980. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38981. }
  38982. RawTexture.prototype.update = function (data) {
  38983. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  38984. };
  38985. // Statics
  38986. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38987. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38988. if (invertY === void 0) { invertY = false; }
  38989. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38990. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  38991. };
  38992. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38993. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38994. if (invertY === void 0) { invertY = false; }
  38995. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38996. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38997. };
  38998. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38999. if (generateMipMaps === void 0) { generateMipMaps = true; }
  39000. if (invertY === void 0) { invertY = false; }
  39001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39002. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  39003. };
  39004. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  39005. if (generateMipMaps === void 0) { generateMipMaps = true; }
  39006. if (invertY === void 0) { invertY = false; }
  39007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39008. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  39009. };
  39010. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  39011. if (generateMipMaps === void 0) { generateMipMaps = true; }
  39012. if (invertY === void 0) { invertY = false; }
  39013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39014. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  39015. };
  39016. return RawTexture;
  39017. })(BABYLON.Texture);
  39018. BABYLON.RawTexture = RawTexture;
  39019. })(BABYLON || (BABYLON = {}));
  39020. var BABYLON;
  39021. (function (BABYLON) {
  39022. var IndexedVector2 = (function (_super) {
  39023. __extends(IndexedVector2, _super);
  39024. function IndexedVector2(original, index) {
  39025. _super.call(this, original.x, original.y);
  39026. this.index = index;
  39027. }
  39028. return IndexedVector2;
  39029. })(BABYLON.Vector2);
  39030. var PolygonPoints = (function () {
  39031. function PolygonPoints() {
  39032. this.elements = new Array();
  39033. }
  39034. PolygonPoints.prototype.add = function (originalPoints) {
  39035. var _this = this;
  39036. var result = new Array();
  39037. originalPoints.forEach(function (point) {
  39038. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  39039. var newPoint = new IndexedVector2(point, _this.elements.length);
  39040. result.push(newPoint);
  39041. _this.elements.push(newPoint);
  39042. }
  39043. });
  39044. return result;
  39045. };
  39046. PolygonPoints.prototype.computeBounds = function () {
  39047. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  39048. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  39049. this.elements.forEach(function (point) {
  39050. // x
  39051. if (point.x < lmin.x) {
  39052. lmin.x = point.x;
  39053. }
  39054. else if (point.x > lmax.x) {
  39055. lmax.x = point.x;
  39056. }
  39057. // y
  39058. if (point.y < lmin.y) {
  39059. lmin.y = point.y;
  39060. }
  39061. else if (point.y > lmax.y) {
  39062. lmax.y = point.y;
  39063. }
  39064. });
  39065. return {
  39066. min: lmin,
  39067. max: lmax,
  39068. width: lmax.x - lmin.x,
  39069. height: lmax.y - lmin.y
  39070. };
  39071. };
  39072. return PolygonPoints;
  39073. })();
  39074. var Polygon = (function () {
  39075. function Polygon() {
  39076. }
  39077. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  39078. return [
  39079. new BABYLON.Vector2(xmin, ymin),
  39080. new BABYLON.Vector2(xmax, ymin),
  39081. new BABYLON.Vector2(xmax, ymax),
  39082. new BABYLON.Vector2(xmin, ymax)
  39083. ];
  39084. };
  39085. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  39086. if (cx === void 0) { cx = 0; }
  39087. if (cy === void 0) { cy = 0; }
  39088. if (numberOfSides === void 0) { numberOfSides = 32; }
  39089. var result = new Array();
  39090. var angle = 0;
  39091. var increment = (Math.PI * 2) / numberOfSides;
  39092. for (var i = 0; i < numberOfSides; i++) {
  39093. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  39094. angle -= increment;
  39095. }
  39096. return result;
  39097. };
  39098. Polygon.Parse = function (input) {
  39099. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  39100. var i, result = [];
  39101. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  39102. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  39103. }
  39104. return result;
  39105. };
  39106. Polygon.StartingAt = function (x, y) {
  39107. return BABYLON.Path2.StartingAt(x, y);
  39108. };
  39109. return Polygon;
  39110. })();
  39111. BABYLON.Polygon = Polygon;
  39112. var PolygonMeshBuilder = (function () {
  39113. function PolygonMeshBuilder(name, contours, scene) {
  39114. this._points = new PolygonPoints();
  39115. this._outlinepoints = new PolygonPoints();
  39116. this._holes = [];
  39117. if (!("poly2tri" in window)) {
  39118. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  39119. }
  39120. this._name = name;
  39121. this._scene = scene;
  39122. var points;
  39123. if (contours instanceof BABYLON.Path2) {
  39124. points = contours.getPoints();
  39125. }
  39126. else {
  39127. points = contours;
  39128. }
  39129. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  39130. this._outlinepoints.add(points);
  39131. }
  39132. PolygonMeshBuilder.prototype.addHole = function (hole) {
  39133. this._swctx.addHole(this._points.add(hole));
  39134. var holepoints = new PolygonPoints();
  39135. holepoints.add(hole);
  39136. this._holes.push(holepoints);
  39137. return this;
  39138. };
  39139. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  39140. var _this = this;
  39141. if (updatable === void 0) { updatable = false; }
  39142. var result = new BABYLON.Mesh(this._name, this._scene);
  39143. var normals = [];
  39144. var positions = [];
  39145. var uvs = [];
  39146. var bounds = this._points.computeBounds();
  39147. this._points.elements.forEach(function (p) {
  39148. normals.push(0, 1.0, 0);
  39149. positions.push(p.x, 0, p.y);
  39150. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  39151. });
  39152. var indices = [];
  39153. this._swctx.triangulate();
  39154. this._swctx.getTriangles().forEach(function (triangle) {
  39155. triangle.getPoints().forEach(function (point) {
  39156. indices.push(point.index);
  39157. });
  39158. });
  39159. if (depth > 0) {
  39160. var positionscount = (positions.length / 3); //get the current pointcount
  39161. this._points.elements.forEach(function (p) {
  39162. normals.push(0, -1.0, 0);
  39163. positions.push(p.x, -depth, p.y);
  39164. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  39165. });
  39166. var p1; //we need to change order of point so the triangles are made in the rigth way.
  39167. var p2;
  39168. var poscounter = 0;
  39169. this._swctx.getTriangles().forEach(function (triangle) {
  39170. triangle.getPoints().forEach(function (point) {
  39171. switch (poscounter) {
  39172. case 0:
  39173. p1 = point;
  39174. break;
  39175. case 1:
  39176. p2 = point;
  39177. break;
  39178. case 2:
  39179. indices.push(point.index + positionscount);
  39180. indices.push(p2.index + positionscount);
  39181. indices.push(p1.index + positionscount);
  39182. poscounter = -1;
  39183. break;
  39184. }
  39185. poscounter++;
  39186. //indices.push((<IndexedVector2>point).index + positionscount);
  39187. });
  39188. });
  39189. //Add the sides
  39190. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  39191. this._holes.forEach(function (hole) {
  39192. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  39193. });
  39194. }
  39195. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  39196. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  39197. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  39198. result.setIndices(indices);
  39199. return result;
  39200. };
  39201. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  39202. var StartIndex = positions.length / 3;
  39203. var ulength = 0;
  39204. for (var i = 0; i < points.elements.length; i++) {
  39205. var p = points.elements[i];
  39206. var p1;
  39207. if ((i + 1) > points.elements.length - 1) {
  39208. p1 = points.elements[0];
  39209. }
  39210. else {
  39211. p1 = points.elements[i + 1];
  39212. }
  39213. positions.push(p.x, 0, p.y);
  39214. positions.push(p.x, -depth, p.y);
  39215. positions.push(p1.x, 0, p1.y);
  39216. positions.push(p1.x, -depth, p1.y);
  39217. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  39218. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  39219. var v3 = v2.subtract(v1);
  39220. var v4 = new BABYLON.Vector3(0, 1, 0);
  39221. var vn = BABYLON.Vector3.Cross(v3, v4);
  39222. vn = vn.normalize();
  39223. uvs.push(ulength / bounds.width, 0);
  39224. uvs.push(ulength / bounds.width, 1);
  39225. ulength += v3.length();
  39226. uvs.push((ulength / bounds.width), 0);
  39227. uvs.push((ulength / bounds.width), 1);
  39228. if (!flip) {
  39229. normals.push(-vn.x, -vn.y, -vn.z);
  39230. normals.push(-vn.x, -vn.y, -vn.z);
  39231. normals.push(-vn.x, -vn.y, -vn.z);
  39232. normals.push(-vn.x, -vn.y, -vn.z);
  39233. indices.push(StartIndex);
  39234. indices.push(StartIndex + 1);
  39235. indices.push(StartIndex + 2);
  39236. indices.push(StartIndex + 1);
  39237. indices.push(StartIndex + 3);
  39238. indices.push(StartIndex + 2);
  39239. }
  39240. else {
  39241. normals.push(vn.x, vn.y, vn.z);
  39242. normals.push(vn.x, vn.y, vn.z);
  39243. normals.push(vn.x, vn.y, vn.z);
  39244. normals.push(vn.x, vn.y, vn.z);
  39245. indices.push(StartIndex);
  39246. indices.push(StartIndex + 2);
  39247. indices.push(StartIndex + 1);
  39248. indices.push(StartIndex + 1);
  39249. indices.push(StartIndex + 2);
  39250. indices.push(StartIndex + 3);
  39251. }
  39252. StartIndex += 4;
  39253. }
  39254. ;
  39255. };
  39256. return PolygonMeshBuilder;
  39257. })();
  39258. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  39259. })(BABYLON || (BABYLON = {}));
  39260. var BABYLON;
  39261. (function (BABYLON) {
  39262. var Octree = (function () {
  39263. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  39264. if (maxDepth === void 0) { maxDepth = 2; }
  39265. this.maxDepth = maxDepth;
  39266. this.dynamicContent = new Array();
  39267. this._maxBlockCapacity = maxBlockCapacity || 64;
  39268. this._selectionContent = new BABYLON.SmartArray(1024);
  39269. this._creationFunc = creationFunc;
  39270. }
  39271. // Methods
  39272. Octree.prototype.update = function (worldMin, worldMax, entries) {
  39273. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  39274. };
  39275. Octree.prototype.addMesh = function (entry) {
  39276. for (var index = 0; index < this.blocks.length; index++) {
  39277. var block = this.blocks[index];
  39278. block.addEntry(entry);
  39279. }
  39280. };
  39281. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  39282. this._selectionContent.reset();
  39283. for (var index = 0; index < this.blocks.length; index++) {
  39284. var block = this.blocks[index];
  39285. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  39286. }
  39287. if (allowDuplicate) {
  39288. this._selectionContent.concat(this.dynamicContent);
  39289. }
  39290. else {
  39291. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  39292. }
  39293. return this._selectionContent;
  39294. };
  39295. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  39296. this._selectionContent.reset();
  39297. for (var index = 0; index < this.blocks.length; index++) {
  39298. var block = this.blocks[index];
  39299. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  39300. }
  39301. if (allowDuplicate) {
  39302. this._selectionContent.concat(this.dynamicContent);
  39303. }
  39304. else {
  39305. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  39306. }
  39307. return this._selectionContent;
  39308. };
  39309. Octree.prototype.intersectsRay = function (ray) {
  39310. this._selectionContent.reset();
  39311. for (var index = 0; index < this.blocks.length; index++) {
  39312. var block = this.blocks[index];
  39313. block.intersectsRay(ray, this._selectionContent);
  39314. }
  39315. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  39316. return this._selectionContent;
  39317. };
  39318. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  39319. target.blocks = new Array();
  39320. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  39321. // Segmenting space
  39322. for (var x = 0; x < 2; x++) {
  39323. for (var y = 0; y < 2; y++) {
  39324. for (var z = 0; z < 2; z++) {
  39325. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  39326. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  39327. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  39328. block.addEntries(entries);
  39329. target.blocks.push(block);
  39330. }
  39331. }
  39332. }
  39333. };
  39334. Octree.CreationFuncForMeshes = function (entry, block) {
  39335. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  39336. block.entries.push(entry);
  39337. }
  39338. };
  39339. Octree.CreationFuncForSubMeshes = function (entry, block) {
  39340. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  39341. block.entries.push(entry);
  39342. }
  39343. };
  39344. return Octree;
  39345. })();
  39346. BABYLON.Octree = Octree;
  39347. })(BABYLON || (BABYLON = {}));
  39348. var BABYLON;
  39349. (function (BABYLON) {
  39350. var OctreeBlock = (function () {
  39351. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  39352. this.entries = new Array();
  39353. this._boundingVectors = new Array();
  39354. this._capacity = capacity;
  39355. this._depth = depth;
  39356. this._maxDepth = maxDepth;
  39357. this._creationFunc = creationFunc;
  39358. this._minPoint = minPoint;
  39359. this._maxPoint = maxPoint;
  39360. this._boundingVectors.push(minPoint.clone());
  39361. this._boundingVectors.push(maxPoint.clone());
  39362. this._boundingVectors.push(minPoint.clone());
  39363. this._boundingVectors[2].x = maxPoint.x;
  39364. this._boundingVectors.push(minPoint.clone());
  39365. this._boundingVectors[3].y = maxPoint.y;
  39366. this._boundingVectors.push(minPoint.clone());
  39367. this._boundingVectors[4].z = maxPoint.z;
  39368. this._boundingVectors.push(maxPoint.clone());
  39369. this._boundingVectors[5].z = minPoint.z;
  39370. this._boundingVectors.push(maxPoint.clone());
  39371. this._boundingVectors[6].x = minPoint.x;
  39372. this._boundingVectors.push(maxPoint.clone());
  39373. this._boundingVectors[7].y = minPoint.y;
  39374. }
  39375. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  39376. // Property
  39377. get: function () {
  39378. return this._capacity;
  39379. },
  39380. enumerable: true,
  39381. configurable: true
  39382. });
  39383. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  39384. get: function () {
  39385. return this._minPoint;
  39386. },
  39387. enumerable: true,
  39388. configurable: true
  39389. });
  39390. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  39391. get: function () {
  39392. return this._maxPoint;
  39393. },
  39394. enumerable: true,
  39395. configurable: true
  39396. });
  39397. // Methods
  39398. OctreeBlock.prototype.addEntry = function (entry) {
  39399. if (this.blocks) {
  39400. for (var index = 0; index < this.blocks.length; index++) {
  39401. var block = this.blocks[index];
  39402. block.addEntry(entry);
  39403. }
  39404. return;
  39405. }
  39406. this._creationFunc(entry, this);
  39407. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  39408. this.createInnerBlocks();
  39409. }
  39410. };
  39411. OctreeBlock.prototype.addEntries = function (entries) {
  39412. for (var index = 0; index < entries.length; index++) {
  39413. var mesh = entries[index];
  39414. this.addEntry(mesh);
  39415. }
  39416. };
  39417. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  39418. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  39419. if (this.blocks) {
  39420. for (var index = 0; index < this.blocks.length; index++) {
  39421. var block = this.blocks[index];
  39422. block.select(frustumPlanes, selection, allowDuplicate);
  39423. }
  39424. return;
  39425. }
  39426. if (allowDuplicate) {
  39427. selection.concat(this.entries);
  39428. }
  39429. else {
  39430. selection.concatWithNoDuplicate(this.entries);
  39431. }
  39432. }
  39433. };
  39434. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  39435. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  39436. if (this.blocks) {
  39437. for (var index = 0; index < this.blocks.length; index++) {
  39438. var block = this.blocks[index];
  39439. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  39440. }
  39441. return;
  39442. }
  39443. if (allowDuplicate) {
  39444. selection.concat(this.entries);
  39445. }
  39446. else {
  39447. selection.concatWithNoDuplicate(this.entries);
  39448. }
  39449. }
  39450. };
  39451. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  39452. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  39453. if (this.blocks) {
  39454. for (var index = 0; index < this.blocks.length; index++) {
  39455. var block = this.blocks[index];
  39456. block.intersectsRay(ray, selection);
  39457. }
  39458. return;
  39459. }
  39460. selection.concatWithNoDuplicate(this.entries);
  39461. }
  39462. };
  39463. OctreeBlock.prototype.createInnerBlocks = function () {
  39464. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  39465. };
  39466. return OctreeBlock;
  39467. })();
  39468. BABYLON.OctreeBlock = OctreeBlock;
  39469. })(BABYLON || (BABYLON = {}));
  39470. var BABYLON;
  39471. (function (BABYLON) {
  39472. var BlurPostProcess = (function (_super) {
  39473. __extends(BlurPostProcess, _super);
  39474. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  39475. var _this = this;
  39476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39477. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  39478. this.direction = direction;
  39479. this.blurWidth = blurWidth;
  39480. this.onApply = function (effect) {
  39481. effect.setFloat2("screenSize", _this.width, _this.height);
  39482. effect.setVector2("direction", _this.direction);
  39483. effect.setFloat("blurWidth", _this.blurWidth);
  39484. };
  39485. }
  39486. return BlurPostProcess;
  39487. })(BABYLON.PostProcess);
  39488. BABYLON.BlurPostProcess = BlurPostProcess;
  39489. })(BABYLON || (BABYLON = {}));
  39490. var BABYLON;
  39491. (function (BABYLON) {
  39492. var RefractionPostProcess = (function (_super) {
  39493. __extends(RefractionPostProcess, _super);
  39494. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  39495. var _this = this;
  39496. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  39497. this.color = color;
  39498. this.depth = depth;
  39499. this.colorLevel = colorLevel;
  39500. this.onActivate = function (cam) {
  39501. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  39502. };
  39503. this.onApply = function (effect) {
  39504. effect.setColor3("baseColor", _this.color);
  39505. effect.setFloat("depth", _this.depth);
  39506. effect.setFloat("colorLevel", _this.colorLevel);
  39507. effect.setTexture("refractionSampler", _this._refRexture);
  39508. };
  39509. }
  39510. // Methods
  39511. RefractionPostProcess.prototype.dispose = function (camera) {
  39512. if (this._refRexture) {
  39513. this._refRexture.dispose();
  39514. }
  39515. _super.prototype.dispose.call(this, camera);
  39516. };
  39517. return RefractionPostProcess;
  39518. })(BABYLON.PostProcess);
  39519. BABYLON.RefractionPostProcess = RefractionPostProcess;
  39520. })(BABYLON || (BABYLON = {}));
  39521. var BABYLON;
  39522. (function (BABYLON) {
  39523. var BlackAndWhitePostProcess = (function (_super) {
  39524. __extends(BlackAndWhitePostProcess, _super);
  39525. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  39526. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  39527. }
  39528. return BlackAndWhitePostProcess;
  39529. })(BABYLON.PostProcess);
  39530. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  39531. })(BABYLON || (BABYLON = {}));
  39532. var BABYLON;
  39533. (function (BABYLON) {
  39534. var ConvolutionPostProcess = (function (_super) {
  39535. __extends(ConvolutionPostProcess, _super);
  39536. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  39537. var _this = this;
  39538. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  39539. this.kernel = kernel;
  39540. this.onApply = function (effect) {
  39541. effect.setFloat2("screenSize", _this.width, _this.height);
  39542. effect.setArray("kernel", _this.kernel);
  39543. };
  39544. }
  39545. // Statics
  39546. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  39547. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  39548. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  39549. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  39550. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  39551. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  39552. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  39553. return ConvolutionPostProcess;
  39554. })(BABYLON.PostProcess);
  39555. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  39556. })(BABYLON || (BABYLON = {}));
  39557. var BABYLON;
  39558. (function (BABYLON) {
  39559. var FilterPostProcess = (function (_super) {
  39560. __extends(FilterPostProcess, _super);
  39561. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  39562. var _this = this;
  39563. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  39564. this.kernelMatrix = kernelMatrix;
  39565. this.onApply = function (effect) {
  39566. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  39567. };
  39568. }
  39569. return FilterPostProcess;
  39570. })(BABYLON.PostProcess);
  39571. BABYLON.FilterPostProcess = FilterPostProcess;
  39572. })(BABYLON || (BABYLON = {}));
  39573. var BABYLON;
  39574. (function (BABYLON) {
  39575. var FxaaPostProcess = (function (_super) {
  39576. __extends(FxaaPostProcess, _super);
  39577. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  39578. var _this = this;
  39579. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  39580. this.onSizeChanged = function () {
  39581. _this.texelWidth = 1.0 / _this.width;
  39582. _this.texelHeight = 1.0 / _this.height;
  39583. };
  39584. this.onApply = function (effect) {
  39585. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  39586. };
  39587. }
  39588. return FxaaPostProcess;
  39589. })(BABYLON.PostProcess);
  39590. BABYLON.FxaaPostProcess = FxaaPostProcess;
  39591. })(BABYLON || (BABYLON = {}));
  39592. var BABYLON;
  39593. (function (BABYLON) {
  39594. var StereoscopicInterlacePostProcess = (function (_super) {
  39595. __extends(StereoscopicInterlacePostProcess, _super);
  39596. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  39597. var _this = this;
  39598. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  39599. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  39600. this.onSizeChanged = function () {
  39601. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  39602. };
  39603. this.onApply = function (effect) {
  39604. effect.setTextureFromPostProcess("camASampler", postProcessA);
  39605. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  39606. };
  39607. }
  39608. return StereoscopicInterlacePostProcess;
  39609. })(BABYLON.PostProcess);
  39610. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  39611. })(BABYLON || (BABYLON = {}));
  39612. var BABYLON;
  39613. (function (BABYLON) {
  39614. var LensFlare = (function () {
  39615. function LensFlare(size, position, color, imgUrl, system) {
  39616. this.size = size;
  39617. this.position = position;
  39618. this.dispose = function () {
  39619. if (this.texture) {
  39620. this.texture.dispose();
  39621. }
  39622. // Remove from scene
  39623. var index = this._system.lensFlares.indexOf(this);
  39624. this._system.lensFlares.splice(index, 1);
  39625. };
  39626. this.color = color || new BABYLON.Color3(1, 1, 1);
  39627. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  39628. this._system = system;
  39629. system.lensFlares.push(this);
  39630. }
  39631. return LensFlare;
  39632. })();
  39633. BABYLON.LensFlare = LensFlare;
  39634. })(BABYLON || (BABYLON = {}));
  39635. var BABYLON;
  39636. (function (BABYLON) {
  39637. var LensFlareSystem = (function () {
  39638. function LensFlareSystem(name, emitter, scene) {
  39639. this.name = name;
  39640. this.lensFlares = new Array();
  39641. this.borderLimit = 300;
  39642. this.layerMask = 0x0FFFFFFF;
  39643. this._vertexDeclaration = [2];
  39644. this._vertexStrideSize = 2 * 4;
  39645. this._isEnabled = true;
  39646. this._scene = scene;
  39647. this._emitter = emitter;
  39648. this.id = name;
  39649. scene.lensFlareSystems.push(this);
  39650. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  39651. // VBO
  39652. var vertices = [];
  39653. vertices.push(1, 1);
  39654. vertices.push(-1, 1);
  39655. vertices.push(-1, -1);
  39656. vertices.push(1, -1);
  39657. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  39658. // Indices
  39659. var indices = [];
  39660. indices.push(0);
  39661. indices.push(1);
  39662. indices.push(2);
  39663. indices.push(0);
  39664. indices.push(2);
  39665. indices.push(3);
  39666. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39667. // Effects
  39668. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  39669. }
  39670. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  39671. get: function () {
  39672. return this._isEnabled;
  39673. },
  39674. set: function (value) {
  39675. this._isEnabled = value;
  39676. },
  39677. enumerable: true,
  39678. configurable: true
  39679. });
  39680. LensFlareSystem.prototype.getScene = function () {
  39681. return this._scene;
  39682. };
  39683. LensFlareSystem.prototype.getEmitter = function () {
  39684. return this._emitter;
  39685. };
  39686. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  39687. this._emitter = newEmitter;
  39688. };
  39689. LensFlareSystem.prototype.getEmitterPosition = function () {
  39690. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  39691. };
  39692. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  39693. var position = this.getEmitterPosition();
  39694. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  39695. this._positionX = position.x;
  39696. this._positionY = position.y;
  39697. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  39698. if (position.z > 0) {
  39699. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  39700. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  39701. return true;
  39702. }
  39703. }
  39704. return false;
  39705. };
  39706. LensFlareSystem.prototype._isVisible = function () {
  39707. if (!this._isEnabled) {
  39708. return false;
  39709. }
  39710. var emitterPosition = this.getEmitterPosition();
  39711. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  39712. var distance = direction.length();
  39713. direction.normalize();
  39714. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  39715. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  39716. return !pickInfo.hit || pickInfo.distance > distance;
  39717. };
  39718. LensFlareSystem.prototype.render = function () {
  39719. if (!this._effect.isReady())
  39720. return false;
  39721. var engine = this._scene.getEngine();
  39722. var viewport = this._scene.activeCamera.viewport;
  39723. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  39724. // Position
  39725. if (!this.computeEffectivePosition(globalViewport)) {
  39726. return false;
  39727. }
  39728. // Visibility
  39729. if (!this._isVisible()) {
  39730. return false;
  39731. }
  39732. // Intensity
  39733. var awayX;
  39734. var awayY;
  39735. if (this._positionX < this.borderLimit + globalViewport.x) {
  39736. awayX = this.borderLimit + globalViewport.x - this._positionX;
  39737. }
  39738. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  39739. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  39740. }
  39741. else {
  39742. awayX = 0;
  39743. }
  39744. if (this._positionY < this.borderLimit + globalViewport.y) {
  39745. awayY = this.borderLimit + globalViewport.y - this._positionY;
  39746. }
  39747. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  39748. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  39749. }
  39750. else {
  39751. awayY = 0;
  39752. }
  39753. var away = (awayX > awayY) ? awayX : awayY;
  39754. if (away > this.borderLimit) {
  39755. away = this.borderLimit;
  39756. }
  39757. var intensity = 1.0 - (away / this.borderLimit);
  39758. if (intensity < 0) {
  39759. return false;
  39760. }
  39761. if (intensity > 1.0) {
  39762. intensity = 1.0;
  39763. }
  39764. // Position
  39765. var centerX = globalViewport.x + globalViewport.width / 2;
  39766. var centerY = globalViewport.y + globalViewport.height / 2;
  39767. var distX = centerX - this._positionX;
  39768. var distY = centerY - this._positionY;
  39769. // Effects
  39770. engine.enableEffect(this._effect);
  39771. engine.setState(false);
  39772. engine.setDepthBuffer(false);
  39773. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  39774. // VBOs
  39775. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  39776. // Flares
  39777. for (var index = 0; index < this.lensFlares.length; index++) {
  39778. var flare = this.lensFlares[index];
  39779. var x = centerX - (distX * flare.position);
  39780. var y = centerY - (distY * flare.position);
  39781. var cw = flare.size;
  39782. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  39783. var cx = 2 * (x / globalViewport.width) - 1.0;
  39784. var cy = 1.0 - 2 * (y / globalViewport.height);
  39785. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  39786. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  39787. // Texture
  39788. this._effect.setTexture("textureSampler", flare.texture);
  39789. // Color
  39790. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  39791. // Draw order
  39792. engine.draw(true, 0, 6);
  39793. }
  39794. engine.setDepthBuffer(true);
  39795. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39796. return true;
  39797. };
  39798. LensFlareSystem.prototype.dispose = function () {
  39799. if (this._vertexBuffer) {
  39800. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  39801. this._vertexBuffer = null;
  39802. }
  39803. if (this._indexBuffer) {
  39804. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39805. this._indexBuffer = null;
  39806. }
  39807. while (this.lensFlares.length) {
  39808. this.lensFlares[0].dispose();
  39809. }
  39810. // Remove from scene
  39811. var index = this._scene.lensFlareSystems.indexOf(this);
  39812. this._scene.lensFlareSystems.splice(index, 1);
  39813. };
  39814. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  39815. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  39816. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  39817. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  39818. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  39819. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  39820. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  39821. var parsedFlare = parsedLensFlareSystem.flares[index];
  39822. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  39823. }
  39824. return lensFlareSystem;
  39825. };
  39826. LensFlareSystem.prototype.serialize = function () {
  39827. var serializationObject = {};
  39828. serializationObject.id = this.id;
  39829. serializationObject.name = this.name;
  39830. serializationObject.emitterId = this.getEmitter().id;
  39831. serializationObject.borderLimit = this.borderLimit;
  39832. serializationObject.flares = [];
  39833. for (var index = 0; index < this.lensFlares.length; index++) {
  39834. var flare = this.lensFlares[index];
  39835. serializationObject.flares.push({
  39836. size: flare.size,
  39837. position: flare.position,
  39838. color: flare.color.asArray(),
  39839. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  39840. });
  39841. }
  39842. return serializationObject;
  39843. };
  39844. return LensFlareSystem;
  39845. })();
  39846. BABYLON.LensFlareSystem = LensFlareSystem;
  39847. })(BABYLON || (BABYLON = {}));
  39848. var BABYLON;
  39849. (function (BABYLON) {
  39850. // We're mainly based on the logic defined into the FreeCamera code
  39851. var DeviceOrientationCamera = (function (_super) {
  39852. __extends(DeviceOrientationCamera, _super);
  39853. //-- end properties for backward compatibility for inputs
  39854. function DeviceOrientationCamera(name, position, scene) {
  39855. _super.call(this, name, position, scene);
  39856. this.inputs.addDeviceOrientation();
  39857. }
  39858. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  39859. //-- Begin properties for backward compatibility for inputs
  39860. get: function () {
  39861. var gamepad = this.inputs.attached["deviceOrientation"];
  39862. if (gamepad)
  39863. return gamepad.angularSensibility;
  39864. },
  39865. set: function (value) {
  39866. var gamepad = this.inputs.attached["deviceOrientation"];
  39867. if (gamepad)
  39868. gamepad.angularSensibility = value;
  39869. },
  39870. enumerable: true,
  39871. configurable: true
  39872. });
  39873. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  39874. get: function () {
  39875. var gamepad = this.inputs.attached["deviceOrientation"];
  39876. if (gamepad)
  39877. return gamepad.moveSensibility;
  39878. },
  39879. set: function (value) {
  39880. var gamepad = this.inputs.attached["deviceOrientation"];
  39881. if (gamepad)
  39882. gamepad.moveSensibility = value;
  39883. },
  39884. enumerable: true,
  39885. configurable: true
  39886. });
  39887. DeviceOrientationCamera.prototype.getTypeName = function () {
  39888. return "DeviceOrientationCamera";
  39889. };
  39890. return DeviceOrientationCamera;
  39891. })(BABYLON.FreeCamera);
  39892. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  39893. })(BABYLON || (BABYLON = {}));
  39894. var BABYLON;
  39895. (function (BABYLON) {
  39896. // We're mainly based on the logic defined into the FreeCamera code
  39897. var UniversalCamera = (function (_super) {
  39898. __extends(UniversalCamera, _super);
  39899. //-- end properties for backward compatibility for inputs
  39900. function UniversalCamera(name, position, scene) {
  39901. _super.call(this, name, position, scene);
  39902. this.inputs.addGamepad();
  39903. }
  39904. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  39905. //-- Begin properties for backward compatibility for inputs
  39906. get: function () {
  39907. var gamepad = this.inputs.attached["gamepad"];
  39908. if (gamepad)
  39909. return gamepad.gamepadAngularSensibility;
  39910. },
  39911. set: function (value) {
  39912. var gamepad = this.inputs.attached["gamepad"];
  39913. if (gamepad)
  39914. gamepad.gamepadAngularSensibility = value;
  39915. },
  39916. enumerable: true,
  39917. configurable: true
  39918. });
  39919. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  39920. get: function () {
  39921. var gamepad = this.inputs.attached["gamepad"];
  39922. if (gamepad)
  39923. return gamepad.gamepadMoveSensibility;
  39924. },
  39925. set: function (value) {
  39926. var gamepad = this.inputs.attached["gamepad"];
  39927. if (gamepad)
  39928. gamepad.gamepadMoveSensibility = value;
  39929. },
  39930. enumerable: true,
  39931. configurable: true
  39932. });
  39933. UniversalCamera.prototype.getTypeName = function () {
  39934. return "UniversalCamera";
  39935. };
  39936. return UniversalCamera;
  39937. })(BABYLON.TouchCamera);
  39938. BABYLON.UniversalCamera = UniversalCamera;
  39939. })(BABYLON || (BABYLON = {}));
  39940. var BABYLON;
  39941. (function (BABYLON) {
  39942. var Gamepads = (function () {
  39943. function Gamepads(ongamedpadconnected) {
  39944. var _this = this;
  39945. this.babylonGamepads = [];
  39946. this.oneGamepadConnected = false;
  39947. this.isMonitoring = false;
  39948. this.gamepadEventSupported = 'GamepadEvent' in window;
  39949. this.gamepadSupportAvailable = (navigator.getGamepads ||
  39950. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  39951. this._callbackGamepadConnected = ongamedpadconnected;
  39952. if (this.gamepadSupportAvailable) {
  39953. // Checking if the gamepad connected event is supported (like in Firefox)
  39954. if (this.gamepadEventSupported) {
  39955. this._onGamepadConnectedEvent = function (evt) {
  39956. _this._onGamepadConnected(evt);
  39957. };
  39958. this._onGamepadDisonnectedEvent = function (evt) {
  39959. _this._onGamepadDisconnected(evt);
  39960. };
  39961. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39962. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39963. }
  39964. else {
  39965. this._startMonitoringGamepads();
  39966. }
  39967. }
  39968. }
  39969. Gamepads.prototype.dispose = function () {
  39970. if (Gamepads.gamepadDOMInfo) {
  39971. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39972. }
  39973. if (this._onGamepadConnectedEvent) {
  39974. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39975. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39976. this._onGamepadConnectedEvent = null;
  39977. this._onGamepadDisonnectedEvent = null;
  39978. }
  39979. };
  39980. Gamepads.prototype._onGamepadConnected = function (evt) {
  39981. var newGamepad = this._addNewGamepad(evt.gamepad);
  39982. if (this._callbackGamepadConnected)
  39983. this._callbackGamepadConnected(newGamepad);
  39984. this._startMonitoringGamepads();
  39985. };
  39986. Gamepads.prototype._addNewGamepad = function (gamepad) {
  39987. if (!this.oneGamepadConnected) {
  39988. this.oneGamepadConnected = true;
  39989. if (Gamepads.gamepadDOMInfo) {
  39990. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39991. Gamepads.gamepadDOMInfo = null;
  39992. }
  39993. }
  39994. var newGamepad;
  39995. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  39996. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  39997. }
  39998. else {
  39999. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  40000. }
  40001. this.babylonGamepads.push(newGamepad);
  40002. return newGamepad;
  40003. };
  40004. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  40005. // Remove the gamepad from the list of gamepads to monitor.
  40006. for (var i in this.babylonGamepads) {
  40007. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  40008. this.babylonGamepads.splice(+i, 1);
  40009. break;
  40010. }
  40011. }
  40012. // If no gamepads are left, stop the polling loop.
  40013. if (this.babylonGamepads.length == 0) {
  40014. this._stopMonitoringGamepads();
  40015. }
  40016. };
  40017. Gamepads.prototype._startMonitoringGamepads = function () {
  40018. if (!this.isMonitoring) {
  40019. this.isMonitoring = true;
  40020. this._checkGamepadsStatus();
  40021. }
  40022. };
  40023. Gamepads.prototype._stopMonitoringGamepads = function () {
  40024. this.isMonitoring = false;
  40025. };
  40026. Gamepads.prototype._checkGamepadsStatus = function () {
  40027. var _this = this;
  40028. // updating gamepad objects
  40029. this._updateGamepadObjects();
  40030. for (var i in this.babylonGamepads) {
  40031. this.babylonGamepads[i].update();
  40032. }
  40033. if (this.isMonitoring) {
  40034. if (window.requestAnimationFrame) {
  40035. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  40036. }
  40037. else if (window.mozRequestAnimationFrame) {
  40038. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  40039. }
  40040. else if (window.webkitRequestAnimationFrame) {
  40041. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  40042. }
  40043. }
  40044. };
  40045. // This function is called only on Chrome, which does not yet support
  40046. // connection/disconnection events, but requires you to monitor
  40047. // an array for changes.
  40048. Gamepads.prototype._updateGamepadObjects = function () {
  40049. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  40050. for (var i = 0; i < gamepads.length; i++) {
  40051. if (gamepads[i]) {
  40052. if (!(gamepads[i].index in this.babylonGamepads)) {
  40053. var newGamepad = this._addNewGamepad(gamepads[i]);
  40054. if (this._callbackGamepadConnected) {
  40055. this._callbackGamepadConnected(newGamepad);
  40056. }
  40057. }
  40058. else {
  40059. this.babylonGamepads[i].browserGamepad = gamepads[i];
  40060. }
  40061. }
  40062. }
  40063. };
  40064. return Gamepads;
  40065. })();
  40066. BABYLON.Gamepads = Gamepads;
  40067. var StickValues = (function () {
  40068. function StickValues(x, y) {
  40069. this.x = x;
  40070. this.y = y;
  40071. }
  40072. return StickValues;
  40073. })();
  40074. BABYLON.StickValues = StickValues;
  40075. var Gamepad = (function () {
  40076. function Gamepad(id, index, browserGamepad) {
  40077. this.id = id;
  40078. this.index = index;
  40079. this.browserGamepad = browserGamepad;
  40080. if (this.browserGamepad.axes.length >= 2) {
  40081. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  40082. }
  40083. if (this.browserGamepad.axes.length >= 4) {
  40084. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  40085. }
  40086. }
  40087. Gamepad.prototype.onleftstickchanged = function (callback) {
  40088. this._onleftstickchanged = callback;
  40089. };
  40090. Gamepad.prototype.onrightstickchanged = function (callback) {
  40091. this._onrightstickchanged = callback;
  40092. };
  40093. Object.defineProperty(Gamepad.prototype, "leftStick", {
  40094. get: function () {
  40095. return this._leftStick;
  40096. },
  40097. set: function (newValues) {
  40098. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  40099. this._onleftstickchanged(newValues);
  40100. }
  40101. this._leftStick = newValues;
  40102. },
  40103. enumerable: true,
  40104. configurable: true
  40105. });
  40106. Object.defineProperty(Gamepad.prototype, "rightStick", {
  40107. get: function () {
  40108. return this._rightStick;
  40109. },
  40110. set: function (newValues) {
  40111. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  40112. this._onrightstickchanged(newValues);
  40113. }
  40114. this._rightStick = newValues;
  40115. },
  40116. enumerable: true,
  40117. configurable: true
  40118. });
  40119. Gamepad.prototype.update = function () {
  40120. if (this._leftStick) {
  40121. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  40122. }
  40123. if (this._rightStick) {
  40124. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  40125. }
  40126. };
  40127. return Gamepad;
  40128. })();
  40129. BABYLON.Gamepad = Gamepad;
  40130. var GenericPad = (function (_super) {
  40131. __extends(GenericPad, _super);
  40132. function GenericPad(id, index, gamepad) {
  40133. _super.call(this, id, index, gamepad);
  40134. this.id = id;
  40135. this.index = index;
  40136. this.gamepad = gamepad;
  40137. this._buttons = new Array(gamepad.buttons.length);
  40138. }
  40139. GenericPad.prototype.onbuttondown = function (callback) {
  40140. this._onbuttondown = callback;
  40141. };
  40142. GenericPad.prototype.onbuttonup = function (callback) {
  40143. this._onbuttonup = callback;
  40144. };
  40145. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  40146. if (newValue !== currentValue) {
  40147. if (this._onbuttondown && newValue === 1) {
  40148. this._onbuttondown(buttonIndex);
  40149. }
  40150. if (this._onbuttonup && newValue === 0) {
  40151. this._onbuttonup(buttonIndex);
  40152. }
  40153. }
  40154. return newValue;
  40155. };
  40156. GenericPad.prototype.update = function () {
  40157. _super.prototype.update.call(this);
  40158. for (var index = 0; index < this._buttons.length; index++) {
  40159. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  40160. }
  40161. };
  40162. return GenericPad;
  40163. })(Gamepad);
  40164. BABYLON.GenericPad = GenericPad;
  40165. (function (Xbox360Button) {
  40166. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  40167. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  40168. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  40169. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  40170. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  40171. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  40172. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  40173. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  40174. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  40175. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  40176. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  40177. var Xbox360Button = BABYLON.Xbox360Button;
  40178. (function (Xbox360Dpad) {
  40179. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  40180. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  40181. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  40182. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  40183. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  40184. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  40185. var Xbox360Pad = (function (_super) {
  40186. __extends(Xbox360Pad, _super);
  40187. function Xbox360Pad() {
  40188. _super.apply(this, arguments);
  40189. this._leftTrigger = 0;
  40190. this._rightTrigger = 0;
  40191. this._buttonA = 0;
  40192. this._buttonB = 0;
  40193. this._buttonX = 0;
  40194. this._buttonY = 0;
  40195. this._buttonBack = 0;
  40196. this._buttonStart = 0;
  40197. this._buttonLB = 0;
  40198. this._buttonRB = 0;
  40199. this._buttonLeftStick = 0;
  40200. this._buttonRightStick = 0;
  40201. this._dPadUp = 0;
  40202. this._dPadDown = 0;
  40203. this._dPadLeft = 0;
  40204. this._dPadRight = 0;
  40205. }
  40206. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  40207. this._onlefttriggerchanged = callback;
  40208. };
  40209. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  40210. this._onrighttriggerchanged = callback;
  40211. };
  40212. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  40213. get: function () {
  40214. return this._leftTrigger;
  40215. },
  40216. set: function (newValue) {
  40217. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  40218. this._onlefttriggerchanged(newValue);
  40219. }
  40220. this._leftTrigger = newValue;
  40221. },
  40222. enumerable: true,
  40223. configurable: true
  40224. });
  40225. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  40226. get: function () {
  40227. return this._rightTrigger;
  40228. },
  40229. set: function (newValue) {
  40230. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  40231. this._onrighttriggerchanged(newValue);
  40232. }
  40233. this._rightTrigger = newValue;
  40234. },
  40235. enumerable: true,
  40236. configurable: true
  40237. });
  40238. Xbox360Pad.prototype.onbuttondown = function (callback) {
  40239. this._onbuttondown = callback;
  40240. };
  40241. Xbox360Pad.prototype.onbuttonup = function (callback) {
  40242. this._onbuttonup = callback;
  40243. };
  40244. Xbox360Pad.prototype.ondpaddown = function (callback) {
  40245. this._ondpaddown = callback;
  40246. };
  40247. Xbox360Pad.prototype.ondpadup = function (callback) {
  40248. this._ondpadup = callback;
  40249. };
  40250. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  40251. if (newValue !== currentValue) {
  40252. if (this._onbuttondown && newValue === 1) {
  40253. this._onbuttondown(buttonType);
  40254. }
  40255. if (this._onbuttonup && newValue === 0) {
  40256. this._onbuttonup(buttonType);
  40257. }
  40258. }
  40259. return newValue;
  40260. };
  40261. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  40262. if (newValue !== currentValue) {
  40263. if (this._ondpaddown && newValue === 1) {
  40264. this._ondpaddown(buttonType);
  40265. }
  40266. if (this._ondpadup && newValue === 0) {
  40267. this._ondpadup(buttonType);
  40268. }
  40269. }
  40270. return newValue;
  40271. };
  40272. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  40273. get: function () {
  40274. return this._buttonA;
  40275. },
  40276. set: function (value) {
  40277. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  40278. },
  40279. enumerable: true,
  40280. configurable: true
  40281. });
  40282. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  40283. get: function () {
  40284. return this._buttonB;
  40285. },
  40286. set: function (value) {
  40287. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  40288. },
  40289. enumerable: true,
  40290. configurable: true
  40291. });
  40292. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  40293. get: function () {
  40294. return this._buttonX;
  40295. },
  40296. set: function (value) {
  40297. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  40298. },
  40299. enumerable: true,
  40300. configurable: true
  40301. });
  40302. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  40303. get: function () {
  40304. return this._buttonY;
  40305. },
  40306. set: function (value) {
  40307. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  40308. },
  40309. enumerable: true,
  40310. configurable: true
  40311. });
  40312. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  40313. get: function () {
  40314. return this._buttonStart;
  40315. },
  40316. set: function (value) {
  40317. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  40318. },
  40319. enumerable: true,
  40320. configurable: true
  40321. });
  40322. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  40323. get: function () {
  40324. return this._buttonBack;
  40325. },
  40326. set: function (value) {
  40327. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  40328. },
  40329. enumerable: true,
  40330. configurable: true
  40331. });
  40332. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  40333. get: function () {
  40334. return this._buttonLB;
  40335. },
  40336. set: function (value) {
  40337. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  40338. },
  40339. enumerable: true,
  40340. configurable: true
  40341. });
  40342. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  40343. get: function () {
  40344. return this._buttonRB;
  40345. },
  40346. set: function (value) {
  40347. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  40348. },
  40349. enumerable: true,
  40350. configurable: true
  40351. });
  40352. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  40353. get: function () {
  40354. return this._buttonLeftStick;
  40355. },
  40356. set: function (value) {
  40357. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  40358. },
  40359. enumerable: true,
  40360. configurable: true
  40361. });
  40362. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  40363. get: function () {
  40364. return this._buttonRightStick;
  40365. },
  40366. set: function (value) {
  40367. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  40368. },
  40369. enumerable: true,
  40370. configurable: true
  40371. });
  40372. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  40373. get: function () {
  40374. return this._dPadUp;
  40375. },
  40376. set: function (value) {
  40377. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  40378. },
  40379. enumerable: true,
  40380. configurable: true
  40381. });
  40382. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  40383. get: function () {
  40384. return this._dPadDown;
  40385. },
  40386. set: function (value) {
  40387. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  40388. },
  40389. enumerable: true,
  40390. configurable: true
  40391. });
  40392. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  40393. get: function () {
  40394. return this._dPadLeft;
  40395. },
  40396. set: function (value) {
  40397. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  40398. },
  40399. enumerable: true,
  40400. configurable: true
  40401. });
  40402. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  40403. get: function () {
  40404. return this._dPadRight;
  40405. },
  40406. set: function (value) {
  40407. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  40408. },
  40409. enumerable: true,
  40410. configurable: true
  40411. });
  40412. Xbox360Pad.prototype.update = function () {
  40413. _super.prototype.update.call(this);
  40414. this.buttonA = this.browserGamepad.buttons[0].value;
  40415. this.buttonB = this.browserGamepad.buttons[1].value;
  40416. this.buttonX = this.browserGamepad.buttons[2].value;
  40417. this.buttonY = this.browserGamepad.buttons[3].value;
  40418. this.buttonLB = this.browserGamepad.buttons[4].value;
  40419. this.buttonRB = this.browserGamepad.buttons[5].value;
  40420. this.leftTrigger = this.browserGamepad.buttons[6].value;
  40421. this.rightTrigger = this.browserGamepad.buttons[7].value;
  40422. this.buttonBack = this.browserGamepad.buttons[8].value;
  40423. this.buttonStart = this.browserGamepad.buttons[9].value;
  40424. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  40425. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  40426. this.dPadUp = this.browserGamepad.buttons[12].value;
  40427. this.dPadDown = this.browserGamepad.buttons[13].value;
  40428. this.dPadLeft = this.browserGamepad.buttons[14].value;
  40429. this.dPadRight = this.browserGamepad.buttons[15].value;
  40430. };
  40431. return Xbox360Pad;
  40432. })(Gamepad);
  40433. BABYLON.Xbox360Pad = Xbox360Pad;
  40434. })(BABYLON || (BABYLON = {}));
  40435. var BABYLON;
  40436. (function (BABYLON) {
  40437. // We're mainly based on the logic defined into the FreeCamera code
  40438. var GamepadCamera = (function (_super) {
  40439. __extends(GamepadCamera, _super);
  40440. //-- end properties for backward compatibility for inputs
  40441. function GamepadCamera(name, position, scene) {
  40442. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  40443. _super.call(this, name, position, scene);
  40444. }
  40445. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  40446. //-- Begin properties for backward compatibility for inputs
  40447. get: function () {
  40448. var gamepad = this.inputs.attached["gamepad"];
  40449. if (gamepad)
  40450. return gamepad.gamepadAngularSensibility;
  40451. },
  40452. set: function (value) {
  40453. var gamepad = this.inputs.attached["gamepad"];
  40454. if (gamepad)
  40455. gamepad.gamepadAngularSensibility = value;
  40456. },
  40457. enumerable: true,
  40458. configurable: true
  40459. });
  40460. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  40461. get: function () {
  40462. var gamepad = this.inputs.attached["gamepad"];
  40463. if (gamepad)
  40464. return gamepad.gamepadMoveSensibility;
  40465. },
  40466. set: function (value) {
  40467. var gamepad = this.inputs.attached["gamepad"];
  40468. if (gamepad)
  40469. gamepad.gamepadMoveSensibility = value;
  40470. },
  40471. enumerable: true,
  40472. configurable: true
  40473. });
  40474. GamepadCamera.prototype.getTypeName = function () {
  40475. return "GamepadCamera";
  40476. };
  40477. return GamepadCamera;
  40478. })(BABYLON.UniversalCamera);
  40479. BABYLON.GamepadCamera = GamepadCamera;
  40480. })(BABYLON || (BABYLON = {}));
  40481. var BABYLON;
  40482. (function (BABYLON) {
  40483. var Analyser = (function () {
  40484. function Analyser(scene) {
  40485. this.SMOOTHING = 0.75;
  40486. this.FFT_SIZE = 512;
  40487. this.BARGRAPHAMPLITUDE = 256;
  40488. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  40489. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  40490. this._scene = scene;
  40491. this._audioEngine = BABYLON.Engine.audioEngine;
  40492. if (this._audioEngine.canUseWebAudio) {
  40493. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  40494. this._webAudioAnalyser.minDecibels = -140;
  40495. this._webAudioAnalyser.maxDecibels = 0;
  40496. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40497. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40498. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  40499. }
  40500. }
  40501. Analyser.prototype.getFrequencyBinCount = function () {
  40502. if (this._audioEngine.canUseWebAudio) {
  40503. return this._webAudioAnalyser.frequencyBinCount;
  40504. }
  40505. else {
  40506. return 0;
  40507. }
  40508. };
  40509. Analyser.prototype.getByteFrequencyData = function () {
  40510. if (this._audioEngine.canUseWebAudio) {
  40511. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40512. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40513. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40514. }
  40515. return this._byteFreqs;
  40516. };
  40517. Analyser.prototype.getByteTimeDomainData = function () {
  40518. if (this._audioEngine.canUseWebAudio) {
  40519. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40520. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40521. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40522. }
  40523. return this._byteTime;
  40524. };
  40525. Analyser.prototype.getFloatFrequencyData = function () {
  40526. if (this._audioEngine.canUseWebAudio) {
  40527. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40528. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40529. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40530. }
  40531. return this._floatFreqs;
  40532. };
  40533. Analyser.prototype.drawDebugCanvas = function () {
  40534. var _this = this;
  40535. if (this._audioEngine.canUseWebAudio) {
  40536. if (!this._debugCanvas) {
  40537. this._debugCanvas = document.createElement("canvas");
  40538. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40539. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40540. this._debugCanvas.style.position = "absolute";
  40541. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40542. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40543. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40544. document.body.appendChild(this._debugCanvas);
  40545. this._registerFunc = function () {
  40546. _this.drawDebugCanvas();
  40547. };
  40548. this._scene.registerBeforeRender(this._registerFunc);
  40549. }
  40550. if (this._registerFunc) {
  40551. var workingArray = this.getByteFrequencyData();
  40552. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40553. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40554. // Draw the frequency domain chart.
  40555. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40556. var value = workingArray[i];
  40557. var percent = value / this.BARGRAPHAMPLITUDE;
  40558. var height = this.DEBUGCANVASSIZE.height * percent;
  40559. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40560. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40561. var hue = i / this.getFrequencyBinCount() * 360;
  40562. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40563. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40564. }
  40565. }
  40566. }
  40567. };
  40568. Analyser.prototype.stopDebugCanvas = function () {
  40569. if (this._debugCanvas) {
  40570. this._scene.unregisterBeforeRender(this._registerFunc);
  40571. this._registerFunc = null;
  40572. document.body.removeChild(this._debugCanvas);
  40573. this._debugCanvas = null;
  40574. this._debugCanvasContext = null;
  40575. }
  40576. };
  40577. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40578. if (this._audioEngine.canUseWebAudio) {
  40579. inputAudioNode.connect(this._webAudioAnalyser);
  40580. this._webAudioAnalyser.connect(outputAudioNode);
  40581. }
  40582. };
  40583. Analyser.prototype.dispose = function () {
  40584. if (this._audioEngine.canUseWebAudio) {
  40585. this._webAudioAnalyser.disconnect();
  40586. }
  40587. };
  40588. return Analyser;
  40589. })();
  40590. BABYLON.Analyser = Analyser;
  40591. })(BABYLON || (BABYLON = {}));
  40592. var BABYLON;
  40593. (function (BABYLON) {
  40594. var DepthRenderer = (function () {
  40595. function DepthRenderer(scene, type) {
  40596. var _this = this;
  40597. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  40598. this._viewMatrix = BABYLON.Matrix.Zero();
  40599. this._projectionMatrix = BABYLON.Matrix.Zero();
  40600. this._transformMatrix = BABYLON.Matrix.Zero();
  40601. this._worldViewProjection = BABYLON.Matrix.Zero();
  40602. this._scene = scene;
  40603. var engine = scene.getEngine();
  40604. // Render target
  40605. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  40606. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40607. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40608. this._depthMap.refreshRate = 1;
  40609. this._depthMap.renderParticles = false;
  40610. this._depthMap.renderList = null;
  40611. // set default depth value to 1.0 (far away)
  40612. this._depthMap.onClear = function (engine) {
  40613. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  40614. };
  40615. // Custom render function
  40616. var renderSubMesh = function (subMesh) {
  40617. var mesh = subMesh.getRenderingMesh();
  40618. var scene = _this._scene;
  40619. var engine = scene.getEngine();
  40620. // Culling
  40621. engine.setState(subMesh.getMaterial().backFaceCulling);
  40622. // Managing instances
  40623. var batch = mesh._getInstancesRenderList(subMesh._id);
  40624. if (batch.mustReturn) {
  40625. return;
  40626. }
  40627. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40628. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40629. engine.enableEffect(_this._effect);
  40630. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  40631. var material = subMesh.getMaterial();
  40632. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  40633. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  40634. // Alpha test
  40635. if (material && material.needAlphaTesting()) {
  40636. var alphaTexture = material.getAlphaTestTexture();
  40637. _this._effect.setTexture("diffuseSampler", alphaTexture);
  40638. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40639. }
  40640. // Bones
  40641. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40642. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40643. }
  40644. // Draw
  40645. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  40646. }
  40647. };
  40648. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  40649. var index;
  40650. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40651. renderSubMesh(opaqueSubMeshes.data[index]);
  40652. }
  40653. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40654. renderSubMesh(alphaTestSubMeshes.data[index]);
  40655. }
  40656. };
  40657. }
  40658. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  40659. var material = subMesh.getMaterial();
  40660. if (material.disableDepthWrite) {
  40661. return false;
  40662. }
  40663. var defines = [];
  40664. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40665. var mesh = subMesh.getMesh();
  40666. var scene = mesh.getScene();
  40667. // Alpha test
  40668. if (material && material.needAlphaTesting()) {
  40669. defines.push("#define ALPHATEST");
  40670. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40671. attribs.push(BABYLON.VertexBuffer.UVKind);
  40672. defines.push("#define UV1");
  40673. }
  40674. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40675. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40676. defines.push("#define UV2");
  40677. }
  40678. }
  40679. // Bones
  40680. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40681. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40682. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40683. if (mesh.numBoneInfluencers > 4) {
  40684. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40685. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40686. }
  40687. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40688. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40689. }
  40690. else {
  40691. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40692. }
  40693. // Instances
  40694. if (useInstances) {
  40695. defines.push("#define INSTANCES");
  40696. attribs.push("world0");
  40697. attribs.push("world1");
  40698. attribs.push("world2");
  40699. attribs.push("world3");
  40700. }
  40701. // Get correct effect
  40702. var join = defines.join("\n");
  40703. if (this._cachedDefines !== join) {
  40704. this._cachedDefines = join;
  40705. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  40706. }
  40707. return this._effect.isReady();
  40708. };
  40709. DepthRenderer.prototype.getDepthMap = function () {
  40710. return this._depthMap;
  40711. };
  40712. // Methods
  40713. DepthRenderer.prototype.dispose = function () {
  40714. this._depthMap.dispose();
  40715. };
  40716. return DepthRenderer;
  40717. })();
  40718. BABYLON.DepthRenderer = DepthRenderer;
  40719. })(BABYLON || (BABYLON = {}));
  40720. var BABYLON;
  40721. (function (BABYLON) {
  40722. var SSAORenderingPipeline = (function (_super) {
  40723. __extends(SSAORenderingPipeline, _super);
  40724. /**
  40725. * @constructor
  40726. * @param {string} name - The rendering pipeline name
  40727. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40728. * @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 }
  40729. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40730. */
  40731. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  40732. var _this = this;
  40733. _super.call(this, scene.getEngine(), name);
  40734. // Members
  40735. /**
  40736. * The PassPostProcess id in the pipeline that contains the original scene color
  40737. * @type {string}
  40738. */
  40739. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  40740. /**
  40741. * The SSAO PostProcess id in the pipeline
  40742. * @type {string}
  40743. */
  40744. this.SSAORenderEffect = "SSAORenderEffect";
  40745. /**
  40746. * The horizontal blur PostProcess id in the pipeline
  40747. * @type {string}
  40748. */
  40749. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  40750. /**
  40751. * The vertical blur PostProcess id in the pipeline
  40752. * @type {string}
  40753. */
  40754. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  40755. /**
  40756. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  40757. * @type {string}
  40758. */
  40759. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  40760. /**
  40761. * The output strength of the SSAO post-process. Default value is 1.0.
  40762. * @type {number}
  40763. */
  40764. this.totalStrength = 1.0;
  40765. /**
  40766. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  40767. * @type {number}
  40768. */
  40769. this.radius = 0.0001;
  40770. /**
  40771. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  40772. * Must not be equal to fallOff and superior to fallOff.
  40773. * Default value is 0.975
  40774. * @type {number}
  40775. */
  40776. this.area = 0.0075;
  40777. /**
  40778. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  40779. * Must not be equal to area and inferior to area.
  40780. * Default value is 0.0
  40781. * @type {number}
  40782. */
  40783. this.fallOff = 0.000001;
  40784. /**
  40785. * The base color of the SSAO post-process
  40786. * The final result is "base + ssao" between [0, 1]
  40787. * @type {number}
  40788. */
  40789. this.base = 0.5;
  40790. this._firstUpdate = true;
  40791. this._scene = scene;
  40792. // Set up assets
  40793. this._createRandomTexture();
  40794. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40795. var ssaoRatio = ratio.ssaoRatio || ratio;
  40796. var combineRatio = ratio.combineRatio || ratio;
  40797. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40798. this._createSSAOPostProcess(ssaoRatio);
  40799. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40800. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40801. this._createSSAOCombinePostProcess(combineRatio);
  40802. // Set up pipeline
  40803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  40804. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  40805. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  40806. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  40807. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  40808. // Finish
  40809. scene.postProcessRenderPipelineManager.addPipeline(this);
  40810. if (cameras)
  40811. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40812. }
  40813. // Public Methods
  40814. /**
  40815. * Returns the horizontal blur PostProcess
  40816. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  40817. */
  40818. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  40819. return this._blurHPostProcess;
  40820. };
  40821. /**
  40822. * Returns the vertical blur PostProcess
  40823. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  40824. */
  40825. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  40826. return this._blurVPostProcess;
  40827. };
  40828. /**
  40829. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  40830. */
  40831. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40832. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40833. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40834. this._originalColorPostProcess = undefined;
  40835. this._ssaoPostProcess = undefined;
  40836. this._blurHPostProcess = undefined;
  40837. this._blurVPostProcess = undefined;
  40838. this._ssaoCombinePostProcess = undefined;
  40839. this._randomTexture.dispose();
  40840. if (disableDepthRender)
  40841. this._scene.disableDepthRenderer();
  40842. };
  40843. // Private Methods
  40844. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  40845. var _this = this;
  40846. var numSamples = 16;
  40847. var sampleSphere = [
  40848. 0.5381, 0.1856, -0.4319,
  40849. 0.1379, 0.2486, 0.4430,
  40850. 0.3371, 0.5679, -0.0057,
  40851. -0.6999, -0.0451, -0.0019,
  40852. 0.0689, -0.1598, -0.8547,
  40853. 0.0560, 0.0069, -0.1843,
  40854. -0.0146, 0.1402, 0.0762,
  40855. 0.0100, -0.1924, -0.0344,
  40856. -0.3577, -0.5301, -0.4358,
  40857. -0.3169, 0.1063, 0.0158,
  40858. 0.0103, -0.5869, 0.0046,
  40859. -0.0897, -0.4940, 0.3287,
  40860. 0.7119, -0.0154, -0.0918,
  40861. -0.0533, 0.0596, -0.5411,
  40862. 0.0352, -0.0631, 0.5460,
  40863. -0.4776, 0.2847, -0.0271
  40864. ];
  40865. var samplesFactor = 1.0 / numSamples;
  40866. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  40867. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  40868. "area", "fallOff", "base"
  40869. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  40870. this._ssaoPostProcess.onApply = function (effect) {
  40871. if (_this._firstUpdate) {
  40872. effect.setArray3("sampleSphere", sampleSphere);
  40873. effect.setFloat("samplesFactor", samplesFactor);
  40874. effect.setFloat("randTextureTiles", 4.0);
  40875. _this._firstUpdate = false;
  40876. }
  40877. effect.setFloat("totalStrength", _this.totalStrength);
  40878. effect.setFloat("radius", _this.radius);
  40879. effect.setFloat("area", _this.area);
  40880. effect.setFloat("fallOff", _this.fallOff);
  40881. effect.setFloat("base", _this.base);
  40882. effect.setTexture("textureSampler", _this._depthTexture);
  40883. effect.setTexture("randomSampler", _this._randomTexture);
  40884. };
  40885. };
  40886. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  40887. var _this = this;
  40888. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40889. this._ssaoCombinePostProcess.onApply = function (effect) {
  40890. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  40891. };
  40892. };
  40893. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  40894. var size = 512;
  40895. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40896. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40897. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40898. var context = this._randomTexture.getContext();
  40899. var rand = function (min, max) {
  40900. return Math.random() * (max - min) + min;
  40901. };
  40902. var randVector = BABYLON.Vector3.Zero();
  40903. for (var x = 0; x < size; x++) {
  40904. for (var y = 0; y < size; y++) {
  40905. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  40906. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  40907. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  40908. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  40909. context.fillRect(x, y, 1, 1);
  40910. }
  40911. }
  40912. this._randomTexture.update(false);
  40913. };
  40914. return SSAORenderingPipeline;
  40915. })(BABYLON.PostProcessRenderPipeline);
  40916. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  40917. })(BABYLON || (BABYLON = {}));
  40918. var BABYLON;
  40919. (function (BABYLON) {
  40920. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  40921. var VolumetricLightScatteringPostProcess = (function (_super) {
  40922. __extends(VolumetricLightScatteringPostProcess, _super);
  40923. /**
  40924. * @constructor
  40925. * @param {string} name - The post-process name
  40926. * @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)
  40927. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  40928. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  40929. * @param {number} samples - The post-process quality, default 100
  40930. * @param {number} samplingMode - The post-process filtering mode
  40931. * @param {BABYLON.Engine} engine - The babylon engine
  40932. * @param {boolean} reusable - If the post-process is reusable
  40933. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  40934. */
  40935. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  40936. var _this = this;
  40937. if (samples === void 0) { samples = 100; }
  40938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40939. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  40940. this._screenCoordinates = BABYLON.Vector2.Zero();
  40941. /**
  40942. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  40943. * @type {Vector3}
  40944. */
  40945. this.customMeshPosition = BABYLON.Vector3.Zero();
  40946. /**
  40947. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  40948. * @type {boolean}
  40949. */
  40950. this.useCustomMeshPosition = false;
  40951. /**
  40952. * If the post-process should inverse the light scattering direction
  40953. * @type {boolean}
  40954. */
  40955. this.invert = true;
  40956. /**
  40957. * Array containing the excluded meshes not rendered in the internal pass
  40958. */
  40959. this.excludedMeshes = new Array();
  40960. /**
  40961. * Controls the overall intensity of the post-process
  40962. * @type {number}
  40963. */
  40964. this.exposure = 0.3;
  40965. /**
  40966. * Dissipates each sample's contribution in range [0, 1]
  40967. * @type {number}
  40968. */
  40969. this.decay = 0.96815;
  40970. /**
  40971. * Controls the overall intensity of each sample
  40972. * @type {number}
  40973. */
  40974. this.weight = 0.58767;
  40975. /**
  40976. * Controls the density of each sample
  40977. * @type {number}
  40978. */
  40979. this.density = 0.926;
  40980. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  40981. var engine = scene.getEngine();
  40982. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  40983. // Configure mesh
  40984. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  40985. // Configure
  40986. this._createPass(scene, ratio.passRatio || ratio);
  40987. this.onActivate = function (camera) {
  40988. if (!_this.isSupported) {
  40989. _this.dispose(camera);
  40990. }
  40991. _this.onActivate = null;
  40992. };
  40993. this.onApply = function (effect) {
  40994. _this._updateMeshScreenCoordinates(scene);
  40995. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  40996. effect.setFloat("exposure", _this.exposure);
  40997. effect.setFloat("decay", _this.decay);
  40998. effect.setFloat("weight", _this.weight);
  40999. effect.setFloat("density", _this.density);
  41000. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  41001. };
  41002. }
  41003. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  41004. get: function () {
  41005. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  41006. return false;
  41007. },
  41008. set: function (useDiffuseColor) {
  41009. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  41010. },
  41011. enumerable: true,
  41012. configurable: true
  41013. });
  41014. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  41015. var mesh = subMesh.getMesh();
  41016. // Render this.mesh as default
  41017. if (mesh === this.mesh) {
  41018. return mesh.material.isReady(mesh);
  41019. }
  41020. var defines = [];
  41021. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41022. var material = subMesh.getMaterial();
  41023. var needUV = false;
  41024. // Alpha test
  41025. if (material) {
  41026. if (material.needAlphaTesting()) {
  41027. defines.push("#define ALPHATEST");
  41028. }
  41029. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41030. attribs.push(BABYLON.VertexBuffer.UVKind);
  41031. defines.push("#define UV1");
  41032. }
  41033. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41034. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41035. defines.push("#define UV2");
  41036. }
  41037. }
  41038. // Bones
  41039. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41042. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41043. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41044. }
  41045. else {
  41046. defines.push("#define NUM_BONE_INFLUENCERS 0");
  41047. }
  41048. // Instances
  41049. if (useInstances) {
  41050. defines.push("#define INSTANCES");
  41051. attribs.push("world0");
  41052. attribs.push("world1");
  41053. attribs.push("world2");
  41054. attribs.push("world3");
  41055. }
  41056. // Get correct effect
  41057. var join = defines.join("\n");
  41058. if (this._cachedDefines !== join) {
  41059. this._cachedDefines = join;
  41060. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  41061. }
  41062. return this._volumetricLightScatteringPass.isReady();
  41063. };
  41064. /**
  41065. * Sets the new light position for light scattering effect
  41066. * @param {BABYLON.Vector3} The new custom light position
  41067. */
  41068. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  41069. this.customMeshPosition = position;
  41070. };
  41071. /**
  41072. * Returns the light position for light scattering effect
  41073. * @return {BABYLON.Vector3} The custom light position
  41074. */
  41075. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  41076. return this.customMeshPosition;
  41077. };
  41078. /**
  41079. * Disposes the internal assets and detaches the post-process from the camera
  41080. */
  41081. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  41082. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  41083. if (rttIndex !== -1) {
  41084. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  41085. }
  41086. this._volumetricLightScatteringRTT.dispose();
  41087. _super.prototype.dispose.call(this, camera);
  41088. };
  41089. /**
  41090. * Returns the render target texture used by the post-process
  41091. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  41092. */
  41093. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  41094. return this._volumetricLightScatteringRTT;
  41095. };
  41096. // Private methods
  41097. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  41098. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  41099. return true;
  41100. }
  41101. return false;
  41102. };
  41103. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  41104. var _this = this;
  41105. var engine = scene.getEngine();
  41106. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  41107. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41108. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41109. this._volumetricLightScatteringRTT.renderList = null;
  41110. this._volumetricLightScatteringRTT.renderParticles = false;
  41111. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  41112. // Custom render function for submeshes
  41113. var renderSubMesh = function (subMesh) {
  41114. var mesh = subMesh.getRenderingMesh();
  41115. if (_this._meshExcluded(mesh)) {
  41116. return;
  41117. }
  41118. var scene = mesh.getScene();
  41119. var engine = scene.getEngine();
  41120. // Culling
  41121. engine.setState(subMesh.getMaterial().backFaceCulling);
  41122. // Managing instances
  41123. var batch = mesh._getInstancesRenderList(subMesh._id);
  41124. if (batch.mustReturn) {
  41125. return;
  41126. }
  41127. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  41128. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  41129. var effect = _this._volumetricLightScatteringPass;
  41130. if (mesh === _this.mesh) {
  41131. effect = subMesh.getMaterial().getEffect();
  41132. }
  41133. engine.enableEffect(effect);
  41134. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  41135. if (mesh === _this.mesh) {
  41136. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  41137. }
  41138. else {
  41139. var material = subMesh.getMaterial();
  41140. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  41141. // Alpha test
  41142. if (material && material.needAlphaTesting()) {
  41143. var alphaTexture = material.getAlphaTestTexture();
  41144. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  41145. if (alphaTexture) {
  41146. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  41147. }
  41148. }
  41149. // Bones
  41150. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41151. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  41152. }
  41153. }
  41154. // Draw
  41155. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  41156. }
  41157. };
  41158. // Render target texture callbacks
  41159. var savedSceneClearColor;
  41160. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  41161. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  41162. savedSceneClearColor = scene.clearColor;
  41163. scene.clearColor = sceneClearColor;
  41164. };
  41165. this._volumetricLightScatteringRTT.onAfterRender = function () {
  41166. scene.clearColor = savedSceneClearColor;
  41167. };
  41168. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  41169. var engine = scene.getEngine();
  41170. var index;
  41171. for (index = 0; index < opaqueSubMeshes.length; index++) {
  41172. renderSubMesh(opaqueSubMeshes.data[index]);
  41173. }
  41174. engine.setAlphaTesting(true);
  41175. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  41176. renderSubMesh(alphaTestSubMeshes.data[index]);
  41177. }
  41178. engine.setAlphaTesting(false);
  41179. if (transparentSubMeshes.length) {
  41180. // Sort sub meshes
  41181. for (index = 0; index < transparentSubMeshes.length; index++) {
  41182. var submesh = transparentSubMeshes.data[index];
  41183. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  41184. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  41185. }
  41186. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  41187. sortedArray.sort(function (a, b) {
  41188. // Alpha index first
  41189. if (a._alphaIndex > b._alphaIndex) {
  41190. return 1;
  41191. }
  41192. if (a._alphaIndex < b._alphaIndex) {
  41193. return -1;
  41194. }
  41195. // Then distance to camera
  41196. if (a._distanceToCamera < b._distanceToCamera) {
  41197. return 1;
  41198. }
  41199. if (a._distanceToCamera > b._distanceToCamera) {
  41200. return -1;
  41201. }
  41202. return 0;
  41203. });
  41204. // Render sub meshes
  41205. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41206. for (index = 0; index < sortedArray.length; index++) {
  41207. renderSubMesh(sortedArray[index]);
  41208. }
  41209. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41210. }
  41211. };
  41212. };
  41213. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  41214. var transform = scene.getTransformMatrix();
  41215. var meshPosition;
  41216. if (this.useCustomMeshPosition) {
  41217. meshPosition = this.customMeshPosition;
  41218. }
  41219. else if (this.attachedNode) {
  41220. meshPosition = this.attachedNode.position;
  41221. }
  41222. else {
  41223. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  41224. }
  41225. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  41226. this._screenCoordinates.x = pos.x / this._viewPort.width;
  41227. this._screenCoordinates.y = pos.y / this._viewPort.height;
  41228. if (this.invert)
  41229. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  41230. };
  41231. // Static methods
  41232. /**
  41233. * Creates a default mesh for the Volumeric Light Scattering post-process
  41234. * @param {string} The mesh name
  41235. * @param {BABYLON.Scene} The scene where to create the mesh
  41236. * @return {BABYLON.Mesh} the default mesh
  41237. */
  41238. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  41239. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  41240. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  41241. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  41242. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  41243. mesh.material = material;
  41244. return mesh;
  41245. };
  41246. __decorate([
  41247. BABYLON.serializeAsVector3()
  41248. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  41249. __decorate([
  41250. BABYLON.serialize()
  41251. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  41252. __decorate([
  41253. BABYLON.serialize()
  41254. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  41255. __decorate([
  41256. BABYLON.serializeAsMeshReference()
  41257. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  41258. __decorate([
  41259. BABYLON.serialize()
  41260. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  41261. __decorate([
  41262. BABYLON.serialize()
  41263. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  41264. __decorate([
  41265. BABYLON.serialize()
  41266. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  41267. __decorate([
  41268. BABYLON.serialize()
  41269. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  41270. __decorate([
  41271. BABYLON.serialize()
  41272. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  41273. return VolumetricLightScatteringPostProcess;
  41274. })(BABYLON.PostProcess);
  41275. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  41276. })(BABYLON || (BABYLON = {}));
  41277. // BABYLON.JS Chromatic Aberration GLSL Shader
  41278. // Author: Olivier Guyot
  41279. // Separates very slightly R, G and B colors on the edges of the screen
  41280. // Inspired by Francois Tarlier & Martins Upitis
  41281. var BABYLON;
  41282. (function (BABYLON) {
  41283. var LensRenderingPipeline = (function (_super) {
  41284. __extends(LensRenderingPipeline, _super);
  41285. /**
  41286. * @constructor
  41287. *
  41288. * Effect parameters are as follow:
  41289. * {
  41290. * chromatic_aberration: number; // from 0 to x (1 for realism)
  41291. * edge_blur: number; // from 0 to x (1 for realism)
  41292. * distortion: number; // from 0 to x (1 for realism)
  41293. * grain_amount: number; // from 0 to 1
  41294. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  41295. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  41296. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  41297. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  41298. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  41299. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  41300. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  41301. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  41302. * }
  41303. * Note: if an effect parameter is unset, effect is disabled
  41304. *
  41305. * @param {string} name - The rendering pipeline name
  41306. * @param {object} parameters - An object containing all parameters (see above)
  41307. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  41308. * @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)
  41309. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  41310. */
  41311. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  41312. var _this = this;
  41313. if (ratio === void 0) { ratio = 1.0; }
  41314. _super.call(this, scene.getEngine(), name);
  41315. // Lens effects can be of the following:
  41316. // - chromatic aberration (slight shift of RGB colors)
  41317. // - blur on the edge of the lens
  41318. // - lens distortion
  41319. // - depth-of-field blur & highlights enhancing
  41320. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  41321. // - grain effect (noise or custom texture)
  41322. // Two additional texture samplers are needed:
  41323. // - depth map (for depth-of-field)
  41324. // - grain texture
  41325. /**
  41326. * The chromatic aberration PostProcess id in the pipeline
  41327. * @type {string}
  41328. */
  41329. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  41330. /**
  41331. * The highlights enhancing PostProcess id in the pipeline
  41332. * @type {string}
  41333. */
  41334. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  41335. /**
  41336. * The depth-of-field PostProcess id in the pipeline
  41337. * @type {string}
  41338. */
  41339. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  41340. this._scene = scene;
  41341. // Fetch texture samplers
  41342. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  41343. if (parameters.grain_texture) {
  41344. this._grainTexture = parameters.grain_texture;
  41345. }
  41346. else {
  41347. this._createGrainTexture();
  41348. }
  41349. // save parameters
  41350. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  41351. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  41352. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  41353. this._distortion = parameters.distortion ? parameters.distortion : 0;
  41354. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  41355. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  41356. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  41357. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  41358. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  41359. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  41360. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  41361. // Create effects
  41362. this._createChromaticAberrationPostProcess(ratio);
  41363. this._createHighlightsPostProcess(ratio);
  41364. this._createDepthOfFieldPostProcess(ratio / 4);
  41365. // Set up pipeline
  41366. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  41367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  41368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  41369. if (this._highlightsGain === -1) {
  41370. this._disableEffect(this.HighlightsEnhancingEffect, null);
  41371. }
  41372. // Finish
  41373. scene.postProcessRenderPipelineManager.addPipeline(this);
  41374. if (cameras) {
  41375. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  41376. }
  41377. }
  41378. // public methods (self explanatory)
  41379. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  41380. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  41381. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  41382. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  41383. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  41384. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  41385. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  41386. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  41387. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  41388. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  41389. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  41390. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  41391. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  41392. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  41393. };
  41394. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  41395. this._highlightsPostProcess.updateEffect();
  41396. };
  41397. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  41398. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  41399. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  41400. this._highlightsGain = amount;
  41401. };
  41402. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  41403. if (this._highlightsGain === -1) {
  41404. this._highlightsGain = 1.0;
  41405. }
  41406. this._highlightsThreshold = amount;
  41407. };
  41408. LensRenderingPipeline.prototype.disableHighlights = function () {
  41409. this._highlightsGain = -1;
  41410. };
  41411. /**
  41412. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  41413. */
  41414. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  41415. if (disableDepthRender === void 0) { disableDepthRender = false; }
  41416. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  41417. this._chromaticAberrationPostProcess = undefined;
  41418. this._highlightsPostProcess = undefined;
  41419. this._depthOfFieldPostProcess = undefined;
  41420. this._grainTexture.dispose();
  41421. if (disableDepthRender)
  41422. this._scene.disableDepthRenderer();
  41423. };
  41424. // colors shifting and distortion
  41425. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  41426. var _this = this;
  41427. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  41428. [], // samplers
  41429. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  41430. this._chromaticAberrationPostProcess.onApply = function (effect) {
  41431. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  41432. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  41433. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  41434. };
  41435. };
  41436. // highlights enhancing
  41437. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  41438. var _this = this;
  41439. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  41440. [], // samplers
  41441. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  41442. this._highlightsPostProcess.onApply = function (effect) {
  41443. effect.setFloat('gain', _this._highlightsGain);
  41444. effect.setFloat('threshold', _this._highlightsThreshold);
  41445. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  41446. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  41447. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  41448. };
  41449. };
  41450. // colors shifting and distortion
  41451. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  41452. var _this = this;
  41453. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  41454. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  41455. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  41456. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  41457. this._depthOfFieldPostProcess.onApply = function (effect) {
  41458. effect.setTexture("depthSampler", _this._depthTexture);
  41459. effect.setTexture("grainSampler", _this._grainTexture);
  41460. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  41461. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  41462. effect.setFloat('grain_amount', _this._grainAmount);
  41463. effect.setBool('blur_noise', _this._blurNoise);
  41464. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  41465. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  41466. effect.setFloat('distortion', _this._distortion);
  41467. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  41468. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  41469. effect.setFloat('aperture', _this._dofAperture);
  41470. effect.setFloat('darken', _this._dofDarken);
  41471. effect.setFloat('edge_blur', _this._edgeBlur);
  41472. effect.setBool('highlights', (_this._highlightsGain !== -1));
  41473. effect.setFloat('near', _this._scene.activeCamera.minZ);
  41474. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  41475. };
  41476. };
  41477. // creates a black and white random noise texture, 512x512
  41478. LensRenderingPipeline.prototype._createGrainTexture = function () {
  41479. var size = 512;
  41480. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41481. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  41482. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  41483. var context = this._grainTexture.getContext();
  41484. var rand = function (min, max) {
  41485. return Math.random() * (max - min) + min;
  41486. };
  41487. var value;
  41488. for (var x = 0; x < size; x++) {
  41489. for (var y = 0; y < size; y++) {
  41490. value = Math.floor(rand(0.42, 0.58) * 255);
  41491. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  41492. context.fillRect(x, y, 1, 1);
  41493. }
  41494. }
  41495. this._grainTexture.update(false);
  41496. };
  41497. return LensRenderingPipeline;
  41498. })(BABYLON.PostProcessRenderPipeline);
  41499. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  41500. })(BABYLON || (BABYLON = {}));
  41501. //
  41502. // This post-process allows the modification of rendered colors by using
  41503. // a 'look-up table' (LUT). This effect is also called Color Grading.
  41504. //
  41505. // The object needs to be provided an url to a texture containing the color
  41506. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  41507. // Use an image editing software to tweak the LUT to match your needs.
  41508. //
  41509. // For an example of a color LUT, see here:
  41510. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  41511. // For explanations on color grading, see here:
  41512. // http://udn.epicgames.com/Three/ColorGrading.html
  41513. //
  41514. var BABYLON;
  41515. (function (BABYLON) {
  41516. var ColorCorrectionPostProcess = (function (_super) {
  41517. __extends(ColorCorrectionPostProcess, _super);
  41518. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  41519. var _this = this;
  41520. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  41521. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  41522. this._colorTableTexture.anisotropicFilteringLevel = 1;
  41523. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41524. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41525. this.onApply = function (effect) {
  41526. effect.setTexture("colorTable", _this._colorTableTexture);
  41527. };
  41528. }
  41529. return ColorCorrectionPostProcess;
  41530. })(BABYLON.PostProcess);
  41531. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  41532. })(BABYLON || (BABYLON = {}));
  41533. var BABYLON;
  41534. (function (BABYLON) {
  41535. var AnaglyphFreeCamera = (function (_super) {
  41536. __extends(AnaglyphFreeCamera, _super);
  41537. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  41538. _super.call(this, name, position, scene);
  41539. this.interaxialDistance = interaxialDistance;
  41540. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41541. }
  41542. AnaglyphFreeCamera.prototype.getTypeName = function () {
  41543. return "AnaglyphFreeCamera";
  41544. };
  41545. return AnaglyphFreeCamera;
  41546. })(BABYLON.FreeCamera);
  41547. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  41548. var AnaglyphArcRotateCamera = (function (_super) {
  41549. __extends(AnaglyphArcRotateCamera, _super);
  41550. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  41551. _super.call(this, name, alpha, beta, radius, target, scene);
  41552. this.interaxialDistance = interaxialDistance;
  41553. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41554. }
  41555. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  41556. return "AnaglyphArcRotateCamera";
  41557. };
  41558. return AnaglyphArcRotateCamera;
  41559. })(BABYLON.ArcRotateCamera);
  41560. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  41561. var AnaglyphGamepadCamera = (function (_super) {
  41562. __extends(AnaglyphGamepadCamera, _super);
  41563. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  41564. _super.call(this, name, position, scene);
  41565. this.interaxialDistance = interaxialDistance;
  41566. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41567. }
  41568. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  41569. return "AnaglyphGamepadCamera";
  41570. };
  41571. return AnaglyphGamepadCamera;
  41572. })(BABYLON.GamepadCamera);
  41573. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  41574. var AnaglyphUniversalCamera = (function (_super) {
  41575. __extends(AnaglyphUniversalCamera, _super);
  41576. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  41577. _super.call(this, name, position, scene);
  41578. this.interaxialDistance = interaxialDistance;
  41579. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41580. }
  41581. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  41582. return "AnaglyphUniversalCamera";
  41583. };
  41584. return AnaglyphUniversalCamera;
  41585. })(BABYLON.UniversalCamera);
  41586. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  41587. var StereoscopicFreeCamera = (function (_super) {
  41588. __extends(StereoscopicFreeCamera, _super);
  41589. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41590. _super.call(this, name, position, scene);
  41591. this.interaxialDistance = interaxialDistance;
  41592. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41593. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41594. }
  41595. StereoscopicFreeCamera.prototype.getTypeName = function () {
  41596. return "StereoscopicFreeCamera";
  41597. };
  41598. return StereoscopicFreeCamera;
  41599. })(BABYLON.FreeCamera);
  41600. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  41601. var StereoscopicArcRotateCamera = (function (_super) {
  41602. __extends(StereoscopicArcRotateCamera, _super);
  41603. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  41604. _super.call(this, name, alpha, beta, radius, target, scene);
  41605. this.interaxialDistance = interaxialDistance;
  41606. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41607. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41608. }
  41609. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  41610. return "StereoscopicArcRotateCamera";
  41611. };
  41612. return StereoscopicArcRotateCamera;
  41613. })(BABYLON.ArcRotateCamera);
  41614. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  41615. var StereoscopicGamepadCamera = (function (_super) {
  41616. __extends(StereoscopicGamepadCamera, _super);
  41617. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41618. _super.call(this, name, position, scene);
  41619. this.interaxialDistance = interaxialDistance;
  41620. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41621. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41622. }
  41623. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  41624. return "StereoscopicGamepadCamera";
  41625. };
  41626. return StereoscopicGamepadCamera;
  41627. })(BABYLON.GamepadCamera);
  41628. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  41629. var StereoscopicUniversalCamera = (function (_super) {
  41630. __extends(StereoscopicUniversalCamera, _super);
  41631. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41632. _super.call(this, name, position, scene);
  41633. this.interaxialDistance = interaxialDistance;
  41634. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41635. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41636. }
  41637. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  41638. return "StereoscopicUniversalCamera";
  41639. };
  41640. return StereoscopicUniversalCamera;
  41641. })(BABYLON.UniversalCamera);
  41642. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  41643. })(BABYLON || (BABYLON = {}));
  41644. var BABYLON;
  41645. (function (BABYLON) {
  41646. var HDRRenderingPipeline = (function (_super) {
  41647. __extends(HDRRenderingPipeline, _super);
  41648. /**
  41649. * @constructor
  41650. * @param {string} name - The rendering pipeline name
  41651. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  41652. * @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)
  41653. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  41654. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  41655. */
  41656. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  41657. var _this = this;
  41658. if (originalPostProcess === void 0) { originalPostProcess = null; }
  41659. _super.call(this, scene.getEngine(), name);
  41660. /**
  41661. * Public members
  41662. */
  41663. // Gaussian Blur
  41664. /**
  41665. * Gaussian blur coefficient
  41666. * @type {number}
  41667. */
  41668. this.gaussCoeff = 0.3;
  41669. /**
  41670. * Gaussian blur mean
  41671. * @type {number}
  41672. */
  41673. this.gaussMean = 1.0;
  41674. /**
  41675. * Gaussian blur standard deviation
  41676. * @type {number}
  41677. */
  41678. this.gaussStandDev = 0.8;
  41679. /**
  41680. * Gaussian blur multiplier. Multiplies the blur effect
  41681. * @type {number}
  41682. */
  41683. this.gaussMultiplier = 4.0;
  41684. // HDR
  41685. /**
  41686. * Exposure, controls the overall intensity of the pipeline
  41687. * @type {number}
  41688. */
  41689. this.exposure = 1.0;
  41690. /**
  41691. * Minimum luminance that the post-process can output. Luminance is >= 0
  41692. * @type {number}
  41693. */
  41694. this.minimumLuminance = 1.0;
  41695. /**
  41696. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  41697. * @type {number}
  41698. */
  41699. this.maximumLuminance = 1e20;
  41700. /**
  41701. * Increase rate for luminance: eye adaptation speed to dark
  41702. * @type {number}
  41703. */
  41704. this.luminanceIncreaserate = 0.5;
  41705. /**
  41706. * Decrease rate for luminance: eye adaptation speed to bright
  41707. * @type {number}
  41708. */
  41709. this.luminanceDecreaseRate = 0.5;
  41710. // Bright pass
  41711. /**
  41712. * Minimum luminance needed to compute HDR
  41713. * @type {number}
  41714. */
  41715. this.brightThreshold = 0.8;
  41716. this._needUpdate = true;
  41717. this._scene = scene;
  41718. // Bright pass
  41719. this._createBrightPassPostProcess(scene, ratio);
  41720. // Down sample X4
  41721. this._createDownSampleX4PostProcess(scene, ratio);
  41722. // Create gaussian blur post-processes
  41723. this._createGaussianBlurPostProcess(scene, ratio);
  41724. // Texture adder
  41725. this._createTextureAdderPostProcess(scene, ratio);
  41726. // Luminance generator
  41727. this._createLuminanceGeneratorPostProcess(scene);
  41728. // HDR
  41729. this._createHDRPostProcess(scene, ratio);
  41730. // Pass postprocess
  41731. if (originalPostProcess === null) {
  41732. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  41733. }
  41734. else {
  41735. this._originalPostProcess = originalPostProcess;
  41736. }
  41737. // Configure pipeline
  41738. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  41739. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  41740. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  41741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  41742. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  41743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  41744. var addDownSamplerPostProcess = function (id) {
  41745. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  41746. };
  41747. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  41748. addDownSamplerPostProcess(i);
  41749. }
  41750. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  41751. // Finish
  41752. scene.postProcessRenderPipelineManager.addPipeline(this);
  41753. if (cameras !== null) {
  41754. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  41755. }
  41756. this.update();
  41757. }
  41758. /**
  41759. * Tells the pipeline to update its post-processes
  41760. */
  41761. HDRRenderingPipeline.prototype.update = function () {
  41762. this._needUpdate = true;
  41763. };
  41764. /**
  41765. * Returns the current calculated luminance
  41766. */
  41767. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  41768. return this._hdrCurrentLuminance;
  41769. };
  41770. /**
  41771. * Returns the currently drawn luminance
  41772. */
  41773. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  41774. return this._hdrOutputLuminance;
  41775. };
  41776. /**
  41777. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  41778. */
  41779. HDRRenderingPipeline.prototype.dispose = function () {
  41780. this._originalPostProcess = undefined;
  41781. this._brightPassPostProcess = undefined;
  41782. this._downSampleX4PostProcess = undefined;
  41783. this._guassianBlurHPostProcess = undefined;
  41784. this._guassianBlurVPostProcess = undefined;
  41785. this._textureAdderPostProcess = undefined;
  41786. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  41787. this._downSamplePostProcesses[i] = undefined;
  41788. }
  41789. this._hdrPostProcess = undefined;
  41790. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  41791. };
  41792. /**
  41793. * Creates the HDR post-process and computes the luminance adaptation
  41794. */
  41795. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  41796. var _this = this;
  41797. var hdrLastLuminance = 0.0;
  41798. this._hdrOutputLuminance = -1.0;
  41799. this._hdrCurrentLuminance = 1.0;
  41800. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  41801. this._hdrPostProcess.onApply = function (effect) {
  41802. if (_this._hdrOutputLuminance < 0.0) {
  41803. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  41804. }
  41805. else {
  41806. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  41807. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  41808. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  41809. }
  41810. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  41811. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  41812. }
  41813. else {
  41814. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  41815. }
  41816. }
  41817. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  41818. hdrLastLuminance += scene.getEngine().getDeltaTime();
  41819. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  41820. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  41821. effect.setFloat("exposure", _this.exposure);
  41822. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  41823. _this._needUpdate = false;
  41824. };
  41825. };
  41826. /**
  41827. * Texture Adder post-process
  41828. */
  41829. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  41830. var _this = this;
  41831. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  41832. this._textureAdderPostProcess.onApply = function (effect) {
  41833. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  41834. };
  41835. };
  41836. /**
  41837. * Down sample X4 post-process
  41838. */
  41839. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  41840. var _this = this;
  41841. var downSampleX4Offsets = new Array(32);
  41842. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  41843. this._downSampleX4PostProcess.onApply = function (effect) {
  41844. if (_this._needUpdate) {
  41845. var id = 0;
  41846. for (var i = -2; i < 2; i++) {
  41847. for (var j = -2; j < 2; j++) {
  41848. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  41849. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  41850. id += 2;
  41851. }
  41852. }
  41853. }
  41854. effect.setArray2("dsOffsets", downSampleX4Offsets);
  41855. };
  41856. };
  41857. /**
  41858. * Bright pass post-process
  41859. */
  41860. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  41861. var _this = this;
  41862. var brightOffsets = new Array(8);
  41863. var brightPassCallback = function (effect) {
  41864. if (_this._needUpdate) {
  41865. var sU = (1.0 / _this._brightPassPostProcess.width);
  41866. var sV = (1.0 / _this._brightPassPostProcess.height);
  41867. brightOffsets[0] = -0.5 * sU;
  41868. brightOffsets[1] = 0.5 * sV;
  41869. brightOffsets[2] = 0.5 * sU;
  41870. brightOffsets[3] = 0.5 * sV;
  41871. brightOffsets[4] = -0.5 * sU;
  41872. brightOffsets[5] = -0.5 * sV;
  41873. brightOffsets[6] = 0.5 * sU;
  41874. brightOffsets[7] = -0.5 * sV;
  41875. }
  41876. effect.setArray2("dsOffsets", brightOffsets);
  41877. effect.setFloat("brightThreshold", _this.brightThreshold);
  41878. };
  41879. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  41880. this._brightPassPostProcess.onApply = brightPassCallback;
  41881. };
  41882. /**
  41883. * Luminance generator. Creates the luminance post-process and down sample post-processes
  41884. */
  41885. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  41886. var _this = this;
  41887. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  41888. var luminanceOffsets = new Array(8);
  41889. var downSampleOffsets = new Array(18);
  41890. var halfDestPixelSize;
  41891. this._downSamplePostProcesses = new Array(lumSteps);
  41892. // Utils for luminance
  41893. var luminanceUpdateSourceOffsets = function (width, height) {
  41894. var sU = (1.0 / width);
  41895. var sV = (1.0 / height);
  41896. luminanceOffsets[0] = -0.5 * sU;
  41897. luminanceOffsets[1] = 0.5 * sV;
  41898. luminanceOffsets[2] = 0.5 * sU;
  41899. luminanceOffsets[3] = 0.5 * sV;
  41900. luminanceOffsets[4] = -0.5 * sU;
  41901. luminanceOffsets[5] = -0.5 * sV;
  41902. luminanceOffsets[6] = 0.5 * sU;
  41903. luminanceOffsets[7] = -0.5 * sV;
  41904. };
  41905. var luminanceUpdateDestOffsets = function (width, height) {
  41906. var id = 0;
  41907. for (var x = -1; x < 2; x++) {
  41908. for (var y = -1; y < 2; y++) {
  41909. downSampleOffsets[id] = (x) / width;
  41910. downSampleOffsets[id + 1] = (y) / height;
  41911. id += 2;
  41912. }
  41913. }
  41914. };
  41915. // Luminance callback
  41916. var luminanceCallback = function (effect) {
  41917. if (_this._needUpdate) {
  41918. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  41919. }
  41920. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  41921. effect.setArray2("lumOffsets", luminanceOffsets);
  41922. };
  41923. // Down sample callbacks
  41924. var downSampleCallback = function (indice) {
  41925. var i = indice;
  41926. return function (effect) {
  41927. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41928. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41929. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  41930. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  41931. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  41932. effect.setArray2("dsOffsets", downSampleOffsets);
  41933. };
  41934. };
  41935. var downSampleAfterRenderCallback = function (effect) {
  41936. // Unpack result
  41937. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  41938. 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);
  41939. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  41940. };
  41941. // Create luminance post-process
  41942. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  41943. 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);
  41944. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  41945. // Create down sample post-processes
  41946. for (var i = lumSteps - 2; i >= 0; i--) {
  41947. var length = Math.pow(3, i);
  41948. ratio = { width: length, height: length };
  41949. var defines = "#define DOWN_SAMPLE\n";
  41950. if (i === 0) {
  41951. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  41952. }
  41953. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  41954. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  41955. if (i === 0) {
  41956. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  41957. }
  41958. }
  41959. };
  41960. /**
  41961. * Gaussian blur post-processes. Horizontal and Vertical
  41962. */
  41963. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  41964. var _this = this;
  41965. var blurOffsetsW = new Array(9);
  41966. var blurOffsetsH = new Array(9);
  41967. var blurWeights = new Array(9);
  41968. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  41969. // Utils for gaussian blur
  41970. var calculateBlurOffsets = function (height) {
  41971. var lastOutputDimensions = {
  41972. width: scene.getEngine().getRenderWidth(),
  41973. height: scene.getEngine().getRenderHeight()
  41974. };
  41975. for (var i = 0; i < 9; i++) {
  41976. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  41977. if (height) {
  41978. blurOffsetsH[i] = value;
  41979. }
  41980. else {
  41981. blurOffsetsW[i] = value;
  41982. }
  41983. }
  41984. };
  41985. var calculateWeights = function () {
  41986. var x = 0.0;
  41987. for (var i = 0; i < 9; i++) {
  41988. x = (i - 4.0) / 4.0;
  41989. 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));
  41990. }
  41991. };
  41992. // Callback
  41993. var gaussianBlurCallback = function (height) {
  41994. return function (effect) {
  41995. if (_this._needUpdate) {
  41996. calculateWeights();
  41997. calculateBlurOffsets(height);
  41998. }
  41999. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  42000. effect.setArray("blurWeights", blurWeights);
  42001. effect.setFloat("multiplier", _this.gaussMultiplier);
  42002. };
  42003. };
  42004. // Create horizontal gaussian blur post-processes
  42005. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  42006. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  42007. // Create vertical gaussian blur post-process
  42008. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  42009. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  42010. };
  42011. // Luminance generator
  42012. HDRRenderingPipeline.LUM_STEPS = 6;
  42013. return HDRRenderingPipeline;
  42014. })(BABYLON.PostProcessRenderPipeline);
  42015. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  42016. })(BABYLON || (BABYLON = {}));
  42017. var BABYLON;
  42018. (function (BABYLON) {
  42019. var FaceAdjacencies = (function () {
  42020. function FaceAdjacencies() {
  42021. this.edges = new Array();
  42022. this.edgesConnectedCount = 0;
  42023. }
  42024. return FaceAdjacencies;
  42025. })();
  42026. var EdgesRenderer = (function () {
  42027. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  42028. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  42029. if (epsilon === void 0) { epsilon = 0.95; }
  42030. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  42031. this.edgesWidthScalerForOrthographic = 1000.0;
  42032. this.edgesWidthScalerForPerspective = 50.0;
  42033. this._linesPositions = new Array();
  42034. this._linesNormals = new Array();
  42035. this._linesIndices = new Array();
  42036. this._buffers = new Array();
  42037. this._checkVerticesInsteadOfIndices = false;
  42038. this._source = source;
  42039. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  42040. this._epsilon = epsilon;
  42041. this._prepareRessources();
  42042. this._generateEdgesLines();
  42043. }
  42044. EdgesRenderer.prototype._prepareRessources = function () {
  42045. if (this._lineShader) {
  42046. return;
  42047. }
  42048. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  42049. attributes: ["position", "normal"],
  42050. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  42051. });
  42052. this._lineShader.disableDepthWrite = true;
  42053. this._lineShader.backFaceCulling = false;
  42054. };
  42055. EdgesRenderer.prototype.dispose = function () {
  42056. this._vb0.dispose();
  42057. this._vb1.dispose();
  42058. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  42059. this._lineShader.dispose();
  42060. };
  42061. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  42062. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  42063. return 0;
  42064. }
  42065. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  42066. return 1;
  42067. }
  42068. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  42069. return 2;
  42070. }
  42071. return -1;
  42072. };
  42073. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  42074. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  42075. return 0;
  42076. }
  42077. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  42078. return 1;
  42079. }
  42080. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  42081. return 2;
  42082. }
  42083. return -1;
  42084. };
  42085. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  42086. var needToCreateLine;
  42087. if (edge === undefined) {
  42088. needToCreateLine = true;
  42089. }
  42090. else {
  42091. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  42092. needToCreateLine = dotProduct < this._epsilon;
  42093. }
  42094. if (needToCreateLine) {
  42095. var offset = this._linesPositions.length / 3;
  42096. var normal = p0.subtract(p1);
  42097. normal.normalize();
  42098. // Positions
  42099. this._linesPositions.push(p0.x);
  42100. this._linesPositions.push(p0.y);
  42101. this._linesPositions.push(p0.z);
  42102. this._linesPositions.push(p0.x);
  42103. this._linesPositions.push(p0.y);
  42104. this._linesPositions.push(p0.z);
  42105. this._linesPositions.push(p1.x);
  42106. this._linesPositions.push(p1.y);
  42107. this._linesPositions.push(p1.z);
  42108. this._linesPositions.push(p1.x);
  42109. this._linesPositions.push(p1.y);
  42110. this._linesPositions.push(p1.z);
  42111. // Normals
  42112. this._linesNormals.push(p1.x);
  42113. this._linesNormals.push(p1.y);
  42114. this._linesNormals.push(p1.z);
  42115. this._linesNormals.push(-1);
  42116. this._linesNormals.push(p1.x);
  42117. this._linesNormals.push(p1.y);
  42118. this._linesNormals.push(p1.z);
  42119. this._linesNormals.push(1);
  42120. this._linesNormals.push(p0.x);
  42121. this._linesNormals.push(p0.y);
  42122. this._linesNormals.push(p0.z);
  42123. this._linesNormals.push(-1);
  42124. this._linesNormals.push(p0.x);
  42125. this._linesNormals.push(p0.y);
  42126. this._linesNormals.push(p0.z);
  42127. this._linesNormals.push(1);
  42128. // Indices
  42129. this._linesIndices.push(offset);
  42130. this._linesIndices.push(offset + 1);
  42131. this._linesIndices.push(offset + 2);
  42132. this._linesIndices.push(offset);
  42133. this._linesIndices.push(offset + 2);
  42134. this._linesIndices.push(offset + 3);
  42135. }
  42136. };
  42137. EdgesRenderer.prototype._generateEdgesLines = function () {
  42138. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42139. var indices = this._source.getIndices();
  42140. // First let's find adjacencies
  42141. var adjacencies = new Array();
  42142. var faceNormals = new Array();
  42143. var index;
  42144. var faceAdjacencies;
  42145. // Prepare faces
  42146. for (index = 0; index < indices.length; index += 3) {
  42147. faceAdjacencies = new FaceAdjacencies();
  42148. var p0Index = indices[index];
  42149. var p1Index = indices[index + 1];
  42150. var p2Index = indices[index + 2];
  42151. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  42152. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  42153. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  42154. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  42155. faceNormal.normalize();
  42156. faceNormals.push(faceNormal);
  42157. adjacencies.push(faceAdjacencies);
  42158. }
  42159. // Scan
  42160. for (index = 0; index < adjacencies.length; index++) {
  42161. faceAdjacencies = adjacencies[index];
  42162. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  42163. var otherFaceAdjacencies = adjacencies[otherIndex];
  42164. if (faceAdjacencies.edgesConnectedCount === 3) {
  42165. break;
  42166. }
  42167. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  42168. continue;
  42169. }
  42170. var otherP0 = indices[otherIndex * 3];
  42171. var otherP1 = indices[otherIndex * 3 + 1];
  42172. var otherP2 = indices[otherIndex * 3 + 2];
  42173. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  42174. var otherEdgeIndex;
  42175. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  42176. continue;
  42177. }
  42178. switch (edgeIndex) {
  42179. case 0:
  42180. if (this._checkVerticesInsteadOfIndices) {
  42181. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  42182. }
  42183. else {
  42184. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  42185. }
  42186. break;
  42187. case 1:
  42188. if (this._checkVerticesInsteadOfIndices) {
  42189. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  42190. }
  42191. else {
  42192. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  42193. }
  42194. break;
  42195. case 2:
  42196. if (this._checkVerticesInsteadOfIndices) {
  42197. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  42198. }
  42199. else {
  42200. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  42201. }
  42202. break;
  42203. }
  42204. if (otherEdgeIndex === -1) {
  42205. continue;
  42206. }
  42207. faceAdjacencies.edges[edgeIndex] = otherIndex;
  42208. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  42209. faceAdjacencies.edgesConnectedCount++;
  42210. otherFaceAdjacencies.edgesConnectedCount++;
  42211. if (faceAdjacencies.edgesConnectedCount === 3) {
  42212. break;
  42213. }
  42214. }
  42215. }
  42216. }
  42217. // Create lines
  42218. for (index = 0; index < adjacencies.length; index++) {
  42219. // 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
  42220. var current = adjacencies[index];
  42221. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  42222. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  42223. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  42224. }
  42225. // Merge into a single mesh
  42226. var engine = this._source.getScene().getEngine();
  42227. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  42228. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  42229. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  42230. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  42231. this._ib = engine.createIndexBuffer(this._linesIndices);
  42232. this._indicesCount = this._linesIndices.length;
  42233. };
  42234. EdgesRenderer.prototype.render = function () {
  42235. if (!this._lineShader.isReady()) {
  42236. return;
  42237. }
  42238. var scene = this._source.getScene();
  42239. var engine = scene.getEngine();
  42240. this._lineShader._preBind();
  42241. // VBOs
  42242. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  42243. scene.resetCachedMaterial();
  42244. this._lineShader.setColor4("color", this._source.edgesColor);
  42245. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  42246. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  42247. }
  42248. else {
  42249. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  42250. }
  42251. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  42252. this._lineShader.bind(this._source.getWorldMatrix());
  42253. // Draw order
  42254. engine.draw(true, 0, this._indicesCount);
  42255. this._lineShader.unbind();
  42256. engine.setDepthWrite(true);
  42257. };
  42258. return EdgesRenderer;
  42259. })();
  42260. BABYLON.EdgesRenderer = EdgesRenderer;
  42261. })(BABYLON || (BABYLON = {}));
  42262. var BABYLON;
  42263. (function (BABYLON) {
  42264. (function (TonemappingOperator) {
  42265. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  42266. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  42267. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  42268. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  42269. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  42270. var TonemappingOperator = BABYLON.TonemappingOperator;
  42271. ;
  42272. var TonemapPostProcess = (function (_super) {
  42273. __extends(TonemapPostProcess, _super);
  42274. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  42275. var _this = this;
  42276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  42277. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42278. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  42279. this._operator = _operator;
  42280. this.exposureAdjustment = exposureAdjustment;
  42281. var defines = "#define ";
  42282. if (this._operator === TonemappingOperator.Hable)
  42283. defines += "HABLE_TONEMAPPING";
  42284. else if (this._operator === TonemappingOperator.Reinhard)
  42285. defines += "REINHARD_TONEMAPPING";
  42286. else if (this._operator === TonemappingOperator.HejiDawson)
  42287. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  42288. else if (this._operator === TonemappingOperator.Photographic)
  42289. defines += "PHOTOGRAPHIC_TONEMAPPING";
  42290. //sadly a second call to create the effect.
  42291. this.updateEffect(defines);
  42292. this.onApply = function (effect) {
  42293. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  42294. };
  42295. }
  42296. return TonemapPostProcess;
  42297. })(BABYLON.PostProcess);
  42298. BABYLON.TonemapPostProcess = TonemapPostProcess;
  42299. })(BABYLON || (BABYLON = {}));
  42300. var BABYLON;
  42301. (function (BABYLON) {
  42302. var ReflectionProbe = (function () {
  42303. function ReflectionProbe(name, size, scene, generateMipMaps) {
  42304. var _this = this;
  42305. if (generateMipMaps === void 0) { generateMipMaps = true; }
  42306. this.name = name;
  42307. this._viewMatrix = BABYLON.Matrix.Identity();
  42308. this._target = BABYLON.Vector3.Zero();
  42309. this._add = BABYLON.Vector3.Zero();
  42310. this.invertYAxis = false;
  42311. this.position = BABYLON.Vector3.Zero();
  42312. this._scene = scene;
  42313. this._scene.reflectionProbes.push(this);
  42314. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  42315. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  42316. switch (faceIndex) {
  42317. case 0:
  42318. _this._add.copyFromFloats(1, 0, 0);
  42319. break;
  42320. case 1:
  42321. _this._add.copyFromFloats(-1, 0, 0);
  42322. break;
  42323. case 2:
  42324. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  42325. break;
  42326. case 3:
  42327. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  42328. break;
  42329. case 4:
  42330. _this._add.copyFromFloats(0, 0, 1);
  42331. break;
  42332. case 5:
  42333. _this._add.copyFromFloats(0, 0, -1);
  42334. break;
  42335. }
  42336. if (_this._attachedMesh) {
  42337. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  42338. }
  42339. _this.position.addToRef(_this._add, _this._target);
  42340. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  42341. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  42342. };
  42343. this._renderTargetTexture.onAfterUnbind = function () {
  42344. scene.updateTransformMatrix(true);
  42345. };
  42346. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  42347. }
  42348. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  42349. get: function () {
  42350. return this._renderTargetTexture.refreshRate;
  42351. },
  42352. set: function (value) {
  42353. this._renderTargetTexture.refreshRate = value;
  42354. },
  42355. enumerable: true,
  42356. configurable: true
  42357. });
  42358. ReflectionProbe.prototype.getScene = function () {
  42359. return this._scene;
  42360. };
  42361. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  42362. get: function () {
  42363. return this._renderTargetTexture;
  42364. },
  42365. enumerable: true,
  42366. configurable: true
  42367. });
  42368. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  42369. get: function () {
  42370. return this._renderTargetTexture.renderList;
  42371. },
  42372. enumerable: true,
  42373. configurable: true
  42374. });
  42375. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  42376. this._attachedMesh = mesh;
  42377. };
  42378. ReflectionProbe.prototype.dispose = function () {
  42379. var index = this._scene.reflectionProbes.indexOf(this);
  42380. if (index !== -1) {
  42381. // Remove from the scene if found
  42382. this._scene.reflectionProbes.splice(index, 1);
  42383. }
  42384. if (this._renderTargetTexture) {
  42385. this._renderTargetTexture.dispose();
  42386. this._renderTargetTexture = null;
  42387. }
  42388. };
  42389. return ReflectionProbe;
  42390. })();
  42391. BABYLON.ReflectionProbe = ReflectionProbe;
  42392. })(BABYLON || (BABYLON = {}));
  42393. var BABYLON;
  42394. (function (BABYLON) {
  42395. var SolidParticle = (function () {
  42396. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  42397. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  42398. this.position = BABYLON.Vector3.Zero(); // position
  42399. this.rotation = BABYLON.Vector3.Zero(); // rotation
  42400. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  42401. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  42402. this.velocity = BABYLON.Vector3.Zero(); // velocity
  42403. this.alive = true; // alive
  42404. this.idx = particleIndex;
  42405. this._pos = positionIndex;
  42406. this._model = model;
  42407. this.shapeId = shapeId;
  42408. this.idxInShape = idxInShape;
  42409. }
  42410. Object.defineProperty(SolidParticle.prototype, "scale", {
  42411. //legacy support, changed scale to scaling
  42412. get: function () {
  42413. return this.scaling;
  42414. },
  42415. set: function (scale) {
  42416. this.scaling = scale;
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  42422. //legacy support, changed quaternion to rotationQuaternion
  42423. get: function () {
  42424. return this.rotationQuaternion;
  42425. },
  42426. set: function (q) {
  42427. this.rotationQuaternion = q;
  42428. },
  42429. enumerable: true,
  42430. configurable: true
  42431. });
  42432. return SolidParticle;
  42433. })();
  42434. BABYLON.SolidParticle = SolidParticle;
  42435. var ModelShape = (function () {
  42436. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  42437. this.shapeID = id;
  42438. this._shape = shape;
  42439. this._shapeUV = shapeUV;
  42440. this._positionFunction = posFunction;
  42441. this._vertexFunction = vtxFunction;
  42442. }
  42443. return ModelShape;
  42444. })();
  42445. BABYLON.ModelShape = ModelShape;
  42446. })(BABYLON || (BABYLON = {}));
  42447. var BABYLON;
  42448. (function (BABYLON) {
  42449. /**
  42450. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  42451. */
  42452. var SolidParticleSystem = (function () {
  42453. /**
  42454. * Creates a SPS (Solid Particle System) object.
  42455. * `name` (String) is the SPS name, this will be the underlying mesh name.
  42456. * `scene` (Scene) is the scene in which the SPS is added.
  42457. * `updatableè (default true) : if the SPS must be updatable or immutable.
  42458. * `isPickable` (default false) : if the solid particles must be pickable.
  42459. */
  42460. function SolidParticleSystem(name, scene, options) {
  42461. // public members
  42462. /**
  42463. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  42464. * Example : var p = SPS.particles[i];
  42465. */
  42466. this.particles = new Array();
  42467. /**
  42468. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  42469. */
  42470. this.nbParticles = 0;
  42471. /**
  42472. * If the particles must ever face the camera (default false). Useful for planar particles.
  42473. */
  42474. this.billboard = false;
  42475. /**
  42476. * This a counter ofr your own usage. It's not set by any SPS functions.
  42477. */
  42478. this.counter = 0;
  42479. /**
  42480. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  42481. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  42482. */
  42483. this.vars = {};
  42484. this._positions = new Array();
  42485. this._indices = new Array();
  42486. this._normals = new Array();
  42487. this._colors = new Array();
  42488. this._uvs = new Array();
  42489. this._index = 0; // indices index
  42490. this._updatable = true;
  42491. this._pickable = false;
  42492. this._isVisibilityBoxLocked = false;
  42493. this._alwaysVisible = false;
  42494. this._shapeCounter = 0;
  42495. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  42496. this._color = new BABYLON.Color4(0, 0, 0, 0);
  42497. this._computeParticleColor = true;
  42498. this._computeParticleTexture = true;
  42499. this._computeParticleRotation = true;
  42500. this._computeParticleVertex = false;
  42501. this._computeBoundingBox = false;
  42502. this._cam_axisZ = BABYLON.Vector3.Zero();
  42503. this._cam_axisY = BABYLON.Vector3.Zero();
  42504. this._cam_axisX = BABYLON.Vector3.Zero();
  42505. this._axisX = BABYLON.Axis.X;
  42506. this._axisY = BABYLON.Axis.Y;
  42507. this._axisZ = BABYLON.Axis.Z;
  42508. this._fakeCamPos = BABYLON.Vector3.Zero();
  42509. this._rotMatrix = new BABYLON.Matrix();
  42510. this._invertMatrix = new BABYLON.Matrix();
  42511. this._rotated = BABYLON.Vector3.Zero();
  42512. this._quaternion = new BABYLON.Quaternion();
  42513. this._vertex = BABYLON.Vector3.Zero();
  42514. this._normal = BABYLON.Vector3.Zero();
  42515. this._yaw = 0.0;
  42516. this._pitch = 0.0;
  42517. this._roll = 0.0;
  42518. this._halfroll = 0.0;
  42519. this._halfpitch = 0.0;
  42520. this._halfyaw = 0.0;
  42521. this._sinRoll = 0.0;
  42522. this._cosRoll = 0.0;
  42523. this._sinPitch = 0.0;
  42524. this._cosPitch = 0.0;
  42525. this._sinYaw = 0.0;
  42526. this._cosYaw = 0.0;
  42527. this._w = 0.0;
  42528. this._minimum = BABYLON.Tmp.Vector3[0];
  42529. this._maximum = BABYLON.Tmp.Vector3[1];
  42530. this.name = name;
  42531. this._scene = scene;
  42532. this._camera = scene.activeCamera;
  42533. this._pickable = options ? options.isPickable : false;
  42534. if (options && options.updatable) {
  42535. this._updatable = options.updatable;
  42536. }
  42537. else {
  42538. this._updatable = true;
  42539. }
  42540. if (this._pickable) {
  42541. this.pickedParticles = [];
  42542. }
  42543. }
  42544. /**
  42545. * Builds the SPS underlying mesh. Returns a standard Mesh.
  42546. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  42547. */
  42548. SolidParticleSystem.prototype.buildMesh = function () {
  42549. if (this.nbParticles === 0) {
  42550. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  42551. this.addShape(triangle, 1);
  42552. triangle.dispose();
  42553. }
  42554. this._positions32 = new Float32Array(this._positions);
  42555. this._uvs32 = new Float32Array(this._uvs);
  42556. this._colors32 = new Float32Array(this._colors);
  42557. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  42558. this._normals32 = new Float32Array(this._normals);
  42559. this._fixedNormal32 = new Float32Array(this._normals);
  42560. var vertexData = new BABYLON.VertexData();
  42561. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  42562. vertexData.indices = this._indices;
  42563. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  42564. if (this._uvs32) {
  42565. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  42566. ;
  42567. }
  42568. if (this._colors32) {
  42569. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  42570. }
  42571. var mesh = new BABYLON.Mesh(this.name, this._scene);
  42572. vertexData.applyToMesh(mesh, this._updatable);
  42573. this.mesh = mesh;
  42574. this.mesh.isPickable = this._pickable;
  42575. // free memory
  42576. this._positions = null;
  42577. this._normals = null;
  42578. this._uvs = null;
  42579. this._colors = null;
  42580. if (!this._updatable) {
  42581. this.particles.length = 0;
  42582. }
  42583. return mesh;
  42584. };
  42585. /**
  42586. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  42587. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  42588. * Thus the particles generated from `digest()` have their property `position` set yet.
  42589. * `mesh` (`Mesh`) is the mesh to be digested
  42590. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  42591. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  42592. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  42593. */
  42594. SolidParticleSystem.prototype.digest = function (mesh, options) {
  42595. var size = (options && options.facetNb) || 1;
  42596. var number = (options && options.number);
  42597. var delta = (options && options.delta) || 0;
  42598. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42599. var meshInd = mesh.getIndices();
  42600. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42601. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42602. var f = 0; // facet counter
  42603. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  42604. // compute size from number
  42605. if (number) {
  42606. number = (number > totalFacets) ? totalFacets : number;
  42607. size = Math.round(totalFacets / number);
  42608. delta = 0;
  42609. }
  42610. else {
  42611. size = (size > totalFacets) ? totalFacets : size;
  42612. }
  42613. var facetPos = []; // submesh positions
  42614. var facetInd = []; // submesh indices
  42615. var facetUV = []; // submesh UV
  42616. var facetCol = []; // submesh colors
  42617. var barycenter = BABYLON.Tmp.Vector3[0];
  42618. var rand;
  42619. var sizeO = size;
  42620. while (f < totalFacets) {
  42621. size = sizeO + Math.floor((1 + delta) * Math.random());
  42622. if (f > totalFacets - size) {
  42623. size = totalFacets - f;
  42624. }
  42625. // reset temp arrays
  42626. facetPos.length = 0;
  42627. facetInd.length = 0;
  42628. facetUV.length = 0;
  42629. facetCol.length = 0;
  42630. // iterate over "size" facets
  42631. var fi = 0;
  42632. for (var j = f * 3; j < (f + size) * 3; j++) {
  42633. facetInd.push(fi);
  42634. var i = meshInd[j];
  42635. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  42636. if (meshUV) {
  42637. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  42638. }
  42639. if (meshCol) {
  42640. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  42641. }
  42642. fi++;
  42643. }
  42644. // create a model shape for each single particle
  42645. var idx = this.nbParticles;
  42646. var shape = this._posToShape(facetPos);
  42647. var shapeUV = this._uvsToShapeUV(facetUV);
  42648. // compute the barycenter of the shape
  42649. var v;
  42650. for (v = 0; v < shape.length; v++) {
  42651. barycenter.addInPlace(shape[v]);
  42652. }
  42653. barycenter.scaleInPlace(1 / shape.length);
  42654. // shift the shape from its barycenter to the origin
  42655. for (v = 0; v < shape.length; v++) {
  42656. shape[v].subtractInPlace(barycenter);
  42657. }
  42658. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  42659. // add the particle in the SPS
  42660. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  42661. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  42662. // initialize the particle position
  42663. this.particles[this.nbParticles].position.addInPlace(barycenter);
  42664. this._index += shape.length;
  42665. idx++;
  42666. this.nbParticles++;
  42667. this._shapeCounter++;
  42668. f += size;
  42669. }
  42670. return this;
  42671. };
  42672. //reset copy
  42673. SolidParticleSystem.prototype._resetCopy = function () {
  42674. this._copy.position.x = 0;
  42675. this._copy.position.y = 0;
  42676. this._copy.position.z = 0;
  42677. this._copy.rotation.x = 0;
  42678. this._copy.rotation.y = 0;
  42679. this._copy.rotation.z = 0;
  42680. this._copy.rotationQuaternion = null;
  42681. this._copy.scaling.x = 1;
  42682. this._copy.scaling.y = 1;
  42683. this._copy.scaling.z = 1;
  42684. this._copy.uvs.x = 0;
  42685. this._copy.uvs.y = 0;
  42686. this._copy.uvs.z = 1;
  42687. this._copy.uvs.w = 1;
  42688. this._copy.color = null;
  42689. };
  42690. // _meshBuilder : inserts the shape model in the global SPS mesh
  42691. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  42692. var i;
  42693. var u = 0;
  42694. var c = 0;
  42695. this._resetCopy();
  42696. if (options && options.positionFunction) {
  42697. options.positionFunction(this._copy, idx, idxInShape);
  42698. }
  42699. if (this._copy.rotationQuaternion) {
  42700. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42701. }
  42702. else {
  42703. this._yaw = this._copy.rotation.y;
  42704. this._pitch = this._copy.rotation.x;
  42705. this._roll = this._copy.rotation.z;
  42706. this._quaternionRotationYPR();
  42707. }
  42708. this._quaternionToRotationMatrix();
  42709. for (i = 0; i < shape.length; i++) {
  42710. this._vertex.x = shape[i].x;
  42711. this._vertex.y = shape[i].y;
  42712. this._vertex.z = shape[i].z;
  42713. if (options && options.vertexFunction) {
  42714. options.vertexFunction(this._copy, this._vertex, i);
  42715. }
  42716. this._vertex.x *= this._copy.scaling.x;
  42717. this._vertex.y *= this._copy.scaling.y;
  42718. this._vertex.z *= this._copy.scaling.z;
  42719. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42720. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  42721. if (meshUV) {
  42722. 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);
  42723. u += 2;
  42724. }
  42725. if (this._copy.color) {
  42726. this._color = this._copy.color;
  42727. }
  42728. else if (meshCol && meshCol[c]) {
  42729. this._color.r = meshCol[c];
  42730. this._color.g = meshCol[c + 1];
  42731. this._color.b = meshCol[c + 2];
  42732. this._color.a = meshCol[c + 3];
  42733. }
  42734. else {
  42735. this._color.r = 1;
  42736. this._color.g = 1;
  42737. this._color.b = 1;
  42738. this._color.a = 1;
  42739. }
  42740. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  42741. c += 4;
  42742. }
  42743. for (i = 0; i < meshInd.length; i++) {
  42744. indices.push(p + meshInd[i]);
  42745. }
  42746. if (this._pickable) {
  42747. var nbfaces = meshInd.length / 3;
  42748. for (i = 0; i < nbfaces; i++) {
  42749. this.pickedParticles.push({ idx: idx, faceId: i });
  42750. }
  42751. }
  42752. };
  42753. // returns a shape array from positions array
  42754. SolidParticleSystem.prototype._posToShape = function (positions) {
  42755. var shape = [];
  42756. for (var i = 0; i < positions.length; i += 3) {
  42757. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  42758. }
  42759. return shape;
  42760. };
  42761. // returns a shapeUV array from a Vector4 uvs
  42762. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  42763. var shapeUV = [];
  42764. if (uvs) {
  42765. for (var i = 0; i < uvs.length; i++)
  42766. shapeUV.push(uvs[i]);
  42767. }
  42768. return shapeUV;
  42769. };
  42770. // adds a new particle object in the particles array
  42771. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  42772. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  42773. };
  42774. /**
  42775. * Adds some particles to the SPS from the model shape. Returns the shape id.
  42776. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  42777. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  42778. * `nb` (positive integer) the number of particles to be created from this model
  42779. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  42780. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  42781. */
  42782. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  42783. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42784. var meshInd = mesh.getIndices();
  42785. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42786. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42787. var shape = this._posToShape(meshPos);
  42788. var shapeUV = this._uvsToShapeUV(meshUV);
  42789. var posfunc = options ? options.positionFunction : null;
  42790. var vtxfunc = options ? options.vertexFunction : null;
  42791. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  42792. // particles
  42793. var idx = this.nbParticles;
  42794. for (var i = 0; i < nb; i++) {
  42795. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  42796. if (this._updatable) {
  42797. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  42798. }
  42799. this._index += shape.length;
  42800. idx++;
  42801. }
  42802. this.nbParticles += nb;
  42803. this._shapeCounter++;
  42804. return this._shapeCounter - 1;
  42805. };
  42806. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  42807. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  42808. this._resetCopy();
  42809. if (particle._model._positionFunction) {
  42810. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  42811. }
  42812. if (this._copy.rotationQuaternion) {
  42813. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42814. }
  42815. else {
  42816. this._yaw = this._copy.rotation.y;
  42817. this._pitch = this._copy.rotation.x;
  42818. this._roll = this._copy.rotation.z;
  42819. this._quaternionRotationYPR();
  42820. }
  42821. this._quaternionToRotationMatrix();
  42822. this._shape = particle._model._shape;
  42823. for (var pt = 0; pt < this._shape.length; pt++) {
  42824. this._vertex.x = this._shape[pt].x;
  42825. this._vertex.y = this._shape[pt].y;
  42826. this._vertex.z = this._shape[pt].z;
  42827. if (particle._model._vertexFunction) {
  42828. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  42829. }
  42830. this._vertex.x *= this._copy.scaling.x;
  42831. this._vertex.y *= this._copy.scaling.y;
  42832. this._vertex.z *= this._copy.scaling.z;
  42833. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42834. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  42835. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  42836. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  42837. }
  42838. particle.position.x = 0;
  42839. particle.position.y = 0;
  42840. particle.position.z = 0;
  42841. particle.rotation.x = 0;
  42842. particle.rotation.y = 0;
  42843. particle.rotation.z = 0;
  42844. particle.rotationQuaternion = null;
  42845. particle.scaling.x = 1;
  42846. particle.scaling.y = 1;
  42847. particle.scaling.z = 1;
  42848. };
  42849. /**
  42850. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  42851. */
  42852. SolidParticleSystem.prototype.rebuildMesh = function () {
  42853. for (var p = 0; p < this.particles.length; p++) {
  42854. this._rebuildParticle(this.particles[p]);
  42855. }
  42856. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42857. };
  42858. /**
  42859. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  42860. * This method calls `updateParticle()` for each particle of the SPS.
  42861. * For an animated SPS, it is usually called within the render loop.
  42862. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  42863. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  42864. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  42865. */
  42866. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  42867. if (start === void 0) { start = 0; }
  42868. if (end === void 0) { end = this.nbParticles - 1; }
  42869. if (update === void 0) { update = true; }
  42870. if (!this._updatable) {
  42871. return;
  42872. }
  42873. // custom beforeUpdate
  42874. this.beforeUpdateParticles(start, end, update);
  42875. this._cam_axisX.x = 1;
  42876. this._cam_axisX.y = 0;
  42877. this._cam_axisX.z = 0;
  42878. this._cam_axisY.x = 0;
  42879. this._cam_axisY.y = 1;
  42880. this._cam_axisY.z = 0;
  42881. this._cam_axisZ.x = 0;
  42882. this._cam_axisZ.y = 0;
  42883. this._cam_axisZ.z = 1;
  42884. // if the particles will always face the camera
  42885. if (this.billboard) {
  42886. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  42887. this._yaw = this.mesh.rotation.y;
  42888. this._pitch = this.mesh.rotation.x;
  42889. this._roll = this.mesh.rotation.z;
  42890. this._quaternionRotationYPR();
  42891. this._quaternionToRotationMatrix();
  42892. this._rotMatrix.invertToRef(this._invertMatrix);
  42893. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  42894. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  42895. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  42896. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  42897. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  42898. this._cam_axisY.normalize();
  42899. this._cam_axisX.normalize();
  42900. this._cam_axisZ.normalize();
  42901. }
  42902. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  42903. var idx = 0;
  42904. var index = 0;
  42905. var colidx = 0;
  42906. var colorIndex = 0;
  42907. var uvidx = 0;
  42908. var uvIndex = 0;
  42909. if (this._computeBoundingBox) {
  42910. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  42911. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  42912. }
  42913. // particle loop
  42914. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  42915. for (var p = start; p <= end; p++) {
  42916. this._particle = this.particles[p];
  42917. this._shape = this._particle._model._shape;
  42918. this._shapeUV = this._particle._model._shapeUV;
  42919. // call to custom user function to update the particle properties
  42920. this.updateParticle(this._particle);
  42921. // particle rotation matrix
  42922. if (this.billboard) {
  42923. this._particle.rotation.x = 0.0;
  42924. this._particle.rotation.y = 0.0;
  42925. }
  42926. if (this._computeParticleRotation) {
  42927. if (this._particle.rotationQuaternion) {
  42928. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42929. }
  42930. else {
  42931. this._yaw = this._particle.rotation.y;
  42932. this._pitch = this._particle.rotation.x;
  42933. this._roll = this._particle.rotation.z;
  42934. this._quaternionRotationYPR();
  42935. }
  42936. this._quaternionToRotationMatrix();
  42937. }
  42938. for (var pt = 0; pt < this._shape.length; pt++) {
  42939. idx = index + pt * 3;
  42940. colidx = colorIndex + pt * 4;
  42941. uvidx = uvIndex + pt * 2;
  42942. this._vertex.x = this._shape[pt].x;
  42943. this._vertex.y = this._shape[pt].y;
  42944. this._vertex.z = this._shape[pt].z;
  42945. if (this._computeParticleVertex) {
  42946. this.updateParticleVertex(this._particle, this._vertex, pt);
  42947. }
  42948. // positions
  42949. this._vertex.x *= this._particle.scaling.x;
  42950. this._vertex.y *= this._particle.scaling.y;
  42951. this._vertex.z *= this._particle.scaling.z;
  42952. 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];
  42953. 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;
  42954. 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;
  42955. 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;
  42956. 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;
  42957. 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;
  42958. 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;
  42959. if (this._computeBoundingBox) {
  42960. if (this._positions32[idx] < this._minimum.x) {
  42961. this._minimum.x = this._positions32[idx];
  42962. }
  42963. if (this._positions32[idx] > this._maximum.x) {
  42964. this._maximum.x = this._positions32[idx];
  42965. }
  42966. if (this._positions32[idx + 1] < this._minimum.y) {
  42967. this._minimum.y = this._positions32[idx + 1];
  42968. }
  42969. if (this._positions32[idx + 1] > this._maximum.y) {
  42970. this._maximum.y = this._positions32[idx + 1];
  42971. }
  42972. if (this._positions32[idx + 2] < this._minimum.z) {
  42973. this._minimum.z = this._positions32[idx + 2];
  42974. }
  42975. if (this._positions32[idx + 2] > this._maximum.z) {
  42976. this._maximum.z = this._positions32[idx + 2];
  42977. }
  42978. }
  42979. // normals : if the particles can't be morphed then just rotate the normals
  42980. if (!this._computeParticleVertex && !this.billboard) {
  42981. this._normal.x = this._fixedNormal32[idx];
  42982. this._normal.y = this._fixedNormal32[idx + 1];
  42983. this._normal.z = this._fixedNormal32[idx + 2];
  42984. 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];
  42985. 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;
  42986. 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;
  42987. 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;
  42988. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42989. 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;
  42990. 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;
  42991. }
  42992. if (this._computeParticleColor) {
  42993. this._colors32[colidx] = this._particle.color.r;
  42994. this._colors32[colidx + 1] = this._particle.color.g;
  42995. this._colors32[colidx + 2] = this._particle.color.b;
  42996. this._colors32[colidx + 3] = this._particle.color.a;
  42997. }
  42998. if (this._computeParticleTexture) {
  42999. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  43000. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  43001. }
  43002. }
  43003. index = idx + 3;
  43004. colorIndex = colidx + 4;
  43005. uvIndex = uvidx + 2;
  43006. }
  43007. if (update) {
  43008. if (this._computeParticleColor) {
  43009. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  43010. }
  43011. if (this._computeParticleTexture) {
  43012. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  43013. }
  43014. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  43015. if (!this.mesh.areNormalsFrozen) {
  43016. if (this._computeParticleVertex || this.billboard) {
  43017. // recompute the normals only if the particles can be morphed, update then the normal reference array
  43018. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  43019. for (var i = 0; i < this._normals32.length; i++) {
  43020. this._fixedNormal32[i] = this._normals32[i];
  43021. }
  43022. }
  43023. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  43024. }
  43025. }
  43026. if (this._computeBoundingBox) {
  43027. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  43028. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  43029. }
  43030. this.afterUpdateParticles(start, end, update);
  43031. };
  43032. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  43033. this._halfroll = this._roll * 0.5;
  43034. this._halfpitch = this._pitch * 0.5;
  43035. this._halfyaw = this._yaw * 0.5;
  43036. this._sinRoll = Math.sin(this._halfroll);
  43037. this._cosRoll = Math.cos(this._halfroll);
  43038. this._sinPitch = Math.sin(this._halfpitch);
  43039. this._cosPitch = Math.cos(this._halfpitch);
  43040. this._sinYaw = Math.sin(this._halfyaw);
  43041. this._cosYaw = Math.cos(this._halfyaw);
  43042. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  43043. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  43044. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  43045. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  43046. };
  43047. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  43048. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  43049. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  43050. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  43051. this._rotMatrix.m[3] = 0;
  43052. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  43053. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  43054. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  43055. this._rotMatrix.m[7] = 0;
  43056. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  43057. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  43058. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  43059. this._rotMatrix.m[11] = 0;
  43060. this._rotMatrix.m[12] = 0;
  43061. this._rotMatrix.m[13] = 0;
  43062. this._rotMatrix.m[14] = 0;
  43063. this._rotMatrix.m[15] = 1.0;
  43064. };
  43065. /**
  43066. * Disposes the SPS
  43067. */
  43068. SolidParticleSystem.prototype.dispose = function () {
  43069. this.mesh.dispose();
  43070. this.vars = null;
  43071. // drop references to internal big arrays for the GC
  43072. this._positions = null;
  43073. this._indices = null;
  43074. this._normals = null;
  43075. this._uvs = null;
  43076. this._colors = null;
  43077. this._positions32 = null;
  43078. this._normals32 = null;
  43079. this._fixedNormal32 = null;
  43080. this._uvs32 = null;
  43081. this._colors32 = null;
  43082. this.pickedParticles = null;
  43083. };
  43084. /**
  43085. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  43086. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  43087. */
  43088. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  43089. if (!this._isVisibilityBoxLocked) {
  43090. this.mesh.refreshBoundingInfo();
  43091. }
  43092. };
  43093. /**
  43094. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  43095. * @param size the size (float) of the visibility box
  43096. * note : this doesn't lock the SPS mesh bounding box.
  43097. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  43098. */
  43099. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  43100. var vis = size / 2;
  43101. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  43102. };
  43103. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  43104. // getter and setter
  43105. get: function () {
  43106. return this._alwaysVisible;
  43107. },
  43108. /**
  43109. * Sets the SPS as always visible or not
  43110. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  43111. */
  43112. set: function (val) {
  43113. this._alwaysVisible = val;
  43114. this.mesh.alwaysSelectAsActiveMesh = val;
  43115. },
  43116. enumerable: true,
  43117. configurable: true
  43118. });
  43119. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  43120. get: function () {
  43121. return this._isVisibilityBoxLocked;
  43122. },
  43123. /**
  43124. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  43125. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  43126. */
  43127. set: function (val) {
  43128. this._isVisibilityBoxLocked = val;
  43129. this.mesh.getBoundingInfo().isLocked = val;
  43130. },
  43131. enumerable: true,
  43132. configurable: true
  43133. });
  43134. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  43135. // getters
  43136. get: function () {
  43137. return this._computeParticleRotation;
  43138. },
  43139. // Optimizer setters
  43140. /**
  43141. * Tells to `setParticles()` to compute the particle rotations or not.
  43142. * Default value : true. The SPS is faster when it's set to false.
  43143. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  43144. */
  43145. set: function (val) {
  43146. this._computeParticleRotation = val;
  43147. },
  43148. enumerable: true,
  43149. configurable: true
  43150. });
  43151. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  43152. get: function () {
  43153. return this._computeParticleColor;
  43154. },
  43155. /**
  43156. * Tells to `setParticles()` to compute the particle colors or not.
  43157. * Default value : true. The SPS is faster when it's set to false.
  43158. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  43159. */
  43160. set: function (val) {
  43161. this._computeParticleColor = val;
  43162. },
  43163. enumerable: true,
  43164. configurable: true
  43165. });
  43166. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  43167. get: function () {
  43168. return this._computeParticleTexture;
  43169. },
  43170. /**
  43171. * Tells to `setParticles()` to compute the particle textures or not.
  43172. * Default value : true. The SPS is faster when it's set to false.
  43173. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  43174. */
  43175. set: function (val) {
  43176. this._computeParticleTexture = val;
  43177. },
  43178. enumerable: true,
  43179. configurable: true
  43180. });
  43181. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  43182. get: function () {
  43183. return this._computeParticleVertex;
  43184. },
  43185. /**
  43186. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  43187. * Default value : false. The SPS is faster when it's set to false.
  43188. * Note : the particle custom vertex positions aren't stored values.
  43189. */
  43190. set: function (val) {
  43191. this._computeParticleVertex = val;
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  43197. get: function () {
  43198. return this._computeBoundingBox;
  43199. },
  43200. /**
  43201. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  43202. */
  43203. set: function (val) {
  43204. this._computeBoundingBox = val;
  43205. },
  43206. enumerable: true,
  43207. configurable: true
  43208. });
  43209. // =======================================================================
  43210. // Particle behavior logic
  43211. // these following methods may be overwritten by the user to fit his needs
  43212. /**
  43213. * This function does nothing. It may be overwritten to set all the particle first values.
  43214. * The SPS doesn't call this function, you may have to call it by your own.
  43215. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  43216. */
  43217. SolidParticleSystem.prototype.initParticles = function () {
  43218. };
  43219. /**
  43220. * This function does nothing. It may be overwritten to recycle a particle.
  43221. * The SPS doesn't call this function, you may have to call it by your own.
  43222. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  43223. */
  43224. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  43225. return particle;
  43226. };
  43227. /**
  43228. * Updates a particle : this function should be overwritten by the user.
  43229. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  43230. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  43231. * ex : just set a particle position or velocity and recycle conditions
  43232. */
  43233. SolidParticleSystem.prototype.updateParticle = function (particle) {
  43234. return particle;
  43235. };
  43236. /**
  43237. * Updates a vertex of a particle : it can be overwritten by the user.
  43238. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  43239. * @param particle the current particle
  43240. * @param vertex the current index of the current particle
  43241. * @param pt the index of the current vertex in the particle shape
  43242. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  43243. * ex : just set a vertex particle position
  43244. */
  43245. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  43246. return vertex;
  43247. };
  43248. /**
  43249. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  43250. * This does nothing and may be overwritten by the user.
  43251. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43252. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43253. * @param update the boolean update value actually passed to setParticles()
  43254. */
  43255. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  43256. };
  43257. /**
  43258. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  43259. * This will be passed three parameters.
  43260. * This does nothing and may be overwritten by the user.
  43261. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43262. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43263. * @param update the boolean update value actually passed to setParticles()
  43264. */
  43265. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  43266. };
  43267. return SolidParticleSystem;
  43268. })();
  43269. BABYLON.SolidParticleSystem = SolidParticleSystem;
  43270. })(BABYLON || (BABYLON = {}));
  43271. var BABYLON;
  43272. (function (BABYLON) {
  43273. var Internals;
  43274. (function (Internals) {
  43275. var FileFaceOrientation = (function () {
  43276. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43277. this.name = name;
  43278. this.worldAxisForNormal = worldAxisForNormal;
  43279. this.worldAxisForFileX = worldAxisForFileX;
  43280. this.worldAxisForFileY = worldAxisForFileY;
  43281. }
  43282. return FileFaceOrientation;
  43283. })();
  43284. ;
  43285. /**
  43286. * Helper class dealing with the extraction of spherical polynomial dataArray
  43287. * from a cube map.
  43288. */
  43289. var CubeMapToSphericalPolynomialTools = (function () {
  43290. function CubeMapToSphericalPolynomialTools() {
  43291. }
  43292. /**
  43293. * Converts a cubemap to the according Spherical Polynomial data.
  43294. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43295. *
  43296. * @param cubeInfo The Cube map to extract the information from.
  43297. * @return The Spherical Polynomial data.
  43298. */
  43299. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43300. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43301. var totalSolidAngle = 0.0;
  43302. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43303. var du = 2.0 / cubeInfo.size;
  43304. var dv = du;
  43305. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43306. var minUV = du * 0.5 - 1.0;
  43307. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43308. var fileFace = this.FileFaces[faceIndex];
  43309. var dataArray = cubeInfo[fileFace.name];
  43310. var v = minUV;
  43311. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43312. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43313. // Because SP is still linear, so summation is fine in that basis.
  43314. for (var y = 0; y < cubeInfo.size; y++) {
  43315. var u = minUV;
  43316. for (var x = 0; x < cubeInfo.size; x++) {
  43317. // World direction (not normalised)
  43318. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43319. worldDirection.normalize();
  43320. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43321. if (1) {
  43322. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  43323. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  43324. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  43325. var color = new BABYLON.Color3(r, g, b);
  43326. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43327. }
  43328. else {
  43329. if (faceIndex == 0) {
  43330. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  43331. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  43332. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  43333. }
  43334. else if (faceIndex == 1) {
  43335. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  43336. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  43337. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  43338. }
  43339. else if (faceIndex == 2) {
  43340. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  43341. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  43342. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  43343. }
  43344. else if (faceIndex == 3) {
  43345. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  43346. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  43347. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  43348. }
  43349. else if (faceIndex == 4) {
  43350. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  43351. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  43352. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  43353. }
  43354. else if (faceIndex == 5) {
  43355. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  43356. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  43357. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  43358. }
  43359. 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]);
  43360. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43361. }
  43362. totalSolidAngle += deltaSolidAngle;
  43363. u += du;
  43364. }
  43365. v += dv;
  43366. }
  43367. }
  43368. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  43369. var correction = correctSolidAngle / totalSolidAngle;
  43370. sphericalHarmonics.scale(correction);
  43371. // Additionally scale by pi -- audit needed
  43372. sphericalHarmonics.scale(1.0 / Math.PI);
  43373. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  43374. };
  43375. CubeMapToSphericalPolynomialTools.FileFaces = [
  43376. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43377. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43378. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43379. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43380. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43381. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43382. ];
  43383. return CubeMapToSphericalPolynomialTools;
  43384. })();
  43385. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43386. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43387. })(BABYLON || (BABYLON = {}));
  43388. var BABYLON;
  43389. (function (BABYLON) {
  43390. var Internals;
  43391. (function (Internals) {
  43392. /**
  43393. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  43394. */
  43395. var PanoramaToCubeMapTools = (function () {
  43396. function PanoramaToCubeMapTools() {
  43397. }
  43398. /**
  43399. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  43400. *
  43401. * @param float32Array The source data.
  43402. * @param inputWidth The width of the input panorama.
  43403. * @param inputhHeight The height of the input panorama.
  43404. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  43405. * @return The cubemap data
  43406. */
  43407. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  43408. if (!float32Array) {
  43409. throw "ConvertPanoramaToCubemap: input cannot be null";
  43410. }
  43411. if (float32Array.length != inputWidth * inputHeight * 3) {
  43412. throw "ConvertPanoramaToCubemap: input size is wrong";
  43413. }
  43414. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  43415. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  43416. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  43417. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  43418. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  43419. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  43420. return {
  43421. front: textureFront,
  43422. back: textureBack,
  43423. left: textureLeft,
  43424. right: textureRight,
  43425. up: textureUp,
  43426. down: textureDown,
  43427. size: size
  43428. };
  43429. };
  43430. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  43431. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  43432. var textureArray = new Float32Array(buffer);
  43433. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  43434. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  43435. var dy = 1 / texSize;
  43436. var fy = 0;
  43437. for (var y = 0; y < texSize; y++) {
  43438. var xv1 = faceData[0];
  43439. var xv2 = faceData[2];
  43440. for (var x = 0; x < texSize; x++) {
  43441. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  43442. v.normalize();
  43443. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  43444. // 3 channels per pixels
  43445. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  43446. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  43447. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  43448. xv1 = xv1.add(rotDX1);
  43449. xv2 = xv2.add(rotDX2);
  43450. }
  43451. fy += dy;
  43452. }
  43453. return textureArray;
  43454. };
  43455. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  43456. var theta = Math.atan2(vDir.z, vDir.x);
  43457. var phi = Math.acos(vDir.y);
  43458. while (theta < -Math.PI)
  43459. theta += 2 * Math.PI;
  43460. while (theta > Math.PI)
  43461. theta -= 2 * Math.PI;
  43462. var dx = theta / Math.PI;
  43463. var dy = phi / Math.PI;
  43464. // recenter.
  43465. dx = dx * 0.5 + 0.5;
  43466. var px = Math.round(dx * inputWidth);
  43467. if (px < 0)
  43468. px = 0;
  43469. else if (px >= inputWidth)
  43470. px = inputWidth - 1;
  43471. var py = Math.round(dy * inputHeight);
  43472. if (py < 0)
  43473. py = 0;
  43474. else if (py >= inputHeight)
  43475. py = inputHeight - 1;
  43476. var inputY = (inputHeight - py - 1);
  43477. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  43478. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  43479. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  43480. return {
  43481. r: r,
  43482. g: g,
  43483. b: b
  43484. };
  43485. };
  43486. PanoramaToCubeMapTools.FACE_FRONT = [
  43487. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  43488. new BABYLON.Vector3(1.0, -1.0, -1.0),
  43489. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  43490. new BABYLON.Vector3(1.0, 1.0, -1.0)
  43491. ];
  43492. PanoramaToCubeMapTools.FACE_BACK = [
  43493. new BABYLON.Vector3(1.0, -1.0, 1.0),
  43494. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  43495. new BABYLON.Vector3(1.0, 1.0, 1.0),
  43496. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  43497. ];
  43498. PanoramaToCubeMapTools.FACE_RIGHT = [
  43499. new BABYLON.Vector3(1.0, -1.0, -1.0),
  43500. new BABYLON.Vector3(1.0, -1.0, 1.0),
  43501. new BABYLON.Vector3(1.0, 1.0, -1.0),
  43502. new BABYLON.Vector3(1.0, 1.0, 1.0)
  43503. ];
  43504. PanoramaToCubeMapTools.FACE_LEFT = [
  43505. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  43506. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  43507. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  43508. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  43509. ];
  43510. PanoramaToCubeMapTools.FACE_DOWN = [
  43511. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  43512. new BABYLON.Vector3(1.0, 1.0, -1.0),
  43513. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  43514. new BABYLON.Vector3(1.0, 1.0, 1.0)
  43515. ];
  43516. PanoramaToCubeMapTools.FACE_UP = [
  43517. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  43518. new BABYLON.Vector3(1.0, -1.0, 1.0),
  43519. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  43520. new BABYLON.Vector3(1.0, -1.0, -1.0)
  43521. ];
  43522. return PanoramaToCubeMapTools;
  43523. })();
  43524. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  43525. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43526. })(BABYLON || (BABYLON = {}));
  43527. var BABYLON;
  43528. (function (BABYLON) {
  43529. var Internals;
  43530. (function (Internals) {
  43531. ;
  43532. /**
  43533. * This groups tools to convert HDR texture to native colors array.
  43534. */
  43535. var HDRTools = (function () {
  43536. function HDRTools() {
  43537. }
  43538. HDRTools.Ldexp = function (mantissa, exponent) {
  43539. if (exponent > 1023) {
  43540. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  43541. }
  43542. if (exponent < -1074) {
  43543. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  43544. }
  43545. return mantissa * Math.pow(2, exponent);
  43546. };
  43547. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  43548. if (exponent > 0) {
  43549. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  43550. float32array[index + 0] = red * exponent;
  43551. float32array[index + 1] = green * exponent;
  43552. float32array[index + 2] = blue * exponent;
  43553. }
  43554. else {
  43555. float32array[index + 0] = 0;
  43556. float32array[index + 1] = 0;
  43557. float32array[index + 2] = 0;
  43558. }
  43559. };
  43560. HDRTools.readStringLine = function (uint8array, startIndex) {
  43561. var line = "";
  43562. var character = "";
  43563. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  43564. character = String.fromCharCode(uint8array[i]);
  43565. if (character == "\n") {
  43566. break;
  43567. }
  43568. line += character;
  43569. }
  43570. return line;
  43571. };
  43572. /**
  43573. * Reads header information from an RGBE texture stored in a native array.
  43574. * More information on this format are available here:
  43575. * https://en.wikipedia.org/wiki/RGBE_image_format
  43576. *
  43577. * @param uint8array The binary file stored in native array.
  43578. * @return The header information.
  43579. */
  43580. HDRTools.RGBE_ReadHeader = function (uint8array) {
  43581. var height = 0;
  43582. var width = 0;
  43583. var line = this.readStringLine(uint8array, 0);
  43584. if (line[0] != '#' || line[1] != '?') {
  43585. throw "Bad HDR Format.";
  43586. }
  43587. var endOfHeader = false;
  43588. var findFormat = false;
  43589. var lineIndex = 0;
  43590. do {
  43591. lineIndex += (line.length + 1);
  43592. line = this.readStringLine(uint8array, lineIndex);
  43593. if (line == "FORMAT=32-bit_rle_rgbe") {
  43594. findFormat = true;
  43595. }
  43596. else if (line.length == 0) {
  43597. endOfHeader = true;
  43598. }
  43599. } while (!endOfHeader);
  43600. if (!findFormat) {
  43601. throw "HDR Bad header format, unsupported FORMAT";
  43602. }
  43603. lineIndex += (line.length + 1);
  43604. line = this.readStringLine(uint8array, lineIndex);
  43605. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  43606. var match = sizeRegexp.exec(line);
  43607. // TODO. Support +Y and -X if needed.
  43608. if (match.length < 3) {
  43609. throw "HDR Bad header format, no size";
  43610. }
  43611. width = parseInt(match[2]);
  43612. height = parseInt(match[1]);
  43613. if (width < 8 || width > 0x7fff) {
  43614. throw "HDR Bad header format, unsupported size";
  43615. }
  43616. lineIndex += (line.length + 1);
  43617. return {
  43618. height: height,
  43619. width: width,
  43620. dataPosition: lineIndex
  43621. };
  43622. };
  43623. /**
  43624. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  43625. * This RGBE texture needs to store the information as a panorama.
  43626. *
  43627. * More information on this format are available here:
  43628. * https://en.wikipedia.org/wiki/RGBE_image_format
  43629. *
  43630. * @param buffer The binary file stored in an array buffer.
  43631. * @param size The expected size of the extracted cubemap.
  43632. * @return The Cube Map information.
  43633. */
  43634. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  43635. var uint8array = new Uint8Array(buffer);
  43636. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  43637. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  43638. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  43639. return cubeMapData;
  43640. };
  43641. /**
  43642. * Returns the pixels data extracted from an RGBE texture.
  43643. * This pixels will be stored left to right up to down in the R G B order in one array.
  43644. *
  43645. * More information on this format are available here:
  43646. * https://en.wikipedia.org/wiki/RGBE_image_format
  43647. *
  43648. * @param uint8array The binary file stored in an array buffer.
  43649. * @param hdrInfo The header information of the file.
  43650. * @return The pixels data in RGB right to left up to down order.
  43651. */
  43652. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  43653. // Keep for multi format supports.
  43654. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  43655. };
  43656. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  43657. var num_scanlines = hdrInfo.height;
  43658. var scanline_width = hdrInfo.width;
  43659. var a, b, c, d, count;
  43660. var dataIndex = hdrInfo.dataPosition;
  43661. var index = 0, endIndex = 0, i = 0;
  43662. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  43663. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  43664. // 3 channels of 4 bytes per pixel in float.
  43665. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  43666. var resultArray = new Float32Array(resultBuffer);
  43667. // read in each successive scanline
  43668. while (num_scanlines > 0) {
  43669. a = uint8array[dataIndex++];
  43670. b = uint8array[dataIndex++];
  43671. c = uint8array[dataIndex++];
  43672. d = uint8array[dataIndex++];
  43673. if (a != 2 || b != 2 || (c & 0x80)) {
  43674. // this file is not run length encoded
  43675. throw "HDR Bad header format, not RLE";
  43676. }
  43677. if (((c << 8) | d) != scanline_width) {
  43678. throw "HDR Bad header format, wrong scan line width";
  43679. }
  43680. index = 0;
  43681. // read each of the four channels for the scanline into the buffer
  43682. for (i = 0; i < 4; i++) {
  43683. endIndex = (i + 1) * scanline_width;
  43684. while (index < endIndex) {
  43685. a = uint8array[dataIndex++];
  43686. b = uint8array[dataIndex++];
  43687. if (a > 128) {
  43688. // a run of the same value
  43689. count = a - 128;
  43690. if ((count == 0) || (count > endIndex - index)) {
  43691. throw "HDR Bad Format, bad scanline data (run)";
  43692. }
  43693. while (count-- > 0) {
  43694. scanLineArray[index++] = b;
  43695. }
  43696. }
  43697. else {
  43698. // a non-run
  43699. count = a;
  43700. if ((count == 0) || (count > endIndex - index)) {
  43701. throw "HDR Bad Format, bad scanline data (non-run)";
  43702. }
  43703. scanLineArray[index++] = b;
  43704. if (--count > 0) {
  43705. for (var j = 0; j < count; j++) {
  43706. scanLineArray[index++] = uint8array[dataIndex++];
  43707. }
  43708. }
  43709. }
  43710. }
  43711. }
  43712. // now convert data from buffer into floats
  43713. for (i = 0; i < scanline_width; i++) {
  43714. a = scanLineArray[i];
  43715. b = scanLineArray[i + scanline_width];
  43716. c = scanLineArray[i + 2 * scanline_width];
  43717. d = scanLineArray[i + 3 * scanline_width];
  43718. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  43719. }
  43720. num_scanlines--;
  43721. }
  43722. return resultArray;
  43723. };
  43724. return HDRTools;
  43725. })();
  43726. Internals.HDRTools = HDRTools;
  43727. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43728. })(BABYLON || (BABYLON = {}));
  43729. //_______________________________________________________________
  43730. // Extracted from CubeMapGen:
  43731. // https://code.google.com/archive/p/cubemapgen/
  43732. //
  43733. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  43734. //_______________________________________________________________
  43735. var BABYLON;
  43736. (function (BABYLON) {
  43737. var Internals;
  43738. (function (Internals) {
  43739. /**
  43740. * The bounding box information used during the conversion process.
  43741. */
  43742. var CMGBoundinBox = (function () {
  43743. function CMGBoundinBox() {
  43744. this.min = new BABYLON.Vector3(0, 0, 0);
  43745. this.max = new BABYLON.Vector3(0, 0, 0);
  43746. this.clear();
  43747. }
  43748. CMGBoundinBox.prototype.clear = function () {
  43749. this.min.x = CMGBoundinBox.MAX;
  43750. this.min.y = CMGBoundinBox.MAX;
  43751. this.min.z = CMGBoundinBox.MAX;
  43752. this.max.x = CMGBoundinBox.MIN;
  43753. this.max.y = CMGBoundinBox.MIN;
  43754. this.max.z = CMGBoundinBox.MIN;
  43755. };
  43756. CMGBoundinBox.prototype.augment = function (x, y, z) {
  43757. this.min.x = Math.min(this.min.x, x);
  43758. this.min.y = Math.min(this.min.y, y);
  43759. this.min.z = Math.min(this.min.z, z);
  43760. this.max.x = Math.max(this.max.x, x);
  43761. this.max.y = Math.max(this.max.y, y);
  43762. this.max.z = Math.max(this.max.z, z);
  43763. };
  43764. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  43765. this.min.x = Math.max(this.min.x, x);
  43766. this.min.y = Math.max(this.min.y, y);
  43767. this.min.z = Math.max(this.min.z, z);
  43768. };
  43769. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  43770. this.max.x = Math.min(this.max.x, x);
  43771. this.max.y = Math.min(this.max.y, y);
  43772. this.max.z = Math.min(this.max.z, z);
  43773. };
  43774. CMGBoundinBox.prototype.empty = function () {
  43775. if ((this.min.x > this.max.y) ||
  43776. (this.min.y > this.max.y) ||
  43777. (this.min.z > this.max.y)) {
  43778. return true;
  43779. }
  43780. else {
  43781. return false;
  43782. }
  43783. };
  43784. CMGBoundinBox.MAX = Number.MAX_VALUE;
  43785. CMGBoundinBox.MIN = Number.MIN_VALUE;
  43786. return CMGBoundinBox;
  43787. })();
  43788. /**
  43789. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  43790. * required by the glossinees of a material.
  43791. *
  43792. * This only supports the cosine drop power as well as Warp fixup generation method.
  43793. *
  43794. * This is using the process from CubeMapGen described here:
  43795. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  43796. */
  43797. var PMREMGenerator = (function () {
  43798. /**
  43799. * Constructor of the generator.
  43800. *
  43801. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  43802. * @param inputSize The size of the cubemap faces
  43803. * @param outputSize The size of the output cubemap faces
  43804. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  43805. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  43806. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  43807. * @param specularPower The max specular level of the desired cubemap
  43808. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  43809. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  43810. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  43811. */
  43812. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  43813. this.input = input;
  43814. this.inputSize = inputSize;
  43815. this.outputSize = outputSize;
  43816. this.maxNumMipLevels = maxNumMipLevels;
  43817. this.numChannels = numChannels;
  43818. this.isFloat = isFloat;
  43819. this.specularPower = specularPower;
  43820. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  43821. this.excludeBase = excludeBase;
  43822. this.fixup = fixup;
  43823. this._outputSurface = [];
  43824. this._numMipLevels = 0;
  43825. }
  43826. /**
  43827. * Launches the filter process and return the result.
  43828. *
  43829. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  43830. */
  43831. PMREMGenerator.prototype.filterCubeMap = function () {
  43832. // Init cubemap processor
  43833. this.init();
  43834. // Filters the cubemap
  43835. this.filterCubeMapMipChain();
  43836. // Returns the filtered mips.
  43837. return this._outputSurface;
  43838. };
  43839. PMREMGenerator.prototype.init = function () {
  43840. var i;
  43841. var j;
  43842. var mipLevelSize;
  43843. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  43844. if (this.maxNumMipLevels == 0) {
  43845. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  43846. }
  43847. //first miplevel size
  43848. mipLevelSize = this.outputSize;
  43849. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  43850. for (j = 0; j < this.maxNumMipLevels; j++) {
  43851. this._outputSurface.length++;
  43852. this._outputSurface[j] = [];
  43853. //Iterate over faces for output images
  43854. for (i = 0; i < 6; i++) {
  43855. this._outputSurface[j].length++;
  43856. // Initializes a new array for the output.
  43857. if (this.isFloat) {
  43858. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  43859. }
  43860. else {
  43861. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  43862. }
  43863. }
  43864. //next mip level is half size
  43865. mipLevelSize >>= 1;
  43866. this._numMipLevels++;
  43867. //terminate if mip chain becomes too small
  43868. if (mipLevelSize == 0) {
  43869. this.maxNumMipLevels = j;
  43870. return;
  43871. }
  43872. }
  43873. };
  43874. //--------------------------------------------------------------------------------------
  43875. //Cube map filtering and mip chain generation.
  43876. // the cube map filtereing is specified using a number of parameters:
  43877. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  43878. // indicates the region of the hemisphere to filter over for each tap.
  43879. //
  43880. // Note that the top mip level is also a filtered version of the original input images
  43881. // as well in order to create mip chains for diffuse environment illumination.
  43882. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  43883. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  43884. //
  43885. // Then the mip angle used to genreate the next level of the mip chain from the first level
  43886. // is a_InitialMipAngle
  43887. //
  43888. // The angle for the subsequent levels of the mip chain are specified by their parents
  43889. // filtering angle and a per-level scale and bias
  43890. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  43891. //
  43892. //--------------------------------------------------------------------------------------
  43893. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  43894. // First, take count of the lighting model to modify SpecularPower
  43895. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  43896. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  43897. //Cone angle start (for generating subsequent mip levels)
  43898. var currentSpecularPower = this.specularPower;
  43899. //Build filter lookup tables based on the source miplevel size
  43900. this.precomputeFilterLookupTables(this.inputSize);
  43901. // Note that we need to filter the first level before generating mipmap
  43902. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  43903. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  43904. // TODO : Write a function to copy and scale the base mipmap in output
  43905. // I am just lazy here and just put a high specular power value, and do some if.
  43906. if (this.excludeBase && (levelIndex == 0)) {
  43907. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  43908. currentSpecularPower = 100000.0;
  43909. }
  43910. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  43911. var srcCubeImage = this.input;
  43912. var dstCubeImage = this._outputSurface[levelIndex];
  43913. var dstSize = this.outputSize >> levelIndex;
  43914. // Compute required angle.
  43915. var angle = this.getBaseFilterAngle(currentSpecularPower);
  43916. // filter cube surfaces
  43917. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  43918. // fix seams
  43919. if (this.fixup) {
  43920. this.fixupCubeEdges(dstCubeImage, dstSize);
  43921. }
  43922. // Decrease the specular power to generate the mipmap chain
  43923. // TODO : Use another method for Exclude (see first comment at start of the function
  43924. if (this.excludeBase && (levelIndex == 0)) {
  43925. currentSpecularPower = this.specularPower;
  43926. }
  43927. currentSpecularPower *= this.cosinePowerDropPerMip;
  43928. }
  43929. };
  43930. //--------------------------------------------------------------------------------------
  43931. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  43932. // It allow to optimize the texel to access base on the specular power.
  43933. //--------------------------------------------------------------------------------------
  43934. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  43935. // We want to find the alpha such that:
  43936. // cos(alpha)^cosinePower = epsilon
  43937. // That's: acos(epsilon^(1/cosinePower))
  43938. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  43939. var angle = 180.0;
  43940. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  43941. angle *= 180.0 / Math.PI; // Convert to degree
  43942. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  43943. return angle;
  43944. };
  43945. //--------------------------------------------------------------------------------------
  43946. //Builds the following lookup tables prior to filtering:
  43947. // -normalizer cube map
  43948. // -tap weight lookup table
  43949. //
  43950. //--------------------------------------------------------------------------------------
  43951. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  43952. var srcTexelAngle;
  43953. var iCubeFace;
  43954. //clear pre-existing normalizer cube map
  43955. this._normCubeMap = [];
  43956. //Normalized vectors per cubeface and per-texel solid angle
  43957. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  43958. };
  43959. //--------------------------------------------------------------------------------------
  43960. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  43961. //
  43962. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  43963. //
  43964. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  43965. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  43966. // below
  43967. //--------------------------------------------------------------------------------------
  43968. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  43969. var iCubeFace;
  43970. var u;
  43971. var v;
  43972. //iterate over cube faces
  43973. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43974. //First three channels for norm cube, and last channel for solid angle
  43975. this._normCubeMap.push(new Float32Array(size * size * 4));
  43976. //fast texture walk, build normalizer cube map
  43977. var facesData = this.input[iCubeFace];
  43978. for (v = 0; v < size; v++) {
  43979. for (u = 0; u < size; u++) {
  43980. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  43981. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  43982. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  43983. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  43984. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  43985. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  43986. }
  43987. }
  43988. }
  43989. };
  43990. //--------------------------------------------------------------------------------------
  43991. // Convert cubemap face texel coordinates and face idx to 3D vector
  43992. // note the U and V coords are integer coords and range from 0 to size-1
  43993. // this routine can be used to generate a normalizer cube map
  43994. //--------------------------------------------------------------------------------------
  43995. // SL BEGIN
  43996. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  43997. var nvcU;
  43998. var nvcV;
  43999. var tempVec;
  44000. // Change from original AMD code
  44001. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  44002. // + 0.5f is for texel center addressing
  44003. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  44004. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  44005. // warp fixup
  44006. if (fixup && size > 1) {
  44007. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  44008. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  44009. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  44010. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  44011. }
  44012. // Get current vector
  44013. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  44014. // U contribution
  44015. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  44016. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  44017. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  44018. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  44019. // V contribution and Sum
  44020. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  44021. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  44022. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  44023. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  44024. //add face axis
  44025. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  44026. PMREMGenerator._vectorTemp.x += faceAxis[0];
  44027. PMREMGenerator._vectorTemp.y += faceAxis[1];
  44028. PMREMGenerator._vectorTemp.z += faceAxis[2];
  44029. //normalize vector
  44030. PMREMGenerator._vectorTemp.normalize();
  44031. return PMREMGenerator._vectorTemp;
  44032. };
  44033. //--------------------------------------------------------------------------------------
  44034. // Convert 3D vector to cubemap face texel coordinates and face idx
  44035. // note the U and V coords are integer coords and range from 0 to size-1
  44036. // this routine can be used to generate a normalizer cube map
  44037. //
  44038. // returns face IDX and texel coords
  44039. //--------------------------------------------------------------------------------------
  44040. // SL BEGIN
  44041. /*
  44042. Mapping Texture Coordinates to Cube Map Faces
  44043. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  44044. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  44045. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  44046. map arrangement in Pixar's RenderMan package.
  44047. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  44048. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  44049. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  44050. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  44051. the major axis direction). The target column in the table below explains how the major axis direction
  44052. maps to the 2D image of a particular cube map target.
  44053. major axis
  44054. direction target sc tc ma
  44055. ---------- --------------------------------- --- --- ---
  44056. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  44057. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  44058. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  44059. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  44060. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  44061. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  44062. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  44063. an updated (s,t) is calculated as follows
  44064. s = ( sc/|ma| + 1 ) / 2
  44065. t = ( tc/|ma| + 1 ) / 2
  44066. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  44067. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  44068. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  44069. */
  44070. // Note this method return U and V in range from 0 to size-1
  44071. // SL END
  44072. // Store the information in vector3 for convenience (faceindex, u, v)
  44073. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  44074. var maxCoord;
  44075. var faceIdx;
  44076. //absolute value 3
  44077. var absX = Math.abs(x);
  44078. var absY = Math.abs(y);
  44079. var absZ = Math.abs(z);
  44080. if (absX >= absY && absX >= absZ) {
  44081. maxCoord = absX;
  44082. if (x >= 0) {
  44083. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  44084. }
  44085. else {
  44086. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  44087. }
  44088. }
  44089. else if (absY >= absX && absY >= absZ) {
  44090. maxCoord = absY;
  44091. if (y >= 0) {
  44092. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  44093. }
  44094. else {
  44095. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  44096. }
  44097. }
  44098. else {
  44099. maxCoord = absZ;
  44100. if (z >= 0) {
  44101. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  44102. }
  44103. else {
  44104. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  44105. }
  44106. }
  44107. //divide through by max coord so face vector lies on cube face
  44108. var scale = 1 / maxCoord;
  44109. x *= scale;
  44110. y *= scale;
  44111. z *= scale;
  44112. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  44113. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  44114. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  44115. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  44116. // Modify original AMD code to return value from 0 to Size - 1
  44117. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  44118. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  44119. PMREMGenerator._vectorTemp.x = faceIdx;
  44120. PMREMGenerator._vectorTemp.y = u;
  44121. PMREMGenerator._vectorTemp.z = v;
  44122. return PMREMGenerator._vectorTemp;
  44123. };
  44124. //--------------------------------------------------------------------------------------
  44125. //Original code from Ignacio CastaÒo
  44126. // This formula is from Manne ÷hrstrˆm's thesis.
  44127. // Take two coordiantes in the range [-1, 1] that define a portion of a
  44128. // cube face and return the area of the projection of that portion on the
  44129. // surface of the sphere.
  44130. //--------------------------------------------------------------------------------------
  44131. PMREMGenerator.prototype.areaElement = function (x, y) {
  44132. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  44133. };
  44134. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  44135. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  44136. // (+ 0.5f is for texel center addressing)
  44137. u = (2.0 * (u + 0.5) / size) - 1.0;
  44138. v = (2.0 * (v + 0.5) / size) - 1.0;
  44139. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  44140. var invResolution = 1.0 / size;
  44141. // U and V are the -1..1 texture coordinate on the current face.
  44142. // Get projected area for this texel
  44143. var x0 = u - invResolution;
  44144. var y0 = v - invResolution;
  44145. var x1 = u + invResolution;
  44146. var y1 = v + invResolution;
  44147. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  44148. return solidAngle;
  44149. };
  44150. //--------------------------------------------------------------------------------------
  44151. //The key to the speed of these filtering routines is to quickly define a per-face
  44152. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  44153. // Later these pixels are selectively processed based on their dot products to see if
  44154. // they reside within the filtering cone.
  44155. //
  44156. //This is done by computing the smallest per-texel angle to get a conservative estimate
  44157. // of the number of texels needed to be covered in width and height order to filter the
  44158. // region. the bounding box for the center taps face is defined first, and if the
  44159. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  44160. // defined next
  44161. //--------------------------------------------------------------------------------------
  44162. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  44163. // note that pixels within these regions may be rejected
  44164. // based on the anlge
  44165. var iCubeFace;
  44166. var u;
  44167. var v;
  44168. // bounding box per face to specify region to process
  44169. var filterExtents = [];
  44170. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  44171. filterExtents.push(new CMGBoundinBox());
  44172. }
  44173. // min angle a src texel can cover (in degrees)
  44174. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  44175. // angle about center tap to define filter cone
  44176. // filter angle is 1/2 the cone angle
  44177. var filterAngle = filterConeAngle / 2.0;
  44178. //ensure filter angle is larger than a texel
  44179. if (filterAngle < srcTexelAngle) {
  44180. filterAngle = srcTexelAngle;
  44181. }
  44182. //ensure filter cone is always smaller than the hemisphere
  44183. if (filterAngle > 90.0) {
  44184. filterAngle = 90.0;
  44185. }
  44186. // the maximum number of texels in 1D the filter cone angle will cover
  44187. // used to determine bounding box size for filter extents
  44188. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  44189. // ensure conservative region always covers at least one texel
  44190. if (filterSize < 1) {
  44191. filterSize = 1;
  44192. }
  44193. // dotProdThresh threshold based on cone angle to determine whether or not taps
  44194. // reside within the cone angle
  44195. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  44196. // process required faces
  44197. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  44198. //iterate over dst cube map face texel
  44199. for (v = 0; v < dstSize; v++) {
  44200. for (u = 0; u < dstSize; u++) {
  44201. //get center tap direction
  44202. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  44203. //clear old per-face filter extents
  44204. this.clearFilterExtents(filterExtents);
  44205. //define per-face filter extents
  44206. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  44207. //perform filtering of src faces using filter extents
  44208. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  44209. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  44210. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  44211. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  44212. }
  44213. }
  44214. }
  44215. };
  44216. //--------------------------------------------------------------------------------------
  44217. //Clear filter extents for the 6 cube map faces
  44218. //--------------------------------------------------------------------------------------
  44219. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  44220. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  44221. filterExtents[iCubeFaces].clear();
  44222. }
  44223. };
  44224. //--------------------------------------------------------------------------------------
  44225. //Define per-face bounding box filter extents
  44226. //
  44227. // These define conservative texel regions in each of the faces the filter can possibly
  44228. // process. When the pixels in the regions are actually processed, the dot product
  44229. // between the tap vector and the center tap vector is used to determine the weight of
  44230. // the tap and whether or not the tap is within the cone.
  44231. //
  44232. //--------------------------------------------------------------------------------------
  44233. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  44234. //neighboring face and bleed over amount, and width of BBOX for
  44235. // left, right, top, and bottom edges of this face
  44236. var bleedOverAmount = [0, 0, 0, 0];
  44237. var bleedOverBBoxMin = [0, 0, 0, 0];
  44238. var bleedOverBBoxMax = [0, 0, 0, 0];
  44239. var neighborFace;
  44240. var neighborEdge;
  44241. var oppositeFaceIdx;
  44242. //get face idx, and u, v info from center tap dir
  44243. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  44244. var faceIdx = result.x;
  44245. var u = result.y;
  44246. var v = result.z;
  44247. //define bbox size within face
  44248. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  44249. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  44250. filterExtents[faceIdx].clampMin(0, 0, 0);
  44251. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  44252. //u and v extent in face corresponding to center tap
  44253. var minU = filterExtents[faceIdx].min.x;
  44254. var minV = filterExtents[faceIdx].min.y;
  44255. var maxU = filterExtents[faceIdx].max.x;
  44256. var maxV = filterExtents[faceIdx].max.y;
  44257. //bleed over amounts for face across u=0 edge (left)
  44258. bleedOverAmount[0] = (bboxSize - u);
  44259. bleedOverBBoxMin[0] = minV;
  44260. bleedOverBBoxMax[0] = maxV;
  44261. //bleed over amounts for face across u=1 edge (right)
  44262. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  44263. bleedOverBBoxMin[1] = minV;
  44264. bleedOverBBoxMax[1] = maxV;
  44265. //bleed over to face across v=0 edge (up)
  44266. bleedOverAmount[2] = (bboxSize - v);
  44267. bleedOverBBoxMin[2] = minU;
  44268. bleedOverBBoxMax[2] = maxU;
  44269. //bleed over to face across v=1 edge (down)
  44270. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  44271. bleedOverBBoxMin[3] = minU;
  44272. bleedOverBBoxMax[3] = maxU;
  44273. //compute bleed over regions in neighboring faces
  44274. for (var i = 0; i < 4; i++) {
  44275. if (bleedOverAmount[i] > 0) {
  44276. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  44277. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  44278. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  44279. // be flipped: the cases are
  44280. // if a left edge mates with a left or bottom edge on the neighbor
  44281. // if a top edge mates with a top or right edge on the neighbor
  44282. // if a right edge mates with a right or top edge on the neighbor
  44283. // if a bottom edge mates with a bottom or left edge on the neighbor
  44284. //Seeing as the edges are enumerated as follows
  44285. // left =0
  44286. // right =1
  44287. // top =2
  44288. // bottom =3
  44289. //
  44290. // so if the edge enums are the same, or the sum of the enums == 3,
  44291. // the bbox needs to be flipped
  44292. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  44293. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  44294. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  44295. }
  44296. //The way the bounding box is extended onto the neighboring face
  44297. // depends on which edge of neighboring face abuts with this one
  44298. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  44299. case PMREMGenerator.CP_EDGE_LEFT:
  44300. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  44301. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  44302. break;
  44303. case PMREMGenerator.CP_EDGE_RIGHT:
  44304. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  44305. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  44306. break;
  44307. case PMREMGenerator.CP_EDGE_TOP:
  44308. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  44309. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  44310. break;
  44311. case PMREMGenerator.CP_EDGE_BOTTOM:
  44312. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  44313. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  44314. break;
  44315. }
  44316. //clamp filter extents in non-center tap faces to remain within surface
  44317. filterExtents[neighborFace].clampMin(0, 0, 0);
  44318. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  44319. }
  44320. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  44321. // from the center tap face, then process the opposite face entirely for now.
  44322. //Note that the cases in which this happens, what usually happens is that
  44323. // more than one edge bleeds onto the opposite face, and the bounding box
  44324. // encompasses the entire cube map face.
  44325. if (bleedOverAmount[i] > srcSize) {
  44326. //determine opposite face
  44327. switch (faceIdx) {
  44328. case PMREMGenerator.CP_FACE_X_POS:
  44329. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  44330. break;
  44331. case PMREMGenerator.CP_FACE_X_NEG:
  44332. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  44333. break;
  44334. case PMREMGenerator.CP_FACE_Y_POS:
  44335. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  44336. break;
  44337. case PMREMGenerator.CP_FACE_Y_NEG:
  44338. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  44339. break;
  44340. case PMREMGenerator.CP_FACE_Z_POS:
  44341. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  44342. break;
  44343. case PMREMGenerator.CP_FACE_Z_NEG:
  44344. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  44345. break;
  44346. default:
  44347. break;
  44348. }
  44349. //just encompass entire face for now
  44350. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  44351. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  44352. }
  44353. }
  44354. };
  44355. //--------------------------------------------------------------------------------------
  44356. //ProcessFilterExtents
  44357. // Process bounding box in each cube face
  44358. //
  44359. //--------------------------------------------------------------------------------------
  44360. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  44361. //accumulators are 64-bit floats in order to have the precision needed
  44362. // over a summation of a large number of pixels
  44363. var dstAccum = [0, 0, 0, 0];
  44364. var weightAccum = 0;
  44365. var k = 0;
  44366. var nSrcChannels = this.numChannels;
  44367. // norm cube map and srcCubeMap have same face width
  44368. var faceWidth = srcSize;
  44369. //amount to add to pointer to move to next scanline in images
  44370. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  44371. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  44372. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  44373. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  44374. // iterate over cubefaces
  44375. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  44376. //if bbox is non empty
  44377. if (!filterExtents[iFaceIdx].empty()) {
  44378. var uStart = filterExtents[iFaceIdx].min.x;
  44379. var vStart = filterExtents[iFaceIdx].min.y;
  44380. var uEnd = filterExtents[iFaceIdx].max.x;
  44381. var vEnd = filterExtents[iFaceIdx].max.y;
  44382. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  44383. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  44384. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  44385. for (var v = vStart; v <= vEnd; v++) {
  44386. var normCubeRowWalk = 0;
  44387. var srcCubeRowWalk = 0;
  44388. for (var u = uStart; u <= uEnd; u++) {
  44389. //pointer to direction in cube map associated with texel
  44390. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  44391. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  44392. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  44393. //check dot product to see if texel is within cone
  44394. var tapDotProd = texelVectX * centerTapDir.x +
  44395. texelVectY * centerTapDir.y +
  44396. texelVectZ * centerTapDir.z;
  44397. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  44398. //solid angle stored in 4th channel of normalizer/solid angle cube map
  44399. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  44400. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  44401. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  44402. // so just adding one to specularpower do the trick.
  44403. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  44404. //iterate over channels
  44405. for (k = 0; k < nSrcChannels; k++) {
  44406. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  44407. srcCubeRowWalk++;
  44408. }
  44409. weightAccum += weight; //accumulate weight
  44410. }
  44411. else {
  44412. //step across source pixel
  44413. srcCubeRowWalk += nSrcChannels;
  44414. }
  44415. normCubeRowWalk += 4; // 4 channels per norm cube map.
  44416. }
  44417. startIndexNormCubeMap += normCubePitch;
  44418. startIndexSrcCubeMap += srcCubePitch;
  44419. }
  44420. }
  44421. }
  44422. //divide through by weights if weight is non zero
  44423. if (weightAccum != 0.0) {
  44424. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  44425. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  44426. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  44427. if (this.numChannels > 3) {
  44428. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  44429. }
  44430. }
  44431. else {
  44432. // otherwise sample nearest
  44433. // get face idx and u, v texel coordinate in face
  44434. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  44435. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  44436. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  44437. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  44438. if (this.numChannels > 3) {
  44439. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  44440. }
  44441. }
  44442. return PMREMGenerator._vectorTemp;
  44443. };
  44444. //--------------------------------------------------------------------------------------
  44445. // Fixup cube edges
  44446. //
  44447. // average texels on cube map faces across the edges
  44448. // WARP/BENT Method Only.
  44449. //--------------------------------------------------------------------------------------
  44450. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  44451. var k;
  44452. var j;
  44453. var i;
  44454. var iFace;
  44455. var iCorner = 0;
  44456. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  44457. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  44458. // note that if functionality to filter across the three texels for each corner, then
  44459. //indexed by corner and face idx. the array contains the face the start points belongs to.
  44460. var cornerPtr = [
  44461. [[], [], []],
  44462. [[], [], []],
  44463. [[], [], []],
  44464. [[], [], []],
  44465. [[], [], []],
  44466. [[], [], []],
  44467. [[], [], []],
  44468. [[], [], []]
  44469. ];
  44470. //if there is no fixup, or fixup width = 0, do nothing
  44471. if (cubeMapSize < 1) {
  44472. return;
  44473. }
  44474. //special case 1x1 cubemap, average face colors
  44475. if (cubeMapSize == 1) {
  44476. //iterate over channels
  44477. for (k = 0; k < this.numChannels; k++) {
  44478. var accum = 0.0;
  44479. //iterate over faces to accumulate face colors
  44480. for (iFace = 0; iFace < 6; iFace++) {
  44481. accum += cubeMap[iFace][k];
  44482. }
  44483. //compute average over 6 face colors
  44484. accum /= 6.0;
  44485. //iterate over faces to distribute face colors
  44486. for (iFace = 0; iFace < 6; iFace++) {
  44487. cubeMap[iFace][k] = accum;
  44488. }
  44489. }
  44490. return;
  44491. }
  44492. //iterate over faces to collect list of corner texel pointers
  44493. for (iFace = 0; iFace < 6; iFace++) {
  44494. //the 4 corner pointers for this face
  44495. faceCornerStartIndicies[0] = [iFace, 0];
  44496. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  44497. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  44498. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  44499. //iterate over face corners to collect cube corner pointers
  44500. for (iCorner = 0; iCorner < 4; iCorner++) {
  44501. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  44502. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  44503. cornerNumPtrs[corner]++;
  44504. }
  44505. }
  44506. //iterate over corners to average across corner tap values
  44507. for (iCorner = 0; iCorner < 8; iCorner++) {
  44508. for (k = 0; k < this.numChannels; k++) {
  44509. var cornerTapAccum = 0.0;
  44510. //iterate over corner texels and average results
  44511. for (i = 0; i < 3; i++) {
  44512. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  44513. }
  44514. //divide by 3 to compute average of corner tap values
  44515. cornerTapAccum *= (1.0 / 3.0);
  44516. //iterate over corner texels and average results
  44517. for (i = 0; i < 3; i++) {
  44518. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  44519. }
  44520. }
  44521. }
  44522. //iterate over the twelve edges of the cube to average across edges
  44523. for (i = 0; i < 12; i++) {
  44524. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  44525. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  44526. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  44527. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  44528. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  44529. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  44530. var edgeWalk = 0;
  44531. var neighborEdgeWalk = 0;
  44532. //Determine walking pointers based on edge type
  44533. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  44534. switch (edge) {
  44535. case PMREMGenerator.CP_EDGE_LEFT:
  44536. // no change to faceEdgeStartPtr
  44537. edgeWalk = this.numChannels * cubeMapSize;
  44538. break;
  44539. case PMREMGenerator.CP_EDGE_RIGHT:
  44540. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44541. edgeWalk = this.numChannels * cubeMapSize;
  44542. break;
  44543. case PMREMGenerator.CP_EDGE_TOP:
  44544. // no change to faceEdgeStartPtr
  44545. edgeWalk = this.numChannels;
  44546. break;
  44547. case PMREMGenerator.CP_EDGE_BOTTOM:
  44548. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  44549. edgeWalk = this.numChannels;
  44550. break;
  44551. }
  44552. //For certain types of edge abutments, the neighbor edge walk needs to
  44553. // be flipped: the cases are
  44554. // if a left edge mates with a left or bottom edge on the neighbor
  44555. // if a top edge mates with a top or right edge on the neighbor
  44556. // if a right edge mates with a right or top edge on the neighbor
  44557. // if a bottom edge mates with a bottom or left edge on the neighbor
  44558. //Seeing as the edges are enumerated as follows
  44559. // left =0
  44560. // right =1
  44561. // top =2
  44562. // bottom =3
  44563. //
  44564. //If the edge enums are the same, or the sum of the enums == 3,
  44565. // the neighbor edge walk needs to be flipped
  44566. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  44567. switch (neighborEdge) {
  44568. case PMREMGenerator.CP_EDGE_LEFT:
  44569. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  44570. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  44571. break;
  44572. case PMREMGenerator.CP_EDGE_RIGHT:
  44573. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  44574. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  44575. break;
  44576. case PMREMGenerator.CP_EDGE_TOP:
  44577. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44578. neighborEdgeWalk = -this.numChannels;
  44579. break;
  44580. case PMREMGenerator.CP_EDGE_BOTTOM:
  44581. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  44582. neighborEdgeWalk = -this.numChannels;
  44583. break;
  44584. }
  44585. }
  44586. else {
  44587. //swapped direction neighbor edge walk
  44588. switch (neighborEdge) {
  44589. case PMREMGenerator.CP_EDGE_LEFT:
  44590. //no change to neighborEdgeStartPtr for this case since it points
  44591. // to the upper left corner already
  44592. neighborEdgeWalk = this.numChannels * cubeMapSize;
  44593. break;
  44594. case PMREMGenerator.CP_EDGE_RIGHT:
  44595. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44596. neighborEdgeWalk = this.numChannels * cubeMapSize;
  44597. break;
  44598. case PMREMGenerator.CP_EDGE_TOP:
  44599. //no change to neighborEdgeStartPtr for this case since it points
  44600. // to the upper left corner already
  44601. neighborEdgeWalk = this.numChannels;
  44602. break;
  44603. case PMREMGenerator.CP_EDGE_BOTTOM:
  44604. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  44605. neighborEdgeWalk = this.numChannels;
  44606. break;
  44607. }
  44608. }
  44609. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  44610. //nearby neighborhood
  44611. //step ahead one texel on edge
  44612. edgeStartIndex += edgeWalk;
  44613. neighborEdgeStartIndex += neighborEdgeWalk;
  44614. // note that this loop does not process the corner texels, since they have already been
  44615. // averaged across faces across earlier
  44616. for (j = 1; j < (cubeMapSize - 1); j++) {
  44617. //for each set of taps along edge, average them
  44618. // and rewrite the results into the edges
  44619. for (k = 0; k < this.numChannels; k++) {
  44620. var edgeTap = cubeMap[face][edgeStartIndex + k];
  44621. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  44622. //compute average of tap intensity values
  44623. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  44624. //propagate average of taps to edge taps
  44625. cubeMap[face][edgeStartIndex + k] = avgTap;
  44626. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  44627. }
  44628. edgeStartIndex += edgeWalk;
  44629. neighborEdgeStartIndex += neighborEdgeWalk;
  44630. }
  44631. }
  44632. };
  44633. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  44634. PMREMGenerator.CP_UDIR = 0;
  44635. PMREMGenerator.CP_VDIR = 1;
  44636. PMREMGenerator.CP_FACEAXIS = 2;
  44637. //used to index cube faces
  44638. PMREMGenerator.CP_FACE_X_POS = 0;
  44639. PMREMGenerator.CP_FACE_X_NEG = 1;
  44640. PMREMGenerator.CP_FACE_Y_POS = 2;
  44641. PMREMGenerator.CP_FACE_Y_NEG = 3;
  44642. PMREMGenerator.CP_FACE_Z_POS = 4;
  44643. PMREMGenerator.CP_FACE_Z_NEG = 5;
  44644. //used to index image edges
  44645. // NOTE.. the actual number corresponding to the edge is important
  44646. // do not change these, or the code will break
  44647. //
  44648. // CP_EDGE_LEFT is u = 0
  44649. // CP_EDGE_RIGHT is u = width-1
  44650. // CP_EDGE_TOP is v = 0
  44651. // CP_EDGE_BOTTOM is v = height-1
  44652. PMREMGenerator.CP_EDGE_LEFT = 0;
  44653. PMREMGenerator.CP_EDGE_RIGHT = 1;
  44654. PMREMGenerator.CP_EDGE_TOP = 2;
  44655. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  44656. //corners of CUBE map (P or N specifys if it corresponds to the
  44657. // positive or negative direction each of X, Y, and Z
  44658. PMREMGenerator.CP_CORNER_NNN = 0;
  44659. PMREMGenerator.CP_CORNER_NNP = 1;
  44660. PMREMGenerator.CP_CORNER_NPN = 2;
  44661. PMREMGenerator.CP_CORNER_NPP = 3;
  44662. PMREMGenerator.CP_CORNER_PNN = 4;
  44663. PMREMGenerator.CP_CORNER_PNP = 5;
  44664. PMREMGenerator.CP_CORNER_PPN = 6;
  44665. PMREMGenerator.CP_CORNER_PPP = 7;
  44666. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  44667. //3x2 matrices that map cube map indexing vectors in 3d
  44668. // (after face selection and divide through by the
  44669. // _ABSOLUTE VALUE_ of the max coord)
  44670. // into NVC space
  44671. //Note this currently assumes the D3D cube face ordering and orientation
  44672. PMREMGenerator._sgFace2DMapping = [
  44673. //XPOS face
  44674. [[0, 0, -1],
  44675. [0, -1, 0],
  44676. [1, 0, 0]],
  44677. //XNEG face
  44678. [[0, 0, 1],
  44679. [0, -1, 0],
  44680. [-1, 0, 0]],
  44681. //YPOS face
  44682. [[1, 0, 0],
  44683. [0, 0, 1],
  44684. [0, 1, 0]],
  44685. //YNEG face
  44686. [[1, 0, 0],
  44687. [0, 0, -1],
  44688. [0, -1, 0]],
  44689. //ZPOS face
  44690. [[1, 0, 0],
  44691. [0, -1, 0],
  44692. [0, 0, 1]],
  44693. //ZNEG face
  44694. [[-1, 0, 0],
  44695. [0, -1, 0],
  44696. [0, 0, -1]],
  44697. ];
  44698. //------------------------------------------------------------------------------
  44699. // D3D cube map face specification
  44700. // mapping from 3D x,y,z cube map lookup coordinates
  44701. // to 2D within face u,v coordinates
  44702. //
  44703. // --------------------> U direction
  44704. // | (within-face texture space)
  44705. // | _____
  44706. // | | |
  44707. // | | +Y |
  44708. // | _____|_____|_____ _____
  44709. // | | | | | |
  44710. // | | -X | +Z | +X | -Z |
  44711. // | |_____|_____|_____|_____|
  44712. // | | |
  44713. // | | -Y |
  44714. // | |_____|
  44715. // |
  44716. // v V direction
  44717. // (within-face texture space)
  44718. //------------------------------------------------------------------------------
  44719. //Information about neighbors and how texture coorrdinates change across faces
  44720. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  44721. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  44722. //Note this currently assumes the D3D cube face ordering and orientation
  44723. PMREMGenerator._sgCubeNgh = [
  44724. //XPOS face
  44725. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44726. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44727. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44728. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  44729. //XNEG face
  44730. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44731. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  44732. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  44733. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  44734. //YPOS face
  44735. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  44736. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  44737. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  44738. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  44739. //YNEG face
  44740. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  44741. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44742. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44743. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  44744. //ZPOS face
  44745. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44746. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  44747. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44748. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  44749. //ZNEG face
  44750. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44751. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44752. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  44753. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  44754. ];
  44755. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  44756. // this table is used to average over the edges.
  44757. PMREMGenerator._sgCubeEdgeList = [
  44758. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  44759. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44760. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  44761. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44762. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44763. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44764. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  44765. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  44766. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  44767. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44768. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  44769. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  44770. ];
  44771. //Information about which of the 8 cube corners are correspond to the
  44772. // the 4 corners in each cube face
  44773. // the order is upper left, upper right, lower left, lower right
  44774. PMREMGenerator._sgCubeCornerList = [
  44775. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  44776. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  44777. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  44778. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  44779. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  44780. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  44781. ];
  44782. return PMREMGenerator;
  44783. })();
  44784. Internals.PMREMGenerator = PMREMGenerator;
  44785. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44786. })(BABYLON || (BABYLON = {}));
  44787. var BABYLON;
  44788. (function (BABYLON) {
  44789. /**
  44790. * This represents a texture coming from an HDR input.
  44791. *
  44792. * The only supported format is currently panorama picture stored in RGBE format.
  44793. * Example of such files can be found on HDRLib: http://hdrlib.com/
  44794. */
  44795. var HDRCubeTexture = (function (_super) {
  44796. __extends(HDRCubeTexture, _super);
  44797. /**
  44798. * Instantiates an HDRTexture from the following parameters.
  44799. *
  44800. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  44801. * @param scene The scene the texture will be used in
  44802. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  44803. * @param noMipmap Forces to not generate the mipmap if true
  44804. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  44805. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  44806. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  44807. */
  44808. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  44809. if (noMipmap === void 0) { noMipmap = false; }
  44810. if (generateHarmonics === void 0) { generateHarmonics = true; }
  44811. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  44812. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  44813. _super.call(this, scene);
  44814. this._useInGammaSpace = false;
  44815. this._generateHarmonics = true;
  44816. this._isBABYLONPreprocessed = false;
  44817. /**
  44818. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  44819. */
  44820. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  44821. /**
  44822. * The spherical polynomial data extracted from the texture.
  44823. */
  44824. this.sphericalPolynomial = null;
  44825. /**
  44826. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  44827. * This is usefull at run time to apply the good shader.
  44828. */
  44829. this.isPMREM = false;
  44830. if (!url) {
  44831. return;
  44832. }
  44833. this.name = url;
  44834. this.url = url;
  44835. this.hasAlpha = false;
  44836. this.isCube = true;
  44837. this._textureMatrix = BABYLON.Matrix.Identity();
  44838. if (size) {
  44839. this._isBABYLONPreprocessed = false;
  44840. this._noMipmap = noMipmap;
  44841. this._size = size;
  44842. this._useInGammaSpace = useInGammaSpace;
  44843. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  44844. }
  44845. else {
  44846. this._isBABYLONPreprocessed = true;
  44847. this._noMipmap = false;
  44848. this._useInGammaSpace = false;
  44849. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD;
  44850. }
  44851. this.isPMREM = this._usePMREMGenerator;
  44852. this._texture = this._getFromCache(url, this._noMipmap);
  44853. if (!this._texture) {
  44854. if (!scene.useDelayedTextureLoading) {
  44855. this.loadTexture();
  44856. }
  44857. else {
  44858. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  44859. }
  44860. }
  44861. }
  44862. /**
  44863. * Occurs when the file is a preprocessed .babylon.hdr file.
  44864. */
  44865. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  44866. var _this = this;
  44867. var mipLevels = 0;
  44868. var floatArrayView = null;
  44869. var mipmapGenerator = function (data) {
  44870. var mips = [];
  44871. var startIndex = 30;
  44872. for (var level = 0; level < mipLevels; level++) {
  44873. mips.push([]);
  44874. // Fill each pixel of the mip level.
  44875. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  44876. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44877. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  44878. mips[level].push(faceData);
  44879. startIndex += faceSize;
  44880. }
  44881. }
  44882. return mips;
  44883. };
  44884. var callback = function (buffer) {
  44885. // Create Native Array Views
  44886. var intArrayView = new Int32Array(buffer);
  44887. floatArrayView = new Float32Array(buffer);
  44888. // Fill header.
  44889. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  44890. _this._size = intArrayView[1]; // CubeMap max mip face size.
  44891. // Update Texture Information.
  44892. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  44893. // Fill polynomial information.
  44894. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  44895. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  44896. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  44897. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  44898. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  44899. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  44900. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  44901. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  44902. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  44903. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  44904. // Fill pixel data.
  44905. mipLevels = intArrayView[29]; // Number of mip levels.
  44906. var startIndex = 30;
  44907. var data = [];
  44908. var faceSize = Math.pow(_this._size, 2) * 3;
  44909. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44910. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  44911. }
  44912. var results = [];
  44913. var byteArray = null;
  44914. // Create uintarray fallback.
  44915. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  44916. // 3 channels of 1 bytes per pixel in bytes.
  44917. var byteBuffer = new ArrayBuffer(faceSize);
  44918. byteArray = new Uint8Array(byteBuffer);
  44919. mipmapGenerator = null;
  44920. }
  44921. // Push each faces.
  44922. for (var j = 0; j < 6; j++) {
  44923. var dataFace = data[j];
  44924. // If special cases.
  44925. if (_this._useInGammaSpace || byteArray) {
  44926. for (var i = 0; i < _this._size * _this._size; i++) {
  44927. // Put in gamma space if requested.
  44928. if (_this._useInGammaSpace) {
  44929. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44930. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44931. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44932. }
  44933. // Convert to int texture for fallback.
  44934. if (byteArray) {
  44935. // R
  44936. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44937. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44938. // G
  44939. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44940. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44941. // B
  44942. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44943. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44944. }
  44945. }
  44946. }
  44947. results.push(dataFace);
  44948. }
  44949. return results;
  44950. };
  44951. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  44952. };
  44953. /**
  44954. * Occurs when the file is raw .hdr file.
  44955. */
  44956. HDRCubeTexture.prototype.loadHDRTexture = function () {
  44957. var _this = this;
  44958. var callback = function (buffer) {
  44959. // Extract the raw linear data.
  44960. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  44961. // Generate harmonics if needed.
  44962. if (_this._generateHarmonics) {
  44963. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  44964. }
  44965. var results = [];
  44966. var byteArray = null;
  44967. // Create uintarray fallback.
  44968. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  44969. // 3 channels of 1 bytes per pixel in bytes.
  44970. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  44971. byteArray = new Uint8Array(byteBuffer);
  44972. }
  44973. // Push each faces.
  44974. for (var j = 0; j < 6; j++) {
  44975. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  44976. // If special cases.
  44977. if (_this._useInGammaSpace || byteArray) {
  44978. for (var i = 0; i < _this._size * _this._size; i++) {
  44979. // Put in gamma space if requested.
  44980. if (_this._useInGammaSpace) {
  44981. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44982. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44983. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44984. }
  44985. // Convert to int texture for fallback.
  44986. if (byteArray) {
  44987. // R
  44988. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44989. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44990. // G
  44991. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44992. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44993. // B
  44994. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44995. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44996. }
  44997. }
  44998. }
  44999. results.push(dataFace);
  45000. }
  45001. return results;
  45002. };
  45003. var mipmapGenerator = null;
  45004. if (!this._noMipmap && this._usePMREMGenerator) {
  45005. mipmapGenerator = function (data) {
  45006. // Custom setup of the generator matching with the PBR shader values.
  45007. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  45008. return generator.filterCubeMap();
  45009. };
  45010. }
  45011. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  45012. };
  45013. /**
  45014. * Starts the loading process of the texture.
  45015. */
  45016. HDRCubeTexture.prototype.loadTexture = function () {
  45017. if (this._isBABYLONPreprocessed) {
  45018. this.loadBabylonTexture();
  45019. }
  45020. else {
  45021. this.loadHDRTexture();
  45022. }
  45023. };
  45024. HDRCubeTexture.prototype.clone = function () {
  45025. var size = this._isBABYLONPreprocessed ? null : this._size;
  45026. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  45027. // Base texture
  45028. newTexture.level = this.level;
  45029. newTexture.wrapU = this.wrapU;
  45030. newTexture.wrapV = this.wrapV;
  45031. newTexture.coordinatesIndex = this.coordinatesIndex;
  45032. newTexture.coordinatesMode = this.coordinatesMode;
  45033. return newTexture;
  45034. };
  45035. // Methods
  45036. HDRCubeTexture.prototype.delayLoad = function () {
  45037. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45038. return;
  45039. }
  45040. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45041. this._texture = this._getFromCache(this.url, this._noMipmap);
  45042. if (!this._texture) {
  45043. this.loadTexture();
  45044. }
  45045. };
  45046. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  45047. return this._textureMatrix;
  45048. };
  45049. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45050. var texture = null;
  45051. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  45052. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  45053. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  45054. texture.name = parsedTexture.name;
  45055. texture.hasAlpha = parsedTexture.hasAlpha;
  45056. texture.level = parsedTexture.level;
  45057. texture.coordinatesMode = parsedTexture.coordinatesMode;
  45058. }
  45059. return texture;
  45060. };
  45061. HDRCubeTexture.prototype.serialize = function () {
  45062. if (!this.name) {
  45063. return null;
  45064. }
  45065. var serializationObject = {};
  45066. serializationObject.name = this.name;
  45067. serializationObject.hasAlpha = this.hasAlpha;
  45068. serializationObject.isCube = true;
  45069. serializationObject.level = this.level;
  45070. serializationObject.size = this._size;
  45071. serializationObject.coordinatesMode = this.coordinatesMode;
  45072. serializationObject.useInGammaSpace = this._useInGammaSpace;
  45073. serializationObject.generateHarmonics = this._generateHarmonics;
  45074. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  45075. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  45076. return serializationObject;
  45077. };
  45078. /**
  45079. * Saves as a file the data contained in the texture in a binary format.
  45080. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  45081. * as the spherical used in the lighting.
  45082. * @param url The HDR file url.
  45083. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  45084. * @param onError Method called if any error happens during download.
  45085. * @return The packed binary data.
  45086. */
  45087. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  45088. if (onError === void 0) { onError = null; }
  45089. var callback = function (buffer) {
  45090. var data = new Blob([buffer], { type: 'application/octet-stream' });
  45091. // Returns a URL you can use as a href.
  45092. var objUrl = window.URL.createObjectURL(data);
  45093. // Simulates a link to it and click to dowload.
  45094. var a = document.createElement("a");
  45095. document.body.appendChild(a);
  45096. a.style.display = "none";
  45097. a.href = objUrl;
  45098. a.download = "envmap.babylon.hdr";
  45099. a.click();
  45100. };
  45101. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  45102. };
  45103. /**
  45104. * Serializes the data contained in the texture in a binary format.
  45105. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  45106. * as the spherical used in the lighting.
  45107. * @param url The HDR file url.
  45108. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  45109. * @param onError Method called if any error happens during download.
  45110. * @return The packed binary data.
  45111. */
  45112. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  45113. if (onError === void 0) { onError = null; }
  45114. // Needs the url tho create the texture.
  45115. if (!url) {
  45116. return null;
  45117. }
  45118. // Check Power of two size.
  45119. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  45120. return null;
  45121. }
  45122. var getDataCallback = function (dataBuffer) {
  45123. // Extract the raw linear data.
  45124. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  45125. // Generate harmonics if needed.
  45126. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  45127. // Generate seamless faces
  45128. var mipGeneratorArray = [];
  45129. // Data are known to be in +X +Y +Z -X -Y -Z
  45130. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  45131. mipGeneratorArray.push(cubeData.right); // +X
  45132. mipGeneratorArray.push(cubeData.left); // -X
  45133. mipGeneratorArray.push(cubeData.up); // +Y
  45134. mipGeneratorArray.push(cubeData.down); // -Y
  45135. mipGeneratorArray.push(cubeData.front); // +Z
  45136. mipGeneratorArray.push(cubeData.back); // -Z
  45137. // Custom setup of the generator matching with the PBR shader values.
  45138. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  45139. var mippedData = generator.filterCubeMap();
  45140. // Compute required byte length.
  45141. var byteLength = 1 * 4; // Raw Data Version int32.
  45142. byteLength += 4; // CubeMap max mip face size int32.
  45143. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  45144. // Add data size.
  45145. byteLength += 4; // Number of mip levels int32.
  45146. for (var level = 0; level < mippedData.length; level++) {
  45147. var mipSize = size >> level;
  45148. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  45149. }
  45150. // Prepare binary structure.
  45151. var buffer = new ArrayBuffer(byteLength);
  45152. var intArrayView = new Int32Array(buffer);
  45153. var floatArrayView = new Float32Array(buffer);
  45154. // Fill header.
  45155. intArrayView[0] = 1; // Version 1.
  45156. intArrayView[1] = size; // CubeMap max mip face size.
  45157. // Fill polynomial information.
  45158. sphericalPolynomial.x.toArray(floatArrayView, 2);
  45159. sphericalPolynomial.y.toArray(floatArrayView, 5);
  45160. sphericalPolynomial.z.toArray(floatArrayView, 8);
  45161. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  45162. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  45163. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  45164. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  45165. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  45166. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  45167. // Fill pixel data.
  45168. intArrayView[29] = mippedData.length; // Number of mip levels.
  45169. var startIndex = 30;
  45170. for (var level = 0; level < mippedData.length; level++) {
  45171. // Fill each pixel of the mip level.
  45172. var faceSize = Math.pow(size >> level, 2) * 3;
  45173. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45174. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  45175. startIndex += faceSize;
  45176. }
  45177. }
  45178. // Callback.
  45179. callback(buffer);
  45180. };
  45181. // Download and process.
  45182. BABYLON.Tools.LoadFile(url, function (data) {
  45183. getDataCallback(data);
  45184. }, null, null, true, onError);
  45185. };
  45186. HDRCubeTexture._facesMapping = [
  45187. "right",
  45188. "up",
  45189. "front",
  45190. "left",
  45191. "down",
  45192. "back"
  45193. ];
  45194. return HDRCubeTexture;
  45195. })(BABYLON.BaseTexture);
  45196. BABYLON.HDRCubeTexture = HDRCubeTexture;
  45197. })(BABYLON || (BABYLON = {}));
  45198. var BABYLON;
  45199. (function (BABYLON) {
  45200. var Debug;
  45201. (function (Debug) {
  45202. /**
  45203. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  45204. */
  45205. var SkeletonViewer = (function () {
  45206. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  45207. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  45208. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  45209. this.skeleton = skeleton;
  45210. this.mesh = mesh;
  45211. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  45212. this.renderingGroupId = renderingGroupId;
  45213. this.color = BABYLON.Color3.White();
  45214. this._debugLines = [];
  45215. this._isEnabled = false;
  45216. this._scene = scene;
  45217. this.update();
  45218. this._renderFunction = this.update.bind(this);
  45219. }
  45220. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  45221. get: function () {
  45222. return this._isEnabled;
  45223. },
  45224. set: function (value) {
  45225. if (this._isEnabled === value) {
  45226. return;
  45227. }
  45228. this._isEnabled = value;
  45229. if (value) {
  45230. this._scene.registerBeforeRender(this._renderFunction);
  45231. }
  45232. else {
  45233. this._scene.unregisterBeforeRender(this._renderFunction);
  45234. }
  45235. },
  45236. enumerable: true,
  45237. configurable: true
  45238. });
  45239. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  45240. if (x === void 0) { x = 0; }
  45241. if (y === void 0) { y = 0; }
  45242. if (z === void 0) { z = 0; }
  45243. var tmat = BABYLON.Tmp.Matrix[0];
  45244. var parentBone = bone.getParent();
  45245. tmat.copyFrom(bone.getLocalMatrix());
  45246. if (x !== 0 || y !== 0 || z !== 0) {
  45247. var tmat2 = BABYLON.Tmp.Matrix[1];
  45248. BABYLON.Matrix.IdentityToRef(tmat2);
  45249. tmat2.m[12] = x;
  45250. tmat2.m[13] = y;
  45251. tmat2.m[14] = z;
  45252. tmat2.multiplyToRef(tmat, tmat);
  45253. }
  45254. if (parentBone) {
  45255. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  45256. }
  45257. tmat.multiplyToRef(meshMat, tmat);
  45258. position.x = tmat.m[12];
  45259. position.y = tmat.m[13];
  45260. position.z = tmat.m[14];
  45261. };
  45262. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  45263. var len = bones.length;
  45264. for (var i = 0; i < len; i++) {
  45265. var bone = bones[i];
  45266. var points = this._debugLines[i];
  45267. if (!points) {
  45268. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45269. this._debugLines[i] = points;
  45270. }
  45271. this._getBonePosition(points[0], bone, meshMat);
  45272. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  45273. }
  45274. };
  45275. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  45276. var len = bones.length;
  45277. var boneNum = 0;
  45278. for (var i = len - 1; i >= 0; i--) {
  45279. var childBone = bones[i];
  45280. var parentBone = childBone.getParent();
  45281. if (!parentBone) {
  45282. continue;
  45283. }
  45284. var points = this._debugLines[boneNum];
  45285. if (!points) {
  45286. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45287. this._debugLines[boneNum] = points;
  45288. }
  45289. this._getBonePosition(points[0], childBone, meshMat);
  45290. this._getBonePosition(points[1], parentBone, meshMat);
  45291. boneNum++;
  45292. }
  45293. };
  45294. SkeletonViewer.prototype.update = function () {
  45295. if (this.autoUpdateBonesMatrices) {
  45296. this._updateBoneMatrix(this.skeleton.bones[0]);
  45297. }
  45298. if (this.skeleton.bones[0].length === undefined) {
  45299. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  45300. }
  45301. else {
  45302. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  45303. }
  45304. if (!this._debugMesh) {
  45305. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  45306. this._debugMesh.renderingGroupId = this.renderingGroupId;
  45307. }
  45308. else {
  45309. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  45310. }
  45311. this._debugMesh.color = this.color;
  45312. };
  45313. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  45314. if (bone.getParent()) {
  45315. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  45316. }
  45317. var children = bone.children;
  45318. var len = children.length;
  45319. for (var i = 0; i < len; i++) {
  45320. this._updateBoneMatrix(children[i]);
  45321. }
  45322. };
  45323. SkeletonViewer.prototype.dispose = function () {
  45324. if (this._debugMesh) {
  45325. this.isEnabled = false;
  45326. this._debugMesh.dispose();
  45327. this._debugMesh = null;
  45328. }
  45329. };
  45330. return SkeletonViewer;
  45331. })();
  45332. Debug.SkeletonViewer = SkeletonViewer;
  45333. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45334. })(BABYLON || (BABYLON = {}));
  45335. var BABYLON;
  45336. (function (BABYLON) {
  45337. var maxSimultaneousLights = 4;
  45338. var PBRMaterialDefines = (function (_super) {
  45339. __extends(PBRMaterialDefines, _super);
  45340. function PBRMaterialDefines() {
  45341. _super.call(this);
  45342. this.ALBEDO = false;
  45343. this.AMBIENT = false;
  45344. this.OPACITY = false;
  45345. this.OPACITYRGB = false;
  45346. this.REFLECTION = false;
  45347. this.EMISSIVE = false;
  45348. this.REFLECTIVITY = false;
  45349. this.BUMP = false;
  45350. this.PARALLAX = false;
  45351. this.PARALLAXOCCLUSION = false;
  45352. this.SPECULAROVERALPHA = false;
  45353. this.CLIPPLANE = false;
  45354. this.ALPHATEST = false;
  45355. this.ALPHAFROMALBEDO = false;
  45356. this.POINTSIZE = false;
  45357. this.FOG = false;
  45358. this.LIGHT0 = false;
  45359. this.LIGHT1 = false;
  45360. this.LIGHT2 = false;
  45361. this.LIGHT3 = false;
  45362. this.SPOTLIGHT0 = false;
  45363. this.SPOTLIGHT1 = false;
  45364. this.SPOTLIGHT2 = false;
  45365. this.SPOTLIGHT3 = false;
  45366. this.HEMILIGHT0 = false;
  45367. this.HEMILIGHT1 = false;
  45368. this.HEMILIGHT2 = false;
  45369. this.HEMILIGHT3 = false;
  45370. this.POINTLIGHT0 = false;
  45371. this.POINTLIGHT1 = false;
  45372. this.POINTLIGHT2 = false;
  45373. this.POINTLIGHT3 = false;
  45374. this.DIRLIGHT0 = false;
  45375. this.DIRLIGHT1 = false;
  45376. this.DIRLIGHT2 = false;
  45377. this.DIRLIGHT3 = false;
  45378. this.SPECULARTERM = false;
  45379. this.SHADOW0 = false;
  45380. this.SHADOW1 = false;
  45381. this.SHADOW2 = false;
  45382. this.SHADOW3 = false;
  45383. this.SHADOWS = false;
  45384. this.SHADOWVSM0 = false;
  45385. this.SHADOWVSM1 = false;
  45386. this.SHADOWVSM2 = false;
  45387. this.SHADOWVSM3 = false;
  45388. this.SHADOWPCF0 = false;
  45389. this.SHADOWPCF1 = false;
  45390. this.SHADOWPCF2 = false;
  45391. this.SHADOWPCF3 = false;
  45392. this.OPACITYFRESNEL = false;
  45393. this.EMISSIVEFRESNEL = false;
  45394. this.FRESNEL = false;
  45395. this.NORMAL = false;
  45396. this.UV1 = false;
  45397. this.UV2 = false;
  45398. this.VERTEXCOLOR = false;
  45399. this.VERTEXALPHA = false;
  45400. this.NUM_BONE_INFLUENCERS = 0;
  45401. this.BonesPerMesh = 0;
  45402. this.INSTANCES = false;
  45403. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45404. this.MICROSURFACEAUTOMATIC = false;
  45405. this.EMISSIVEASILLUMINATION = false;
  45406. this.LINKEMISSIVEWITHALBEDO = false;
  45407. this.LIGHTMAP = false;
  45408. this.USELIGHTMAPASSHADOWMAP = false;
  45409. this.REFLECTIONMAP_3D = false;
  45410. this.REFLECTIONMAP_SPHERICAL = false;
  45411. this.REFLECTIONMAP_PLANAR = false;
  45412. this.REFLECTIONMAP_CUBIC = false;
  45413. this.REFLECTIONMAP_PROJECTION = false;
  45414. this.REFLECTIONMAP_SKYBOX = false;
  45415. this.REFLECTIONMAP_EXPLICIT = false;
  45416. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45417. this.INVERTCUBICMAP = false;
  45418. this.LOGARITHMICDEPTH = false;
  45419. this.CAMERATONEMAP = false;
  45420. this.CAMERACONTRAST = false;
  45421. this.OVERLOADEDVALUES = false;
  45422. this.OVERLOADEDSHADOWVALUES = false;
  45423. this.USESPHERICALFROMREFLECTIONMAP = false;
  45424. this.REFRACTION = false;
  45425. this.REFRACTIONMAP_3D = false;
  45426. this.LINKREFRACTIONTOTRANSPARENCY = false;
  45427. this.REFRACTIONMAPINLINEARSPACE = false;
  45428. this.LODBASEDMICROSFURACE = false;
  45429. this.USEPHYSICALLIGHTFALLOFF = false;
  45430. this.RADIANCEOVERALPHA = false;
  45431. this.USEPMREMREFLECTION = false;
  45432. this.USEPMREMREFRACTION = false;
  45433. this._keys = Object.keys(this);
  45434. }
  45435. return PBRMaterialDefines;
  45436. })(BABYLON.MaterialDefines);
  45437. /**
  45438. * The Physically based material of BJS.
  45439. *
  45440. * This offers the main features of a standard PBR material.
  45441. * For more information, please refer to the documentation :
  45442. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45443. */
  45444. var PBRMaterial = (function (_super) {
  45445. __extends(PBRMaterial, _super);
  45446. /**
  45447. * Instantiates a new PBRMaterial instance.
  45448. *
  45449. * @param name The material name
  45450. * @param scene The scene the material will be use in.
  45451. */
  45452. function PBRMaterial(name, scene) {
  45453. var _this = this;
  45454. _super.call(this, name, scene);
  45455. /**
  45456. * Intensity of the direct lights e.g. the four lights available in your scene.
  45457. * This impacts both the direct diffuse and specular highlights.
  45458. */
  45459. this.directIntensity = 1.0;
  45460. /**
  45461. * Intensity of the emissive part of the material.
  45462. * This helps controlling the emissive effect without modifying the emissive color.
  45463. */
  45464. this.emissiveIntensity = 1.0;
  45465. /**
  45466. * Intensity of the environment e.g. how much the environment will light the object
  45467. * either through harmonics for rough material or through the refelction for shiny ones.
  45468. */
  45469. this.environmentIntensity = 1.0;
  45470. /**
  45471. * This is a special control allowing the reduction of the specular highlights coming from the
  45472. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45473. */
  45474. this.specularIntensity = 1.0;
  45475. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  45476. /**
  45477. * Debug Control allowing disabling the bump map on this material.
  45478. */
  45479. this.disableBumpMap = false;
  45480. /**
  45481. * Debug Control helping enforcing or dropping the darkness of shadows.
  45482. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  45483. */
  45484. this.overloadedShadowIntensity = 1.0;
  45485. /**
  45486. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  45487. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  45488. */
  45489. this.overloadedShadeIntensity = 1.0;
  45490. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  45491. /**
  45492. * The camera exposure used on this material.
  45493. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45494. * This corresponds to a photographic exposure.
  45495. */
  45496. this.cameraExposure = 1.0;
  45497. /**
  45498. * The camera contrast used on this material.
  45499. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  45500. */
  45501. this.cameraContrast = 1.0;
  45502. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  45503. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  45504. /**
  45505. * Debug Control allowing to overload the ambient color.
  45506. * This as to be use with the overloadedAmbientIntensity parameter.
  45507. */
  45508. this.overloadedAmbient = BABYLON.Color3.White();
  45509. /**
  45510. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  45511. */
  45512. this.overloadedAmbientIntensity = 0.0;
  45513. /**
  45514. * Debug Control allowing to overload the albedo color.
  45515. * This as to be use with the overloadedAlbedoIntensity parameter.
  45516. */
  45517. this.overloadedAlbedo = BABYLON.Color3.White();
  45518. /**
  45519. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  45520. */
  45521. this.overloadedAlbedoIntensity = 0.0;
  45522. /**
  45523. * Debug Control allowing to overload the reflectivity color.
  45524. * This as to be use with the overloadedReflectivityIntensity parameter.
  45525. */
  45526. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  45527. /**
  45528. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  45529. */
  45530. this.overloadedReflectivityIntensity = 0.0;
  45531. /**
  45532. * Debug Control allowing to overload the emissive color.
  45533. * This as to be use with the overloadedEmissiveIntensity parameter.
  45534. */
  45535. this.overloadedEmissive = BABYLON.Color3.White();
  45536. /**
  45537. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  45538. */
  45539. this.overloadedEmissiveIntensity = 0.0;
  45540. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  45541. /**
  45542. * Debug Control allowing to overload the reflection color.
  45543. * This as to be use with the overloadedReflectionIntensity parameter.
  45544. */
  45545. this.overloadedReflection = BABYLON.Color3.White();
  45546. /**
  45547. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  45548. */
  45549. this.overloadedReflectionIntensity = 0.0;
  45550. /**
  45551. * Debug Control allowing to overload the microsurface.
  45552. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  45553. */
  45554. this.overloadedMicroSurface = 0.0;
  45555. /**
  45556. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  45557. */
  45558. this.overloadedMicroSurfaceIntensity = 0.0;
  45559. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  45560. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45561. /**
  45562. * AKA Diffuse Color in other nomenclature.
  45563. */
  45564. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45565. /**
  45566. * AKA Specular Color in other nomenclature.
  45567. */
  45568. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45569. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  45570. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45571. /**
  45572. * AKA Glossiness in other nomenclature.
  45573. */
  45574. this.microSurface = 0.9;
  45575. /**
  45576. * source material index of refraction (IOR)' / 'destination material IOR.
  45577. */
  45578. this.indexOfRefraction = 0.66;
  45579. /**
  45580. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45581. */
  45582. this.invertRefractionY = false;
  45583. /**
  45584. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45585. * Materials half opaque for instance using refraction could benefit from this control.
  45586. */
  45587. this.linkRefractionWithTransparency = false;
  45588. /**
  45589. * The emissive and albedo are linked to never be more than one (Energy conservation).
  45590. */
  45591. this.linkEmissiveWithAlbedo = false;
  45592. this.useLightmapAsShadowmap = false;
  45593. /**
  45594. * In this mode, the emissive informtaion will always be added to the lighting once.
  45595. * A light for instance can be thought as emissive.
  45596. */
  45597. this.useEmissiveAsIllumination = false;
  45598. /**
  45599. * Secifies that the alpha is coming form the albedo channel alpha channel.
  45600. */
  45601. this.useAlphaFromAlbedoTexture = false;
  45602. /**
  45603. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45604. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45605. */
  45606. this.useSpecularOverAlpha = true;
  45607. /**
  45608. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45609. */
  45610. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45611. /**
  45612. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45613. * The material will try to infer what glossiness each pixel should be.
  45614. */
  45615. this.useAutoMicroSurfaceFromReflectivityMap = false;
  45616. /**
  45617. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  45618. * the creation of the material.
  45619. */
  45620. this.useScalarInLinearSpace = false;
  45621. /**
  45622. * BJS is using an harcoded light falloff based on a manually sets up range.
  45623. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45624. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45625. */
  45626. this.usePhysicalLightFalloff = true;
  45627. /**
  45628. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45629. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45630. */
  45631. this.useRadianceOverAlpha = true;
  45632. /**
  45633. * Allows using the bump map in parallax mode.
  45634. */
  45635. this.useParallax = false;
  45636. /**
  45637. * Allows using the bump map in parallax occlusion mode.
  45638. */
  45639. this.useParallaxOcclusion = false;
  45640. /**
  45641. * Controls the scale bias of the parallax mode.
  45642. */
  45643. this.parallaxScaleBias = 0.05;
  45644. this.disableLighting = false;
  45645. this._renderTargets = new BABYLON.SmartArray(16);
  45646. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  45647. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45648. this._tempColor = new BABYLON.Color3();
  45649. this._defines = new PBRMaterialDefines();
  45650. this._cachedDefines = new PBRMaterialDefines();
  45651. this._myScene = null;
  45652. this._myShadowGenerator = null;
  45653. this._cachedDefines.BonesPerMesh = -1;
  45654. this.getRenderTargetTextures = function () {
  45655. _this._renderTargets.reset();
  45656. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  45657. _this._renderTargets.push(_this.reflectionTexture);
  45658. }
  45659. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  45660. _this._renderTargets.push(_this.refractionTexture);
  45661. }
  45662. return _this._renderTargets;
  45663. };
  45664. }
  45665. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  45666. get: function () {
  45667. return this._useLogarithmicDepth;
  45668. },
  45669. set: function (value) {
  45670. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45671. },
  45672. enumerable: true,
  45673. configurable: true
  45674. });
  45675. PBRMaterial.prototype.needAlphaBlending = function () {
  45676. if (this.linkRefractionWithTransparency) {
  45677. return false;
  45678. }
  45679. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  45680. };
  45681. PBRMaterial.prototype.needAlphaTesting = function () {
  45682. if (this.linkRefractionWithTransparency) {
  45683. return false;
  45684. }
  45685. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  45686. };
  45687. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45688. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  45689. };
  45690. PBRMaterial.prototype.getAlphaTestTexture = function () {
  45691. return this.albedoTexture;
  45692. };
  45693. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  45694. if (!mesh) {
  45695. return true;
  45696. }
  45697. if (this._defines.INSTANCES !== useInstances) {
  45698. return false;
  45699. }
  45700. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  45701. return true;
  45702. }
  45703. return false;
  45704. };
  45705. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  45706. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  45707. };
  45708. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  45709. if (!useScalarInLinear) {
  45710. color.toLinearSpaceToRef(ref);
  45711. }
  45712. else {
  45713. ref.r = color.r;
  45714. ref.g = color.g;
  45715. ref.b = color.b;
  45716. }
  45717. };
  45718. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  45719. var lightIndex = 0;
  45720. var depthValuesAlreadySet = false;
  45721. for (var index = 0; index < scene.lights.length; index++) {
  45722. var light = scene.lights[index];
  45723. if (!light.isEnabled()) {
  45724. continue;
  45725. }
  45726. if (!light.canAffectMesh(mesh)) {
  45727. continue;
  45728. }
  45729. this._lightRadiuses[lightIndex] = light.radius;
  45730. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  45731. // GAMMA CORRECTION.
  45732. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  45733. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  45734. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  45735. if (defines["SPECULARTERM"]) {
  45736. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  45737. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  45738. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  45739. }
  45740. // Shadows
  45741. if (scene.shadowsEnabled) {
  45742. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  45743. }
  45744. lightIndex++;
  45745. if (lightIndex === maxSimultaneousLights)
  45746. break;
  45747. }
  45748. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  45749. };
  45750. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  45751. if (this.checkReadyOnlyOnce) {
  45752. if (this._wasPreviouslyReady) {
  45753. return true;
  45754. }
  45755. }
  45756. var scene = this.getScene();
  45757. if (!this.checkReadyOnEveryCall) {
  45758. if (this._renderId === scene.getRenderId()) {
  45759. if (this._checkCache(scene, mesh, useInstances)) {
  45760. return true;
  45761. }
  45762. }
  45763. }
  45764. var engine = scene.getEngine();
  45765. var needNormals = false;
  45766. var needUVs = false;
  45767. this._defines.reset();
  45768. if (scene.texturesEnabled) {
  45769. // Textures
  45770. if (scene.texturesEnabled) {
  45771. if (scene.getEngine().getCaps().textureLOD) {
  45772. this._defines.LODBASEDMICROSFURACE = true;
  45773. }
  45774. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45775. if (!this.albedoTexture.isReady()) {
  45776. return false;
  45777. }
  45778. else {
  45779. needUVs = true;
  45780. this._defines.ALBEDO = true;
  45781. }
  45782. }
  45783. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45784. if (!this.ambientTexture.isReady()) {
  45785. return false;
  45786. }
  45787. else {
  45788. needUVs = true;
  45789. this._defines.AMBIENT = true;
  45790. }
  45791. }
  45792. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45793. if (!this.opacityTexture.isReady()) {
  45794. return false;
  45795. }
  45796. else {
  45797. needUVs = true;
  45798. this._defines.OPACITY = true;
  45799. if (this.opacityTexture.getAlphaFromRGB) {
  45800. this._defines.OPACITYRGB = true;
  45801. }
  45802. }
  45803. }
  45804. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45805. if (!this.reflectionTexture.isReady()) {
  45806. return false;
  45807. }
  45808. else {
  45809. needNormals = true;
  45810. this._defines.REFLECTION = true;
  45811. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45812. this._defines.INVERTCUBICMAP = true;
  45813. }
  45814. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  45815. switch (this.reflectionTexture.coordinatesMode) {
  45816. case BABYLON.Texture.CUBIC_MODE:
  45817. case BABYLON.Texture.INVCUBIC_MODE:
  45818. this._defines.REFLECTIONMAP_CUBIC = true;
  45819. break;
  45820. case BABYLON.Texture.EXPLICIT_MODE:
  45821. this._defines.REFLECTIONMAP_EXPLICIT = true;
  45822. break;
  45823. case BABYLON.Texture.PLANAR_MODE:
  45824. this._defines.REFLECTIONMAP_PLANAR = true;
  45825. break;
  45826. case BABYLON.Texture.PROJECTION_MODE:
  45827. this._defines.REFLECTIONMAP_PROJECTION = true;
  45828. break;
  45829. case BABYLON.Texture.SKYBOX_MODE:
  45830. this._defines.REFLECTIONMAP_SKYBOX = true;
  45831. break;
  45832. case BABYLON.Texture.SPHERICAL_MODE:
  45833. this._defines.REFLECTIONMAP_SPHERICAL = true;
  45834. break;
  45835. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45836. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45837. break;
  45838. }
  45839. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  45840. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  45841. needNormals = true;
  45842. if (this.reflectionTexture.isPMREM) {
  45843. this._defines.USEPMREMREFLECTION = true;
  45844. }
  45845. }
  45846. }
  45847. }
  45848. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45849. if (!this.lightmapTexture.isReady()) {
  45850. return false;
  45851. }
  45852. else {
  45853. needUVs = true;
  45854. this._defines.LIGHTMAP = true;
  45855. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  45856. }
  45857. }
  45858. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45859. if (!this.emissiveTexture.isReady()) {
  45860. return false;
  45861. }
  45862. else {
  45863. needUVs = true;
  45864. this._defines.EMISSIVE = true;
  45865. }
  45866. }
  45867. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45868. if (!this.reflectivityTexture.isReady()) {
  45869. return false;
  45870. }
  45871. else {
  45872. needUVs = true;
  45873. this._defines.REFLECTIVITY = true;
  45874. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  45875. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  45876. }
  45877. }
  45878. }
  45879. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  45880. if (!this.bumpTexture.isReady()) {
  45881. return false;
  45882. }
  45883. else {
  45884. needUVs = true;
  45885. this._defines.BUMP = true;
  45886. if (this.useParallax) {
  45887. this._defines.PARALLAX = true;
  45888. if (this.useParallaxOcclusion) {
  45889. this._defines.PARALLAXOCCLUSION = true;
  45890. }
  45891. }
  45892. }
  45893. }
  45894. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45895. if (!this.refractionTexture.isReady()) {
  45896. return false;
  45897. }
  45898. else {
  45899. needUVs = true;
  45900. this._defines.REFRACTION = true;
  45901. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  45902. if (this.linkRefractionWithTransparency) {
  45903. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45904. }
  45905. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  45906. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  45907. if (this.refractionTexture.isPMREM) {
  45908. this._defines.USEPMREMREFRACTION = true;
  45909. }
  45910. }
  45911. }
  45912. }
  45913. }
  45914. // Effect
  45915. if (scene.clipPlane) {
  45916. this._defines.CLIPPLANE = true;
  45917. }
  45918. if (engine.getAlphaTesting()) {
  45919. this._defines.ALPHATEST = true;
  45920. }
  45921. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45922. this._defines.ALPHAFROMALBEDO = true;
  45923. }
  45924. if (this.useEmissiveAsIllumination) {
  45925. this._defines.EMISSIVEASILLUMINATION = true;
  45926. }
  45927. if (this.linkEmissiveWithAlbedo) {
  45928. this._defines.LINKEMISSIVEWITHALBEDO = true;
  45929. }
  45930. if (this.useLogarithmicDepth) {
  45931. this._defines.LOGARITHMICDEPTH = true;
  45932. }
  45933. if (this.cameraContrast != 1) {
  45934. this._defines.CAMERACONTRAST = true;
  45935. }
  45936. if (this.cameraExposure != 1) {
  45937. this._defines.CAMERATONEMAP = true;
  45938. }
  45939. if (this.overloadedShadeIntensity != 1 ||
  45940. this.overloadedShadowIntensity != 1) {
  45941. this._defines.OVERLOADEDSHADOWVALUES = true;
  45942. }
  45943. if (this.overloadedMicroSurfaceIntensity > 0 ||
  45944. this.overloadedEmissiveIntensity > 0 ||
  45945. this.overloadedReflectivityIntensity > 0 ||
  45946. this.overloadedAlbedoIntensity > 0 ||
  45947. this.overloadedAmbientIntensity > 0 ||
  45948. this.overloadedReflectionIntensity > 0) {
  45949. this._defines.OVERLOADEDVALUES = true;
  45950. }
  45951. // Point size
  45952. if (this.pointsCloud || scene.forcePointsCloud) {
  45953. this._defines.POINTSIZE = true;
  45954. }
  45955. // Fog
  45956. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45957. this._defines.FOG = true;
  45958. }
  45959. if (scene.lightsEnabled && !this.disableLighting) {
  45960. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  45961. }
  45962. if (BABYLON.StandardMaterial.FresnelEnabled) {
  45963. // Fresnel
  45964. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  45965. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45966. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  45967. this._defines.OPACITYFRESNEL = true;
  45968. }
  45969. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45970. this._defines.EMISSIVEFRESNEL = true;
  45971. }
  45972. needNormals = true;
  45973. this._defines.FRESNEL = true;
  45974. }
  45975. }
  45976. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  45977. this._defines.SPECULAROVERALPHA = true;
  45978. }
  45979. if (this.usePhysicalLightFalloff) {
  45980. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  45981. }
  45982. if (this.useRadianceOverAlpha) {
  45983. this._defines.RADIANCEOVERALPHA = true;
  45984. }
  45985. // Attribs
  45986. if (mesh) {
  45987. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45988. this._defines.NORMAL = true;
  45989. }
  45990. if (needUVs) {
  45991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45992. this._defines.UV1 = true;
  45993. }
  45994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45995. this._defines.UV2 = true;
  45996. }
  45997. }
  45998. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  45999. this._defines.VERTEXCOLOR = true;
  46000. if (mesh.hasVertexAlpha) {
  46001. this._defines.VERTEXALPHA = true;
  46002. }
  46003. }
  46004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46005. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  46006. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  46007. }
  46008. // Instances
  46009. if (useInstances) {
  46010. this._defines.INSTANCES = true;
  46011. }
  46012. }
  46013. // Get correct effect
  46014. if (!this._defines.isEqual(this._cachedDefines)) {
  46015. this._defines.cloneTo(this._cachedDefines);
  46016. scene.resetCachedMaterial();
  46017. // Fallbacks
  46018. var fallbacks = new BABYLON.EffectFallbacks();
  46019. if (this._defines.REFLECTION) {
  46020. fallbacks.addFallback(0, "REFLECTION");
  46021. }
  46022. if (this._defines.REFRACTION) {
  46023. fallbacks.addFallback(0, "REFRACTION");
  46024. }
  46025. if (this._defines.REFLECTIVITY) {
  46026. fallbacks.addFallback(0, "REFLECTIVITY");
  46027. }
  46028. if (this._defines.BUMP) {
  46029. fallbacks.addFallback(0, "BUMP");
  46030. }
  46031. if (this._defines.PARALLAX) {
  46032. fallbacks.addFallback(1, "PARALLAX");
  46033. }
  46034. if (this._defines.PARALLAXOCCLUSION) {
  46035. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  46036. }
  46037. if (this._defines.SPECULAROVERALPHA) {
  46038. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  46039. }
  46040. if (this._defines.FOG) {
  46041. fallbacks.addFallback(1, "FOG");
  46042. }
  46043. if (this._defines.POINTSIZE) {
  46044. fallbacks.addFallback(0, "POINTSIZE");
  46045. }
  46046. if (this._defines.LOGARITHMICDEPTH) {
  46047. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  46048. }
  46049. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  46050. if (this._defines.SPECULARTERM) {
  46051. fallbacks.addFallback(0, "SPECULARTERM");
  46052. }
  46053. if (this._defines.OPACITYFRESNEL) {
  46054. fallbacks.addFallback(1, "OPACITYFRESNEL");
  46055. }
  46056. if (this._defines.EMISSIVEFRESNEL) {
  46057. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  46058. }
  46059. if (this._defines.FRESNEL) {
  46060. fallbacks.addFallback(3, "FRESNEL");
  46061. }
  46062. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  46063. fallbacks.addCPUSkinningFallback(0, mesh);
  46064. }
  46065. //Attributes
  46066. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46067. if (this._defines.NORMAL) {
  46068. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46069. }
  46070. if (this._defines.UV1) {
  46071. attribs.push(BABYLON.VertexBuffer.UVKind);
  46072. }
  46073. if (this._defines.UV2) {
  46074. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46075. }
  46076. if (this._defines.VERTEXCOLOR) {
  46077. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46078. }
  46079. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  46080. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  46081. // Legacy browser patch
  46082. var shaderName = "pbr";
  46083. if (!scene.getEngine().getCaps().standardDerivatives) {
  46084. shaderName = "legacypbr";
  46085. }
  46086. var join = this._defines.toString();
  46087. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46088. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  46089. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  46090. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  46091. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  46092. "vFogInfos", "vFogColor", "pointSize",
  46093. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46094. "mBones",
  46095. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46096. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  46097. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  46098. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  46099. "logarithmicDepthConstant",
  46100. "vSphericalX", "vSphericalY", "vSphericalZ",
  46101. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46102. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46103. "vMicrosurfaceTextureLods", "vLightRadiuses"
  46104. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  46105. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  46106. ], join, fallbacks, this.onCompiled, this.onError);
  46107. }
  46108. if (!this._effect.isReady()) {
  46109. return false;
  46110. }
  46111. this._renderId = scene.getRenderId();
  46112. this._wasPreviouslyReady = true;
  46113. if (mesh) {
  46114. if (!mesh._materialDefines) {
  46115. mesh._materialDefines = new PBRMaterialDefines();
  46116. }
  46117. this._defines.cloneTo(mesh._materialDefines);
  46118. }
  46119. return true;
  46120. };
  46121. PBRMaterial.prototype.unbind = function () {
  46122. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  46123. this._effect.setTexture("reflection2DSampler", null);
  46124. }
  46125. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  46126. this._effect.setTexture("refraction2DSampler", null);
  46127. }
  46128. _super.prototype.unbind.call(this);
  46129. };
  46130. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46131. this._effect.setMatrix("world", world);
  46132. };
  46133. PBRMaterial.prototype.bind = function (world, mesh) {
  46134. this._myScene = this.getScene();
  46135. // Matrices
  46136. this.bindOnlyWorldMatrix(world);
  46137. // Bones
  46138. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46139. if (this._myScene.getCachedMaterial() !== this) {
  46140. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  46141. if (BABYLON.StandardMaterial.FresnelEnabled) {
  46142. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  46143. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  46144. }
  46145. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  46146. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  46147. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  46148. }
  46149. }
  46150. // Textures
  46151. if (this._myScene.texturesEnabled) {
  46152. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46153. this._effect.setTexture("albedoSampler", this.albedoTexture);
  46154. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  46155. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  46156. }
  46157. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46158. this._effect.setTexture("ambientSampler", this.ambientTexture);
  46159. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  46160. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  46161. }
  46162. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46163. this._effect.setTexture("opacitySampler", this.opacityTexture);
  46164. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  46165. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  46166. }
  46167. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46168. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  46169. if (this.reflectionTexture.isCube) {
  46170. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  46171. }
  46172. else {
  46173. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  46174. }
  46175. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  46176. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  46177. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  46178. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  46179. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  46180. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  46181. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  46182. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  46183. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  46184. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  46185. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  46186. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  46187. }
  46188. }
  46189. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46190. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  46191. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  46192. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  46193. }
  46194. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46195. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  46196. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  46197. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  46198. }
  46199. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46200. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  46201. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  46202. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  46203. }
  46204. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  46205. this._effect.setTexture("bumpSampler", this.bumpTexture);
  46206. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  46207. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  46208. }
  46209. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46210. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  46211. var depth = 1.0;
  46212. if (this.refractionTexture.isCube) {
  46213. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  46214. }
  46215. else {
  46216. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  46217. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  46218. if (this.refractionTexture.depth) {
  46219. depth = this.refractionTexture.depth;
  46220. }
  46221. }
  46222. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  46223. }
  46224. if ((this.reflectionTexture || this.refractionTexture)) {
  46225. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  46226. }
  46227. }
  46228. // Clip plane
  46229. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  46230. // Point size
  46231. if (this.pointsCloud) {
  46232. this._effect.setFloat("pointSize", this.pointSize);
  46233. }
  46234. // Colors
  46235. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  46236. // GAMMA CORRECTION.
  46237. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  46238. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  46239. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46240. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  46241. // GAMMA CORRECTION.
  46242. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  46243. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  46244. // GAMMA CORRECTION.
  46245. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  46246. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  46247. }
  46248. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  46249. // GAMMA CORRECTION.
  46250. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  46251. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  46252. // Lights
  46253. if (this._myScene.lightsEnabled && !this.disableLighting) {
  46254. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  46255. }
  46256. // View
  46257. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  46258. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  46259. }
  46260. // Fog
  46261. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  46262. this._lightingInfos.x = this.directIntensity;
  46263. this._lightingInfos.y = this.emissiveIntensity;
  46264. this._lightingInfos.z = this.environmentIntensity;
  46265. this._lightingInfos.w = this.specularIntensity;
  46266. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  46267. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  46268. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  46269. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  46270. this._cameraInfos.x = this.cameraExposure;
  46271. this._cameraInfos.y = this.cameraContrast;
  46272. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  46273. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  46274. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  46275. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  46276. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  46277. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  46278. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  46279. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  46280. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  46281. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  46282. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  46283. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  46284. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  46285. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  46286. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  46287. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  46288. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  46289. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  46290. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  46291. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  46292. // Log. depth
  46293. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  46294. }
  46295. _super.prototype.bind.call(this, world, mesh);
  46296. this._myScene = null;
  46297. };
  46298. PBRMaterial.prototype.getAnimatables = function () {
  46299. var results = [];
  46300. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  46301. results.push(this.albedoTexture);
  46302. }
  46303. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  46304. results.push(this.ambientTexture);
  46305. }
  46306. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  46307. results.push(this.opacityTexture);
  46308. }
  46309. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  46310. results.push(this.reflectionTexture);
  46311. }
  46312. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  46313. results.push(this.emissiveTexture);
  46314. }
  46315. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  46316. results.push(this.reflectivityTexture);
  46317. }
  46318. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  46319. results.push(this.bumpTexture);
  46320. }
  46321. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  46322. results.push(this.lightmapTexture);
  46323. }
  46324. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  46325. results.push(this.refractionTexture);
  46326. }
  46327. return results;
  46328. };
  46329. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46330. if (forceDisposeTextures) {
  46331. if (this.albedoTexture) {
  46332. this.albedoTexture.dispose();
  46333. }
  46334. if (this.ambientTexture) {
  46335. this.ambientTexture.dispose();
  46336. }
  46337. if (this.opacityTexture) {
  46338. this.opacityTexture.dispose();
  46339. }
  46340. if (this.reflectionTexture) {
  46341. this.reflectionTexture.dispose();
  46342. }
  46343. if (this.emissiveTexture) {
  46344. this.emissiveTexture.dispose();
  46345. }
  46346. if (this.reflectivityTexture) {
  46347. this.reflectivityTexture.dispose();
  46348. }
  46349. if (this.bumpTexture) {
  46350. this.bumpTexture.dispose();
  46351. }
  46352. if (this.lightmapTexture) {
  46353. this.lightmapTexture.dispose();
  46354. }
  46355. if (this.refractionTexture) {
  46356. this.refractionTexture.dispose();
  46357. }
  46358. }
  46359. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46360. };
  46361. PBRMaterial.prototype.clone = function (name) {
  46362. var _this = this;
  46363. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46364. };
  46365. PBRMaterial.prototype.serialize = function () {
  46366. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46367. serializationObject.customType = "BABYLON.PBRMaterial";
  46368. return serializationObject;
  46369. };
  46370. // Statics
  46371. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46372. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46373. };
  46374. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  46375. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  46376. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  46377. PBRMaterial._scaledReflection = new BABYLON.Color3();
  46378. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  46379. __decorate([
  46380. BABYLON.serialize()
  46381. ], PBRMaterial.prototype, "directIntensity", void 0);
  46382. __decorate([
  46383. BABYLON.serialize()
  46384. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46385. __decorate([
  46386. BABYLON.serialize()
  46387. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46388. __decorate([
  46389. BABYLON.serialize()
  46390. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46391. __decorate([
  46392. BABYLON.serialize()
  46393. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46394. __decorate([
  46395. BABYLON.serialize()
  46396. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  46397. __decorate([
  46398. BABYLON.serialize()
  46399. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  46400. __decorate([
  46401. BABYLON.serialize()
  46402. ], PBRMaterial.prototype, "cameraExposure", void 0);
  46403. __decorate([
  46404. BABYLON.serialize()
  46405. ], PBRMaterial.prototype, "cameraContrast", void 0);
  46406. __decorate([
  46407. BABYLON.serializeAsColor3()
  46408. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  46409. __decorate([
  46410. BABYLON.serialize()
  46411. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  46412. __decorate([
  46413. BABYLON.serializeAsColor3()
  46414. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  46415. __decorate([
  46416. BABYLON.serialize()
  46417. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  46418. __decorate([
  46419. BABYLON.serializeAsColor3()
  46420. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  46421. __decorate([
  46422. BABYLON.serialize()
  46423. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  46424. __decorate([
  46425. BABYLON.serializeAsColor3()
  46426. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  46427. __decorate([
  46428. BABYLON.serialize()
  46429. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  46430. __decorate([
  46431. BABYLON.serializeAsColor3()
  46432. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  46433. __decorate([
  46434. BABYLON.serialize()
  46435. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  46436. __decorate([
  46437. BABYLON.serialize()
  46438. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  46439. __decorate([
  46440. BABYLON.serialize()
  46441. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  46442. __decorate([
  46443. BABYLON.serializeAsTexture()
  46444. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46445. __decorate([
  46446. BABYLON.serializeAsTexture()
  46447. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46448. __decorate([
  46449. BABYLON.serializeAsTexture()
  46450. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46451. __decorate([
  46452. BABYLON.serializeAsTexture()
  46453. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46454. __decorate([
  46455. BABYLON.serializeAsTexture()
  46456. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46457. __decorate([
  46458. BABYLON.serializeAsTexture()
  46459. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46460. __decorate([
  46461. BABYLON.serializeAsTexture()
  46462. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46463. __decorate([
  46464. BABYLON.serializeAsTexture()
  46465. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46466. __decorate([
  46467. BABYLON.serializeAsTexture()
  46468. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46469. __decorate([
  46470. BABYLON.serializeAsColor3("ambient")
  46471. ], PBRMaterial.prototype, "ambientColor", void 0);
  46472. __decorate([
  46473. BABYLON.serializeAsColor3("albedo")
  46474. ], PBRMaterial.prototype, "albedoColor", void 0);
  46475. __decorate([
  46476. BABYLON.serializeAsColor3("reflectivity")
  46477. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46478. __decorate([
  46479. BABYLON.serializeAsColor3("reflection")
  46480. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46481. __decorate([
  46482. BABYLON.serializeAsColor3("emissive")
  46483. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46484. __decorate([
  46485. BABYLON.serialize()
  46486. ], PBRMaterial.prototype, "microSurface", void 0);
  46487. __decorate([
  46488. BABYLON.serialize()
  46489. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46490. __decorate([
  46491. BABYLON.serialize()
  46492. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46493. __decorate([
  46494. BABYLON.serializeAsFresnelParameters()
  46495. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  46496. __decorate([
  46497. BABYLON.serializeAsFresnelParameters()
  46498. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  46499. __decorate([
  46500. BABYLON.serialize()
  46501. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46502. __decorate([
  46503. BABYLON.serialize()
  46504. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  46505. __decorate([
  46506. BABYLON.serialize()
  46507. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46508. __decorate([
  46509. BABYLON.serialize()
  46510. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  46511. __decorate([
  46512. BABYLON.serialize()
  46513. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46514. __decorate([
  46515. BABYLON.serialize()
  46516. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46517. __decorate([
  46518. BABYLON.serialize()
  46519. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46520. __decorate([
  46521. BABYLON.serialize()
  46522. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46523. __decorate([
  46524. BABYLON.serialize()
  46525. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  46526. __decorate([
  46527. BABYLON.serialize()
  46528. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46529. __decorate([
  46530. BABYLON.serialize()
  46531. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46532. __decorate([
  46533. BABYLON.serialize()
  46534. ], PBRMaterial.prototype, "useParallax", void 0);
  46535. __decorate([
  46536. BABYLON.serialize()
  46537. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46538. __decorate([
  46539. BABYLON.serialize()
  46540. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46541. __decorate([
  46542. BABYLON.serialize()
  46543. ], PBRMaterial.prototype, "disableLighting", void 0);
  46544. __decorate([
  46545. BABYLON.serialize()
  46546. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  46547. return PBRMaterial;
  46548. })(BABYLON.Material);
  46549. BABYLON.PBRMaterial = PBRMaterial;
  46550. })(BABYLON || (BABYLON = {}));
  46551. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0 ,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0 ,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  46552. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,vec3(1.,1.,1.));\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\nfloat computeLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\nreturn lightDistanceFalloff;\n#else\nfloat lightFalloff=max(0.,1.0-length(lightOffset)/range);\nreturn lightFalloff;\n#endif\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(lightOffset);\n\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\n\nattenuation*=cosAngle;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  46553. 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)},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)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=c,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new s(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,b=-(s*v-e*g+h*T),F=1/(i*R+n*_+r*M+o*b),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,D=e*y-h*m,E=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*P)*F,t.m[6]=-(i*A-r*Z+o*C)*F,t.m[10]=(i*L-n*Z+o*S)*F,t.m[14]=-(i*P-n*C+r*S)*F,t.m[3]=-(n*I-r*q+o*D)*F,t.m[7]=(i*I-r*E+o*V)*F,t.m[11]=-(i*q-n*E+o*W)*F,t.m[15]=(i*D-n*V+r*W)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new s(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*F+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*b+s*P+e*I,i[n+4]=h*v+a*R+u*F+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*b+u*P+m*I,i[n+8]=y*v+c*R+p*F+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*b+p*P+f*I,i[n+12]=l*v+x*R+z*F+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*b+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new e(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){\nvar o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);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},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),s=0;16>s;s++)o.m[s]=i.m[s]*r+n.m[s]*(1-r);return o},t.DecomposeLerp=function(i,n,r){var o=new s(0,0,0),e=new a,h=new s(0,0,0);i.decompose(o,e,h);var u=new s(0,0,0),m=new a,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=a.Slerp(e,m,r),f=s.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=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=x;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.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?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(e,h,a),m=u.angle.radians()/s;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=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,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  46554. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  46555. module.exports = BABYLON;
  46556. };